cache.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /**
  2. * SessionProjectionCache behavior: mandatory-point writes (turn/end, detach),
  3. * count/interval throttling between them, fail-soft durability (a failed
  4. * write logs and stays stale, never throws into the event path), and the
  5. * cold-read ladder (cached row + readFrom tail + registry restore +
  6. * write-back; version bump and shrunk-log rows degrade to a full re-read).
  7. */
  8. import { afterEach, describe, expect, it, vi } from 'vitest'
  9. import { Context } from '@deepseek-ai/cordis'
  10. import { z } from 'zod'
  11. import Storage from '@deepseek-ai/dsh-storage'
  12. import { DomainFacility } from '@deepseek-ai/dsh-storage-domain'
  13. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  14. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  15. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  16. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  17. import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts'
  18. import SessionProjectionCache from '../src/index.ts'
  19. declare module '@deepseek-ai/dsh-session-projection/types' {
  20. interface SessionProjectionMap {
  21. 'cache-test/marks': { marks: string[] }
  22. }
  23. }
  24. declare module '@deepseek-ai/dsh-session/types' {
  25. interface SessionEventMap {
  26. 'cache-test/mark': { marks: string[] }
  27. }
  28. interface OutOfBandSessionEventMap {
  29. 'cache-test/mark': true
  30. }
  31. }
  32. type MarksState = { marks: string[] } | null
  33. const marksUnit = (stateVersion = 1): ProjectionDefinition<'cache-test/marks', MarksState> => ({
  34. key: 'cache-test/marks',
  35. schema: z.object({ marks: z.array(z.string()) }),
  36. init: () => null,
  37. apply: (state, event) => (event.type === 'cache-test/mark' ? (event).data : state),
  38. view: state => state ?? { marks: [] },
  39. stateVersion,
  40. })
  41. /** A persistence double serving readFrom over a fixed per-id stored log (headers stamp createdAt 0). */
  42. function fakePersistence(logs: Map<string, SessionEvent[]>) {
  43. const readFrom = vi.fn(async (id: SessionId, fromSeq: number) => {
  44. const events = logs.get(String(id))
  45. if (events === undefined) throw new Error(`session "${id}" not found`)
  46. return {
  47. meta: { version: 0, id, createdAt: 0 },
  48. events: events.filter(event => event.seq >= fromSeq),
  49. }
  50. })
  51. return { readFrom }
  52. }
  53. /** Header shape for cachedSnapshot calls (fake logs stamp createdAt 0, no cwd). */
  54. const headerOf = (id: SessionId, createdAt = 0, cwd?: string) =>
  55. ({ version: 0, id, createdAt, ...cwd === undefined ? {} : { cwd } })
  56. interface HarnessOptions {
  57. pool?: MemoryMediaPool
  58. config?: { writeEveryEvents: number; writeIntervalMs: number }
  59. stateVersion?: number
  60. logs?: Map<string, SessionEvent[]>
  61. }
  62. const contexts: Context[] = []
  63. async function harness(options: HarnessOptions = {}) {
  64. const pool = options.pool ?? new MemoryMediaPool()
  65. const logs = options.logs ?? new Map<string, SessionEvent[]>()
  66. const ctx = new Context()
  67. contexts.push(ctx)
  68. await ctx.plugin(Storage)
  69. ctx.storage.backend.register('memory', new MemoryStorageBackend(pool))
  70. const facility = new DomainFacility(ctx, { backend: 'memory', routes: {} })
  71. ctx.storage.mount('domain', facility)
  72. ctx.provide('storageDomain', facility)
  73. await ctx.plugin(SessionStore)
  74. await ctx.plugin(SessionProjectionRegistry)
  75. ctx.sessionProjections.register(marksUnit(options.stateVersion))
  76. const persistence = fakePersistence(logs)
  77. ctx.provide('sessionPersistence', persistence as never)
  78. const fiber = await ctx.plugin(SessionProjectionCache, options.config ?? { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  79. return { ctx, pool, logs, fiber, persistence, cache: ctx.sessionProjectionCache }
  80. }
  81. const mark = (session: Session, marks: string[]): SessionEvent =>
  82. session.append('cache-test/mark', { marks })
  83. const endTurn = (session: Session): SessionEvent =>
  84. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  85. /** The stored medium record for one session id (undefined = never written). */
  86. function storedRecord(pool: MemoryMediaPool, id: Session['id']) {
  87. return pool.media.get('session_projcache')?.tables.get('sessions')?.get(String(id)) as
  88. {
  89. identity: { createdAt: number; cwd?: string }
  90. rows: Record<string, { ver: number; seq: number; val: unknown }>
  91. } | undefined
  92. }
  93. /** The stored medium rows for one session id (undefined = never written). */
  94. function storedRows(pool: MemoryMediaPool, id: Session['id']) {
  95. return storedRecord(pool, id)?.rows
  96. }
  97. /** Wait until queued fail-soft writes (event-listener fire-and-forget) drain. */
  98. const settle = () => new Promise(resolve => setTimeout(resolve, 0))
  99. afterEach(async () => {
  100. vi.useRealTimers()
  101. await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose()))
  102. })
  103. describe('SessionProjectionCache write policy', () => {
  104. it('writes a durable checkpoint at turn/end (mandatory point)', async () => {
  105. const { ctx, pool } = await harness()
  106. const session = ctx.sessions.create(SessionId('turn-end'))
  107. mark(session, ['a'])
  108. expect(storedRows(pool, session.id)).toBeUndefined() // throttled: no write yet
  109. const end = endTurn(session)
  110. await settle()
  111. const rows = storedRows(pool, session.id)
  112. expect(rows?.['cache-test/marks']).toEqual({ ver: 1, seq: end.seq, val: { marks: ['a'] } })
  113. })
  114. it('writes at session disposal (detach, the live-to-cold moment)', async () => {
  115. const { ctx, pool } = await harness()
  116. // Sessions dispose with their owning fiber: create in a child plugin.
  117. let session: Session | undefined
  118. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  119. session = inner.sessions.create(SessionId('detach'))
  120. }, { inject: ['sessions'] }))
  121. if (session === undefined) throw new Error('session was not created')
  122. mark(session, ['live'])
  123. await owner.dispose()
  124. await settle()
  125. expect(storedRows(pool, session.id)?.['cache-test/marks']?.val).toEqual({ marks: ['live'] })
  126. })
  127. it('flushes when the in-turn event count reaches the configured threshold', async () => {
  128. const { ctx, pool } = await harness({ config: { writeEveryEvents: 3, writeIntervalMs: 60_000 } })
  129. const session = ctx.sessions.create(SessionId('count'))
  130. mark(session, ['1'])
  131. mark(session, ['2'])
  132. await settle()
  133. expect(storedRows(pool, session.id)).toBeUndefined()
  134. mark(session, ['3'])
  135. await settle()
  136. expect(storedRows(pool, session.id)?.['cache-test/marks']?.val).toEqual({ marks: ['3'] })
  137. })
  138. it('flushes on the configured interval when the count threshold is not reached', async () => {
  139. vi.useFakeTimers()
  140. const { ctx, pool } = await harness({ config: { writeEveryEvents: 100, writeIntervalMs: 250 } })
  141. const session = ctx.sessions.create(SessionId('interval'))
  142. mark(session, ['slow'])
  143. await vi.advanceTimersByTimeAsync(249)
  144. expect(storedRows(pool, session.id)).toBeUndefined()
  145. await vi.advanceTimersByTimeAsync(1)
  146. await vi.advanceTimersByTimeAsync(0)
  147. expect(storedRows(pool, session.id)?.['cache-test/marks']?.val).toEqual({ marks: ['slow'] })
  148. })
  149. it('write() on a never-dirty session checkpoints directly and rejects a non-JSON unit state', async () => {
  150. const { ctx, pool } = await harness()
  151. // Never dirtied: no events — write() still lands the init-derived cut.
  152. const clean = ctx.sessions.create(SessionId('clean-write'))
  153. await ctx.sessionProjectionCache.write(clean)
  154. expect(storedRows(pool, clean.id)?.['cache-test/marks']).toEqual({ ver: 1, seq: -1, val: null })
  155. // A unit whose state violates the plain-JSON contract fails the write loud.
  156. ctx.sessionProjections.register({
  157. key: 'cache-test/marks2' as never,
  158. schema: { parse: (value: unknown) => value } as never,
  159. init: () => new Map<string, string>(),
  160. apply: (state: unknown) => state,
  161. view: () => null as never,
  162. stateVersion: 1,
  163. })
  164. await expect(ctx.sessionProjectionCache.write(clean)).rejects.toThrow('not losslessly JSON-serializable')
  165. })
  166. it('plugin disposal clears armed interval timers and leaves cleaned sessions alone', async () => {
  167. vi.useFakeTimers()
  168. const { ctx, pool, fiber } = await harness({ config: { writeEveryEvents: 100, writeIntervalMs: 5000 } })
  169. const armed = ctx.sessions.create(SessionId('armed'))
  170. const cleaned = ctx.sessions.create(SessionId('cleaned'))
  171. mark(armed, ['pending']) // timer armed, no write yet
  172. mark(cleaned, ['done'])
  173. endTurn(cleaned) // mandatory write; markClean leaves {pending: 0, timer: undefined} in the map
  174. await vi.advanceTimersByTimeAsync(0)
  175. await fiber.dispose()
  176. // The armed timer died with the plugin: advancing time writes nothing.
  177. await vi.advanceTimersByTimeAsync(10_000)
  178. expect(storedRows(pool, armed.id)).toBeUndefined()
  179. })
  180. it('contains a durable write failure: logs a warning, event path unharmed, next write self-heals', async () => {
  181. const { ctx, pool } = await harness()
  182. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  183. const session = ctx.sessions.create(SessionId('fail-soft'))
  184. mark(session, ['x'])
  185. pool.failNextWrites = 1
  186. endTurn(session)
  187. await settle()
  188. expect(storedRows(pool, session.id)).toBeUndefined()
  189. expect(warn).toHaveBeenCalledWith(expect.stringContaining('turn/end write for "fail-soft" failed'))
  190. // Self-heal: the next mandatory point writes the current cut.
  191. mark(session, ['y'])
  192. endTurn(session)
  193. await settle()
  194. expect(storedRows(pool, session.id)?.['cache-test/marks']?.val).toEqual({ marks: ['y'] })
  195. })
  196. })
  197. describe('SessionProjectionCache cold read', () => {
  198. const storedLog = (marks: string[][]): SessionEvent[] => {
  199. const events: SessionEvent[] = [
  200. { type: 'turn/start', seq: 0, time: 0, data: { turn: 1 } },
  201. ]
  202. for (const m of marks) {
  203. events.push({ type: 'cache-test/mark', seq: events.length, time: events.length, data: { marks: m } })
  204. }
  205. events.push({ type: 'turn/end', seq: events.length, time: events.length, data: { turn: 1, reason: { kind: 'completed' } } })
  206. return events
  207. }
  208. /** Pre-seed the medium with one stored checkpoint record (before the domain opens). */
  209. function seedRow(
  210. pool: MemoryMediaPool,
  211. id: string,
  212. row: { ver: number; seq: number; val: unknown },
  213. identity: { createdAt: number; cwd?: string } = { createdAt: 0 },
  214. ): void {
  215. pool.versions.set('session_projcache', 3)
  216. pool.media.set('session_projcache', {
  217. tables: new Map([['sessions', new Map([[id, { identity, rows: { 'cache-test/marks': row } }]])]]),
  218. global: null,
  219. })
  220. }
  221. it('serves a cold session from the cache row plus a bounded tail read, and writes the refresh back', async () => {
  222. const pool = new MemoryMediaPool()
  223. const logs = new Map([['cold', storedLog([['a'], ['a', 'b']])]])
  224. // A warm-era checkpoint at watermark 1 (only ['a'] folded).
  225. seedRow(pool, 'cold', { ver: 1, seq: 1, val: { marks: ['a'] } })
  226. const { cache, persistence, pool: samePool } = await harness({ pool, logs })
  227. const id = SessionId('cold')
  228. const snapshot = await cache.coldSnapshot(id)
  229. expect(snapshot.values['cache-test/marks']).toEqual({ marks: ['a', 'b'] })
  230. expect(snapshot.asOfSeq).toBe(3)
  231. // The tail read was bounded by the anchored floor (watermark 1 -> floor 1), not 0.
  232. expect(persistence.readFrom).toHaveBeenCalledWith(id, 1, undefined)
  233. // Write-back: the stored row advanced to the served cut.
  234. expect(storedRows(samePool, id)?.['cache-test/marks'])
  235. .toEqual({ ver: 1, seq: 3, val: { marks: ['a', 'b'] } })
  236. })
  237. it('discards a version-mismatched row and refolds the full log', async () => {
  238. const pool = new MemoryMediaPool()
  239. const logs = new Map([['bumped', storedLog([['a']])]])
  240. seedRow(pool, 'bumped', { ver: 1, seq: 2, val: { marks: ['stale'] } })
  241. const { cache, persistence } = await harness({ pool, logs, stateVersion: 2 })
  242. const snapshot = await cache.coldSnapshot(SessionId('bumped'))
  243. expect(snapshot.values['cache-test/marks']).toEqual({ marks: ['a'] })
  244. // Mismatch pulls the floor to 0: one full read, no second pass needed.
  245. expect(persistence.readFrom).toHaveBeenCalledTimes(1)
  246. expect(persistence.readFrom).toHaveBeenCalledWith(SessionId('bumped'), 0, undefined)
  247. })
  248. it('detects a log shrunk below the row watermark and degrades to one full re-read', async () => {
  249. const pool = new MemoryMediaPool()
  250. const logs = new Map([['shrunk', storedLog([['a']])]]) // seqs 0..2
  251. seedRow(pool, 'shrunk', { ver: 1, seq: 9, val: { marks: ['ghost'] } })
  252. const { cache, persistence } = await harness({ pool, logs })
  253. const snapshot = await cache.coldSnapshot(SessionId('shrunk'))
  254. expect(snapshot.values['cache-test/marks']).toEqual({ marks: ['a'] })
  255. expect(snapshot.asOfSeq).toBe(2)
  256. // Anchored tail read (floor 9) came back empty -> full re-read from 0.
  257. expect(persistence.readFrom).toHaveBeenNthCalledWith(1, SessionId('shrunk'), 9, undefined)
  258. expect(persistence.readFrom).toHaveBeenNthCalledWith(2, SessionId('shrunk'), 0, undefined)
  259. })
  260. it('write-back failure is contained: the snapshot is still served', async () => {
  261. const pool = new MemoryMediaPool()
  262. const logs = new Map([['soft', storedLog([['a']])]])
  263. const { ctx, cache } = await harness({ pool, logs })
  264. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  265. pool.failNextWrites = 1
  266. const snapshot = await cache.coldSnapshot(SessionId('soft'))
  267. expect(snapshot.values['cache-test/marks']).toEqual({ marks: ['a'] })
  268. expect(warn).toHaveBeenCalledWith(expect.stringContaining('cold-read write-back for "soft" failed'))
  269. })
  270. it('rejects for a session with no persisted log', async () => {
  271. const { cache } = await harness()
  272. await expect(cache.coldSnapshot(SessionId('absent'))).rejects.toThrow('not found')
  273. })
  274. it('discards a record bound to a different log lifecycle and refolds from the actual log', async () => {
  275. const pool = new MemoryMediaPool()
  276. const logs = new Map([['reborn', storedLog([['real']])]]) // stored header stamps createdAt 0
  277. // A checkpoint from a PRIOR lifecycle of the same id (different createdAt):
  278. // its rows pass every watermark check, but the identity does not match.
  279. seedRow(pool, 'reborn', { ver: 1, seq: 2, val: { marks: ['phantom'] } }, { createdAt: 999 })
  280. const { cache, pool: samePool } = await harness({ pool, logs })
  281. const snapshot = await cache.coldSnapshot(SessionId('reborn'))
  282. expect(snapshot.values['cache-test/marks']).toEqual({ marks: ['real'] })
  283. // The write-back rebinds the record to the actual log's identity.
  284. expect(storedRecord(samePool, SessionId('reborn'))?.identity).toEqual({ createdAt: 0 })
  285. })
  286. it('cachedSnapshot returns undefined when every stored row is version-mismatched', async () => {
  287. const pool = new MemoryMediaPool()
  288. seedRow(pool, 'all-stale', { ver: 99, seq: 4, val: { marks: ['old'] } })
  289. const { cache } = await harness({ pool })
  290. expect(cache.cachedSnapshot(headerOf(SessionId('all-stale')))).toBeUndefined()
  291. })
  292. it('binds identity on cwd too: a matching cwd serves, a moved session does not', async () => {
  293. const pool = new MemoryMediaPool()
  294. seedRow(pool, 'homed', { ver: 1, seq: 2, val: { marks: ['w'] } }, { createdAt: 0, cwd: '/work' })
  295. const { cache } = await harness({ pool })
  296. const id = SessionId('homed')
  297. expect(cache.cachedSnapshot(headerOf(id, 0, '/work'))?.values['cache-test/marks']).toEqual({ marks: ['w'] })
  298. expect(cache.cachedSnapshot(headerOf(id, 0, '/elsewhere'))).toBeUndefined()
  299. expect(cache.cachedSnapshot(headerOf(id, 0))).toBeUndefined()
  300. })
  301. it('dates an empty stored log at -1 in the zero-units topology', async () => {
  302. const pool = new MemoryMediaPool()
  303. const logs = new Map([['empty', [] as SessionEvent[]]])
  304. const ctx = new Context()
  305. contexts.push(ctx)
  306. await ctx.plugin(Storage)
  307. ctx.storage.backend.register('memory', new MemoryStorageBackend(pool))
  308. const facility = new DomainFacility(ctx, { backend: 'memory', routes: {} })
  309. ctx.storage.mount('domain', facility)
  310. ctx.provide('storageDomain', facility)
  311. await ctx.plugin(SessionStore)
  312. await ctx.plugin(SessionProjectionRegistry)
  313. ctx.provide('sessionPersistence', fakePersistence(logs) as never)
  314. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  315. await expect(ctx.sessionProjectionCache.coldSnapshot(SessionId('empty')))
  316. .resolves.toEqual({ asOfSeq: -1, values: {} })
  317. })
  318. it('cachedSnapshot serves identity-matching rows with the cut watermark and refuses unrelated ones', async () => {
  319. const pool = new MemoryMediaPool()
  320. seedRow(pool, 'listed', { ver: 1, seq: 4, val: { marks: ['t'] } })
  321. const { cache } = await harness({ pool })
  322. const id = SessionId('listed')
  323. // Matching header: values plus the watermark the client seeds under.
  324. expect(cache.cachedSnapshot(headerOf(id))).toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['t'] } } })
  325. // A recreated id (different createdAt): the record is unrelated — no block.
  326. expect(cache.cachedSnapshot(headerOf(id, 777))).toBeUndefined()
  327. // Unknown id: no block.
  328. expect(cache.cachedSnapshot(headerOf(SessionId('never-cached')))).toBeUndefined()
  329. })
  330. it('holds the not-found contract with zero registered units, and dates the empty cut for a present log', async () => {
  331. // Same composition minus any registered unit: restoreFloor is undefined,
  332. // yet coldSnapshot must still reject for an absent log (probe read) and
  333. // serve an empty cut at the stored end for a present one.
  334. const pool = new MemoryMediaPool()
  335. const logs = new Map([['bare', storedLog([['a']])]]) // seqs 0..2
  336. const ctx = new Context()
  337. contexts.push(ctx)
  338. await ctx.plugin(Storage)
  339. ctx.storage.backend.register('memory', new MemoryStorageBackend(pool))
  340. const facility = new DomainFacility(ctx, { backend: 'memory', routes: {} })
  341. ctx.storage.mount('domain', facility)
  342. ctx.provide('storageDomain', facility)
  343. await ctx.plugin(SessionStore)
  344. await ctx.plugin(SessionProjectionRegistry)
  345. ctx.provide('sessionPersistence', fakePersistence(logs) as never)
  346. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  347. await expect(ctx.sessionProjectionCache.coldSnapshot(SessionId('absent'))).rejects.toThrow('not found')
  348. await expect(ctx.sessionProjectionCache.coldSnapshot(SessionId('bare')))
  349. .resolves.toEqual({ asOfSeq: 2, values: {} })
  350. })
  351. })