cache.spec.ts 20 KB

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