cache.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. * synchronous cached listing read. The durable medium is the
  6. * `session_projcache` storage domain in per-record layout: one
  7. * version-stamped document per session under the json backend root at
  8. * `<root>/session_projcache/sessions/<id>.json`. Reads never touch the
  9. * medium — they come from the domain's in-memory tables, which writes mutate
  10. * only after durability.
  11. */
  12. import { afterEach, describe, expect, it, vi } from 'vitest'
  13. import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  14. import { tmpdir } from 'node:os'
  15. import { dirname, join } from 'node:path'
  16. import { Context } from '@deepseek-ai/cordis'
  17. import { z } from 'zod'
  18. import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
  19. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  20. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  21. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  22. import Storage from '@deepseek-ai/dsh-storage'
  23. import {
  24. apply as storageJsonApply, Config as storageJsonConfig, inject as storageJsonInject, name as storageJsonName,
  25. } from '@deepseek-ai/dsh-storage-json'
  26. import {
  27. apply as storageDomainApply, Config as storageDomainConfig, inject as storageDomainInject, name as storageDomainName,
  28. } from '@deepseek-ai/dsh-storage-domain'
  29. import SessionProjectionCache from '../src/index.ts'
  30. import { checkpointRecord, projectionCacheDomainSpec } from '../src/spec.ts'
  31. import type { CheckpointRecord } from '../src/spec.ts'
  32. declare module '@deepseek-ai/dsh-session-projection/types' {
  33. interface SessionProjectionStateMap {
  34. 'cache-test/marks': MarksState
  35. 'cache-test/marks2': Map<string, string>
  36. 'cache-test/count': number
  37. 'cache-test/secret': string
  38. }
  39. interface SessionProjectionMap {
  40. 'cache-test/marks': { marks: string[] }
  41. }
  42. }
  43. declare module '@deepseek-ai/dsh-session/types' {
  44. interface SessionEventMap {
  45. 'cache-test/mark': { marks: string[] }
  46. }
  47. interface OutOfBandSessionEventMap {
  48. 'cache-test/mark': true
  49. }
  50. }
  51. type MarksState = { marks: string[] } | null
  52. const marksUnit = (stateVersion = 1) => ({
  53. key: 'cache-test/marks',
  54. stateSchema: z.object({ marks: z.array(z.string()) }).nullable(),
  55. init: () => null,
  56. apply: (state, event) => (event.type === 'cache-test/mark' ? (event).data : state),
  57. wire: {
  58. viewSchema: z.object({ marks: z.array(z.string()) }),
  59. view: state => state ?? { marks: [] },
  60. },
  61. stateVersion,
  62. }) satisfies ProjectionDefinition<'cache-test/marks', MarksState>
  63. const secretUnit = {
  64. key: 'cache-test/secret',
  65. stateSchema: z.string(),
  66. init: () => '',
  67. apply: state => state,
  68. stateVersion: 1,
  69. } satisfies ProjectionDefinition<'cache-test/secret', string>
  70. /** One session's record document on the per-record medium. */
  71. const recordPath = (root: string, id: Session['id']): string =>
  72. join(root, projectionCacheDomainSpec.name, 'sessions', `${String(id)}.json`)
  73. /** Header shape for cachedSnapshot calls. */
  74. const headerOf = (id: SessionId, createdAt = 0, cwd?: string) =>
  75. ({ version: 0, id, createdAt, ...cwd === undefined ? {} : { cwd } })
  76. interface HarnessOptions {
  77. root?: string
  78. config?: { writeEveryEvents: number; writeIntervalMs: number }
  79. stateVersion?: number
  80. }
  81. const contexts: Context[] = []
  82. const roots: string[] = []
  83. async function harness(options: HarnessOptions = {}) {
  84. const root = options.root ?? await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  85. roots.push(root)
  86. const ctx = new Context()
  87. contexts.push(ctx)
  88. // The cache opens its domain through the storage stack; the json backend
  89. // lands the per-record tree under this tmp root.
  90. await ctx.plugin(Storage)
  91. await ctx.plugin({ name: storageJsonName, inject: storageJsonInject, apply: storageJsonApply, Config: storageJsonConfig }, { root })
  92. await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
  93. await ctx.plugin(SessionStore)
  94. await ctx.plugin(SessionProjectionRegistry)
  95. ctx.sessionProjections.register(marksUnit(options.stateVersion))
  96. const fiber = await ctx.plugin(SessionProjectionCache, options.config ?? { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  97. return { ctx, root, fiber, cache: ctx.sessionProjectionCache }
  98. }
  99. const mark = (session: Session, marks: string[]): SessionEvent =>
  100. session.append('cache-test/mark', { marks })
  101. const endTurn = (session: Session): SessionEvent =>
  102. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  103. /** The stored record for one session id (undefined = absent or unreadable). */
  104. async function storedRecord(root: string, id: Session['id']): Promise<CheckpointRecord | undefined> {
  105. try {
  106. const document = JSON.parse(await readFile(recordPath(root, id), 'utf8')) as { record: unknown }
  107. return checkpointRecord.parse(document.record)
  108. } catch {
  109. return undefined
  110. }
  111. }
  112. /** The stored rows for one session id (undefined = absent or unreadable). */
  113. async function storedRows(root: string, id: Session['id']): Promise<CheckpointRecord['rows'] | undefined> {
  114. return (await storedRecord(root, id))?.rows
  115. }
  116. /** Pre-seed one session's record document with a stored checkpoint record. */
  117. async function seedRecord(
  118. root: string,
  119. id: string,
  120. rows: CheckpointRecord['rows'],
  121. identity: CheckpointRecord['identity'] = { createdAt: 0 },
  122. ): Promise<void> {
  123. const path = recordPath(root, SessionId(id))
  124. await mkdir(dirname(path), { recursive: true })
  125. await writeFile(path, JSON.stringify({ version: projectionCacheDomainSpec.version, record: { identity, rows } }))
  126. }
  127. afterEach(async () => {
  128. vi.useRealTimers()
  129. await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose()))
  130. await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })))
  131. })
  132. describe('SessionProjectionCache write policy', () => {
  133. it('writes a durable checkpoint at turn/end (mandatory point)', async () => {
  134. const { ctx, root } = await harness()
  135. const session = ctx.sessions.create(SessionId('turn-end'))
  136. mark(session, ['a'])
  137. // Creation already wrote the init cut; the mark is throttled, so the
  138. // stored row is still the creation-time cut (no marks folded).
  139. await vi.waitFor(async () => {
  140. expect((await storedRows(root, session.id))?.['cache-test/marks']?.seq).toBe(-1)
  141. }, { timeout: 5_000 })
  142. const end = endTurn(session)
  143. await vi.waitFor(async () => {
  144. expect((await storedRows(root, session.id))?.['cache-test/marks'])
  145. .toEqual({ ver: 1, seq: end.seq, val: { marks: ['a'] } })
  146. }, { timeout: 5_000 })
  147. })
  148. it('writes a checkpoint at session creation, capturing the seed-derived cut', async () => {
  149. const { ctx, root } = await harness()
  150. // A forked child seeded with its ancestor's title-like event: no
  151. // conversation follows, yet the creation write must capture the fold so
  152. // a crash or a live-held fork still lists the derived value.
  153. const session = ctx.sessions.create(SessionId('seeded'), {
  154. seed: [{ type: 'cache-test/mark', seq: 0, time: 1, data: { marks: ['seed'] } }] as SessionEvent[],
  155. })
  156. await vi.waitFor(async () => {
  157. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val)
  158. .toEqual({ marks: ['seed'] })
  159. }, { timeout: 5_000 })
  160. })
  161. it('writes at session disposal (detach, the live-to-cold moment)', async () => {
  162. const { ctx, root } = await harness()
  163. // Sessions dispose with their owning fiber: create in a child plugin.
  164. let session: Session | undefined
  165. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  166. session = inner.sessions.create(SessionId('detach'))
  167. }, { inject: ['sessions'] }))
  168. if (session === undefined) throw new Error('session was not created')
  169. mark(session, ['live'])
  170. await owner.dispose()
  171. const detached = session
  172. await vi.waitFor(async () => {
  173. expect((await storedRows(root, detached.id))?.['cache-test/marks']?.val).toEqual({ marks: ['live'] })
  174. }, { timeout: 5_000 })
  175. })
  176. it('flushes when the in-turn event count reaches the configured threshold', async () => {
  177. const { ctx, root } = await harness({ config: { writeEveryEvents: 3, writeIntervalMs: 60_000 } })
  178. const session = ctx.sessions.create(SessionId('count'))
  179. mark(session, ['1'])
  180. mark(session, ['2'])
  181. await vi.waitFor(async () => {
  182. expect((await storedRows(root, session.id))?.['cache-test/marks']?.seq).toBe(-1) // still the creation cut
  183. }, { timeout: 5_000 })
  184. mark(session, ['3'])
  185. await vi.waitFor(async () => {
  186. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val).toEqual({ marks: ['3'] })
  187. }, { timeout: 5_000 })
  188. })
  189. it('flushes on the configured interval when the count threshold is not reached', async () => {
  190. const { ctx, cache } = await harness({ config: { writeEveryEvents: 100, writeIntervalMs: 20 } })
  191. const write = vi.spyOn(cache, 'write').mockResolvedValue()
  192. vi.useFakeTimers()
  193. const session = ctx.sessions.create(SessionId('interval'))
  194. write.mockClear()
  195. mark(session, ['slow'])
  196. await vi.advanceTimersByTimeAsync(19)
  197. expect(write).not.toHaveBeenCalled()
  198. await vi.advanceTimersByTimeAsync(1)
  199. expect(write).toHaveBeenCalledExactlyOnceWith(session)
  200. })
  201. it('write() on a never-dirty session checkpoints directly and rejects a non-JSON unit state', async () => {
  202. const { ctx, root } = await harness()
  203. // Never dirtied: no events — write() still lands the init-derived cut.
  204. const clean = ctx.sessions.create(SessionId('clean-write'))
  205. await ctx.sessionProjectionCache.write(clean)
  206. expect((await storedRows(root, clean.id))?.['cache-test/marks']).toEqual({ ver: 1, seq: -1, val: null })
  207. // A unit whose state violates the plain-JSON contract fails the write loud.
  208. ctx.sessionProjections.register({
  209. key: 'cache-test/marks2',
  210. stateSchema: z.custom<Map<string, string>>(() => true),
  211. init: () => new Map<string, string>(),
  212. apply: state => state,
  213. stateVersion: 1,
  214. })
  215. await expect(ctx.sessionProjectionCache.write(clean)).rejects.toThrow('not losslessly JSON-serializable')
  216. })
  217. it('plugin disposal clears armed interval timers and leaves cleaned sessions alone', async () => {
  218. vi.useFakeTimers()
  219. const { ctx, root, fiber } = await harness({ config: { writeEveryEvents: 100, writeIntervalMs: 5000 } })
  220. const armed = ctx.sessions.create(SessionId('armed'))
  221. const cleaned = ctx.sessions.create(SessionId('cleaned'))
  222. mark(armed, ['pending']) // timer armed, no write yet
  223. mark(cleaned, ['done'])
  224. endTurn(cleaned) // mandatory write; markClean leaves {pending: 0, timer: undefined} in the map
  225. await vi.advanceTimersByTimeAsync(0)
  226. await fiber.dispose()
  227. // The armed timer died with the plugin: advancing time writes nothing.
  228. await vi.advanceTimersByTimeAsync(10_000)
  229. // Only the creation cut exists: the armed mark never wrote.
  230. expect((await storedRows(root, armed.id))?.['cache-test/marks']?.seq).toBe(-1)
  231. })
  232. it('contains a durable write failure: logs a warning, event path unharmed, next write self-heals', async () => {
  233. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  234. roots.push(root)
  235. const ctx = new Context()
  236. contexts.push(ctx)
  237. await ctx.plugin(Storage)
  238. await ctx.plugin({ name: storageJsonName, inject: storageJsonInject, apply: storageJsonApply, Config: storageJsonConfig }, { root })
  239. await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
  240. await ctx.plugin(SessionStore)
  241. await ctx.plugin(SessionProjectionRegistry)
  242. ctx.sessionProjections.register(marksUnit())
  243. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  244. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  245. // A directory where the record document must land makes the atomic
  246. // rename fail — including the creation write, so no row ever lands.
  247. const blocker = recordPath(root, SessionId('fail-soft'))
  248. await mkdir(blocker, { recursive: true })
  249. const session = ctx.sessions.create(SessionId('fail-soft'))
  250. mark(session, ['x'])
  251. endTurn(session)
  252. // The failed creation/turn-end writes are fire-and-forget: wait for the
  253. // warn (the write actually failed), then assert no row landed — the
  254. // property under test is that a failed write leaves no partial row.
  255. await vi.waitFor(() => {
  256. expect(warn).toHaveBeenCalledWith(expect.stringContaining('turn/end write for "fail-soft" failed'))
  257. }, { timeout: 5_000 })
  258. await vi.waitFor(async () => {
  259. expect(await storedRows(root, session.id)).toBeUndefined()
  260. }, { timeout: 5_000 })
  261. // Self-heal: once the blocker clears, the next mandatory point writes.
  262. await rm(recordPath(root, session.id), { recursive: true })
  263. mark(session, ['y'])
  264. endTurn(session)
  265. await vi.waitFor(async () => {
  266. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val).toEqual({ marks: ['y'] })
  267. }, { timeout: 5_000 })
  268. })
  269. })
  270. describe('SessionProjectionCache listing read', () => {
  271. it('keeps host-only checkpoint state out of cached wire snapshots', async () => {
  272. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  273. roots.push(root)
  274. await seedRecord(root, 'host-state', {
  275. 'cache-test/marks': { ver: 1, seq: 4, val: { marks: ['wire'] } },
  276. 'cache-test/secret': { ver: 1, seq: 4, val: 'private prompt text' },
  277. })
  278. const { ctx, cache } = await harness({ root })
  279. ctx.sessionProjections.register(secretUnit)
  280. const header = headerOf(SessionId('host-state'))
  281. expect(cache.cachedSnapshot(header)).toEqual({
  282. asOfSeq: 4,
  283. values: { 'cache-test/marks': { marks: ['wire'] } },
  284. })
  285. expect(JSON.stringify(cache.cachedSnapshot(header))).not.toContain('private prompt text')
  286. })
  287. it('serves identity-matching rows with the cut watermark and refuses unrelated ones', async () => {
  288. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  289. roots.push(root)
  290. await seedRecord(root, 'listed', { 'cache-test/marks': { ver: 1, seq: 4, val: { marks: ['t'] } } })
  291. const { cache } = await harness({ root })
  292. const id = SessionId('listed')
  293. // Matching header: values plus the watermark the client seeds under.
  294. expect(cache.cachedSnapshot(headerOf(id))).toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['t'] } } })
  295. // A recreated id (different createdAt): the record is unrelated — no block.
  296. expect(cache.cachedSnapshot(headerOf(id, 777))).toBeUndefined()
  297. // Unknown id: no block.
  298. expect(cache.cachedSnapshot(headerOf(SessionId('never-cached')))).toBeUndefined()
  299. })
  300. it('returns undefined when the stored record is version-mismatched', async () => {
  301. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  302. roots.push(root)
  303. // A stale version-stamped document is discarded at open: absent record.
  304. const path = recordPath(root, SessionId('all-stale'))
  305. await mkdir(dirname(path), { recursive: true })
  306. await writeFile(path, JSON.stringify({
  307. version: projectionCacheDomainSpec.version + 1,
  308. record: { identity: { createdAt: 0 }, rows: { 'cache-test/marks': { ver: 1, seq: 4, val: { marks: ['old'] } } } },
  309. }))
  310. const { cache } = await harness({ root })
  311. expect(cache.cachedSnapshot(headerOf(SessionId('all-stale')))).toBeUndefined()
  312. })
  313. it('returns undefined when every stored row is version-mismatched', async () => {
  314. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  315. roots.push(root)
  316. // A current document whose rows all fail the live unit's stateVersion:
  317. // the listing view is empty, so no block is served.
  318. await seedRecord(root, 'row-stale', { 'cache-test/marks': { ver: 99, seq: 4, val: { marks: ['old'] } } })
  319. const { cache } = await harness({ root })
  320. expect(cache.cachedSnapshot(headerOf(SessionId('row-stale')))).toBeUndefined()
  321. })
  322. it('binds identity on cwd too: a matching cwd serves, a moved session does not', async () => {
  323. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  324. roots.push(root)
  325. await seedRecord(root, 'homed', { 'cache-test/marks': { ver: 1, seq: 2, val: { marks: ['w'] } } }, { createdAt: 0, cwd: '/work' })
  326. const { cache } = await harness({ root })
  327. const id = SessionId('homed')
  328. expect(cache.cachedSnapshot(headerOf(id, 0, '/work'))?.values['cache-test/marks']).toEqual({ marks: ['w'] })
  329. expect(cache.cachedSnapshot(headerOf(id, 0, '/elsewhere'))).toBeUndefined()
  330. expect(cache.cachedSnapshot(headerOf(id, 0))).toBeUndefined()
  331. })
  332. it('returns undefined for a malformed record document (refold from the log on the caller side)', async () => {
  333. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  334. roots.push(root)
  335. const path = recordPath(root, SessionId('malformed'))
  336. await mkdir(dirname(path), { recursive: true })
  337. await writeFile(path, 'not json at all')
  338. const { cache } = await harness({ root })
  339. expect(cache.cachedSnapshot(headerOf(SessionId('malformed')))).toBeUndefined()
  340. })
  341. })
  342. describe('SessionProjectionCache cold-read seeding', () => {
  343. /** One session's event log: turn/start, one mark per group, turn/end. */
  344. const storedLog = (marks: string[][]): SessionEvent[] => {
  345. const events: SessionEvent[] = [
  346. { type: 'turn/start', seq: 0, time: 0, data: { turn: 1 } },
  347. ]
  348. for (const m of marks) {
  349. events.push({ type: 'cache-test/mark', seq: events.length, time: events.length, data: { marks: m } })
  350. }
  351. events.push({ type: 'turn/end', seq: events.length, time: events.length, data: { turn: 1, reason: { kind: 'completed' } } })
  352. return events
  353. }
  354. it('hydratePrepared seeds from a matching row and retries from the exact log on a malformed one', async () => {
  355. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  356. roots.push(root)
  357. // Records land on disk before the domain opens, so the in-memory table
  358. // picks them up at init.
  359. await seedRecord(root, 'prepared-seeded', {
  360. 'cache-test/marks': { ver: 1, seq: 1, val: { marks: ['cached'] } },
  361. })
  362. await seedRecord(root, 'prepared-fallback', {
  363. 'cache-test/marks': { ver: 1, seq: 1, val: { marks: 'malformed' } },
  364. })
  365. const { cache } = await harness({ root })
  366. const events = storedLog([['fresh']])
  367. // A matching row hydrates the prepared Session without a persistence read.
  368. const seeded = headerOf(SessionId('prepared-seeded'))
  369. const seededSession = Session.create(seeded.id, events, seeded)
  370. expect(cache.hydratePrepared(seededSession, seeded, events)).toEqual({
  371. asOfSeq: 2,
  372. values: { 'cache-test/marks': { marks: ['cached'] } },
  373. })
  374. // A malformed row cannot seed the fold; hydration falls back to the
  375. // exact log so a valid Session stays readable.
  376. const fallback = headerOf(SessionId('prepared-fallback'))
  377. const fallbackSession = Session.create(fallback.id, events, fallback)
  378. expect(cache.hydratePrepared(fallbackSession, fallback, events)).toEqual({
  379. asOfSeq: 2,
  380. values: { 'cache-test/marks': { marks: ['fresh'] } },
  381. })
  382. // No row at all: hydrate from init over the exact log.
  383. const bare = headerOf(SessionId('prepared-bare'))
  384. const bareSession = Session.create(bare.id, events, bare)
  385. expect(cache.hydratePrepared(bareSession, bare, events)).toEqual({
  386. asOfSeq: 2,
  387. values: { 'cache-test/marks': { marks: ['fresh'] } },
  388. })
  389. })
  390. it('coldSnapshot traverses the full log but applies only the events after each cached watermark', async () => {
  391. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  392. roots.push(root)
  393. // A cached row covering the prefix through seq 2 (three applies folded).
  394. await seedRecord(root, 'cold-snap', {
  395. 'cache-test/count': { ver: 1, seq: 2, val: 3 },
  396. }, { createdAt: 9 })
  397. const { cache, ctx } = await harness({ root })
  398. const apply = vi.fn((_state: number, _event: SessionEvent) => 1)
  399. ctx.sessionProjections.register({
  400. key: 'cache-test/count',
  401. stateSchema: z.number().int().nonnegative(),
  402. init: () => 0,
  403. apply,
  404. stateVersion: 1,
  405. } satisfies ProjectionDefinition<'cache-test/count', number>)
  406. const meta = headerOf(SessionId('cold-snap'), 9)
  407. const events = Array.from({ length: 5 }, (_, seq) => ({
  408. type: 'cache-test/mark', seq, time: seq, data: { marks: [`m${seq}`] },
  409. })) as SessionEvent[]
  410. const snapshot = cache.coldSnapshot(meta, events)
  411. // The full log was traversed, but the fold applied only seqs 3 and 4.
  412. expect(apply).toHaveBeenCalledTimes(2)
  413. expect(apply.mock.calls.map(call => call[1].seq)).toEqual([3, 4])
  414. expect(snapshot.asOfSeq).toBe(4)
  415. // Host-only unit: folded but not served; the refreshed row is written
  416. // back (fail-soft, fire-and-forget) once the write lands.
  417. expect(Object.keys(snapshot.values)).not.toContain('cache-test/count')
  418. await vi.waitFor(async () => {
  419. expect((await storedRows(root, meta.id))?.['cache-test/count']?.seq).toBe(4)
  420. })
  421. // No cached row yet: the first cold read folds from init over the full
  422. // log and creates the cache row (the `?? {}` seed path).
  423. const fresh = headerOf(SessionId('cold-fresh'), 10)
  424. cache.coldSnapshot(fresh, events)
  425. expect(apply).toHaveBeenCalledTimes(7) // 2 tail + 5 full
  426. await vi.waitFor(async () => {
  427. expect((await storedRows(root, fresh.id))?.['cache-test/count']?.seq).toBe(4)
  428. })
  429. })
  430. it('coldSnapshot write-back is fail-soft: a failed durable write logs and never throws', async () => {
  431. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  432. roots.push(root)
  433. const ctx = new Context()
  434. contexts.push(ctx)
  435. await ctx.plugin(Storage)
  436. await ctx.plugin({ name: storageJsonName, inject: storageJsonInject, apply: storageJsonApply, Config: storageJsonConfig }, { root })
  437. await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
  438. await ctx.plugin(SessionStore)
  439. await ctx.plugin(SessionProjectionRegistry)
  440. ctx.sessionProjections.register(marksUnit())
  441. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  442. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  443. // A directory where the record document must land makes the write-back
  444. // fail; the cold read itself still succeeds and never throws.
  445. const meta = headerOf(SessionId('cold-fail'))
  446. await mkdir(recordPath(root, meta.id), { recursive: true })
  447. expect(ctx.sessionProjectionCache.coldSnapshot(meta, [])).toBeDefined()
  448. // The failed write-back is fire-and-forget: poll for the warn instead of
  449. // assuming a fixed settle window (slow runners exceed it).
  450. await vi.waitFor(() => {
  451. expect(warn).toHaveBeenCalledWith(expect.stringContaining('cold-read write-back for "cold-fail" failed'))
  452. }, { timeout: 5_000 })
  453. })
  454. })