cache.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. /** Wait until queued fail-soft writes (event-listener fire-and-forget over real fs I/O) drain. */
  128. const settle = () => new Promise(resolve => setTimeout(resolve, 40))
  129. afterEach(async () => {
  130. vi.useRealTimers()
  131. await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose()))
  132. await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })))
  133. })
  134. describe('SessionProjectionCache write policy', () => {
  135. it('writes a durable checkpoint at turn/end (mandatory point)', async () => {
  136. const { ctx, root } = await harness()
  137. const session = ctx.sessions.create(SessionId('turn-end'))
  138. mark(session, ['a'])
  139. // Creation already wrote the init cut; the mark is throttled, so the
  140. // stored row is still the creation-time cut (no marks folded).
  141. await settle()
  142. expect((await storedRows(root, session.id))?.['cache-test/marks']?.seq).toBe(-1)
  143. const end = endTurn(session)
  144. await settle()
  145. const rows = await storedRows(root, session.id)
  146. expect(rows?.['cache-test/marks']).toEqual({ ver: 1, seq: end.seq, val: { marks: ['a'] } })
  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 settle()
  157. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val)
  158. .toEqual({ marks: ['seed'] })
  159. })
  160. it('writes at session disposal (detach, the live-to-cold moment)', async () => {
  161. const { ctx, root } = await harness()
  162. // Sessions dispose with their owning fiber: create in a child plugin.
  163. let session: Session | undefined
  164. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  165. session = inner.sessions.create(SessionId('detach'))
  166. }, { inject: ['sessions'] }))
  167. if (session === undefined) throw new Error('session was not created')
  168. mark(session, ['live'])
  169. await owner.dispose()
  170. await settle()
  171. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val).toEqual({ marks: ['live'] })
  172. })
  173. it('flushes when the in-turn event count reaches the configured threshold', async () => {
  174. const { ctx, root } = await harness({ config: { writeEveryEvents: 3, writeIntervalMs: 60_000 } })
  175. const session = ctx.sessions.create(SessionId('count'))
  176. mark(session, ['1'])
  177. mark(session, ['2'])
  178. await settle()
  179. expect((await storedRows(root, session.id))?.['cache-test/marks']?.seq).toBe(-1) // still the creation cut
  180. mark(session, ['3'])
  181. await settle()
  182. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val).toEqual({ marks: ['3'] })
  183. })
  184. it('flushes on the configured interval when the count threshold is not reached', async () => {
  185. const { ctx, cache } = await harness({ config: { writeEveryEvents: 100, writeIntervalMs: 20 } })
  186. const write = vi.spyOn(cache, 'write').mockResolvedValue()
  187. vi.useFakeTimers()
  188. const session = ctx.sessions.create(SessionId('interval'))
  189. write.mockClear()
  190. mark(session, ['slow'])
  191. await vi.advanceTimersByTimeAsync(19)
  192. expect(write).not.toHaveBeenCalled()
  193. await vi.advanceTimersByTimeAsync(1)
  194. expect(write).toHaveBeenCalledExactlyOnceWith(session)
  195. })
  196. it('write() on a never-dirty session checkpoints directly and rejects a non-JSON unit state', async () => {
  197. const { ctx, root } = await harness()
  198. // Never dirtied: no events — write() still lands the init-derived cut.
  199. const clean = ctx.sessions.create(SessionId('clean-write'))
  200. await ctx.sessionProjectionCache.write(clean)
  201. expect((await storedRows(root, clean.id))?.['cache-test/marks']).toEqual({ ver: 1, seq: -1, val: null })
  202. // A unit whose state violates the plain-JSON contract fails the write loud.
  203. ctx.sessionProjections.register({
  204. key: 'cache-test/marks2',
  205. stateSchema: z.custom<Map<string, string>>(() => true),
  206. init: () => new Map<string, string>(),
  207. apply: state => state,
  208. stateVersion: 1,
  209. })
  210. await expect(ctx.sessionProjectionCache.write(clean)).rejects.toThrow('not losslessly JSON-serializable')
  211. })
  212. it('plugin disposal clears armed interval timers and leaves cleaned sessions alone', async () => {
  213. vi.useFakeTimers()
  214. const { ctx, root, fiber } = await harness({ config: { writeEveryEvents: 100, writeIntervalMs: 5000 } })
  215. const armed = ctx.sessions.create(SessionId('armed'))
  216. const cleaned = ctx.sessions.create(SessionId('cleaned'))
  217. mark(armed, ['pending']) // timer armed, no write yet
  218. mark(cleaned, ['done'])
  219. endTurn(cleaned) // mandatory write; markClean leaves {pending: 0, timer: undefined} in the map
  220. await vi.advanceTimersByTimeAsync(0)
  221. await fiber.dispose()
  222. // The armed timer died with the plugin: advancing time writes nothing.
  223. await vi.advanceTimersByTimeAsync(10_000)
  224. // Only the creation cut exists: the armed mark never wrote.
  225. expect((await storedRows(root, armed.id))?.['cache-test/marks']?.seq).toBe(-1)
  226. })
  227. it('contains a durable write failure: logs a warning, event path unharmed, next write self-heals', async () => {
  228. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  229. roots.push(root)
  230. const ctx = new Context()
  231. contexts.push(ctx)
  232. await ctx.plugin(Storage)
  233. await ctx.plugin({ name: storageJsonName, inject: storageJsonInject, apply: storageJsonApply, Config: storageJsonConfig }, { root })
  234. await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
  235. await ctx.plugin(SessionStore)
  236. await ctx.plugin(SessionProjectionRegistry)
  237. ctx.sessionProjections.register(marksUnit())
  238. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  239. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  240. // A directory where the record document must land makes the atomic
  241. // rename fail — including the creation write, so no row ever lands.
  242. const blocker = recordPath(root, SessionId('fail-soft'))
  243. await mkdir(blocker, { recursive: true })
  244. const session = ctx.sessions.create(SessionId('fail-soft'))
  245. mark(session, ['x'])
  246. endTurn(session)
  247. await settle()
  248. expect(await storedRows(root, session.id)).toBeUndefined()
  249. expect(warn).toHaveBeenCalledWith(expect.stringContaining('turn/end write for "fail-soft" failed'))
  250. // Self-heal: once the blocker clears, the next mandatory point writes.
  251. await rm(recordPath(root, session.id), { recursive: true })
  252. mark(session, ['y'])
  253. endTurn(session)
  254. await settle()
  255. expect((await storedRows(root, session.id))?.['cache-test/marks']?.val).toEqual({ marks: ['y'] })
  256. })
  257. })
  258. describe('SessionProjectionCache listing read', () => {
  259. it('keeps host-only checkpoint state out of cached wire snapshots', async () => {
  260. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  261. roots.push(root)
  262. await seedRecord(root, 'host-state', {
  263. 'cache-test/marks': { ver: 1, seq: 4, val: { marks: ['wire'] } },
  264. 'cache-test/secret': { ver: 1, seq: 4, val: 'private prompt text' },
  265. })
  266. const { ctx, cache } = await harness({ root })
  267. ctx.sessionProjections.register(secretUnit)
  268. const header = headerOf(SessionId('host-state'))
  269. expect(cache.cachedSnapshot(header)).toEqual({
  270. asOfSeq: 4,
  271. values: { 'cache-test/marks': { marks: ['wire'] } },
  272. })
  273. expect(JSON.stringify(cache.cachedSnapshot(header))).not.toContain('private prompt text')
  274. })
  275. it('serves identity-matching rows with the cut watermark and refuses unrelated ones', async () => {
  276. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  277. roots.push(root)
  278. await seedRecord(root, 'listed', { 'cache-test/marks': { ver: 1, seq: 4, val: { marks: ['t'] } } })
  279. const { cache } = await harness({ root })
  280. const id = SessionId('listed')
  281. // Matching header: values plus the watermark the client seeds under.
  282. expect(cache.cachedSnapshot(headerOf(id))).toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['t'] } } })
  283. // A recreated id (different createdAt): the record is unrelated — no block.
  284. expect(cache.cachedSnapshot(headerOf(id, 777))).toBeUndefined()
  285. // Unknown id: no block.
  286. expect(cache.cachedSnapshot(headerOf(SessionId('never-cached')))).toBeUndefined()
  287. })
  288. it('returns undefined when the stored record is version-mismatched', async () => {
  289. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  290. roots.push(root)
  291. // A stale version-stamped document is discarded at open: absent record.
  292. const path = recordPath(root, SessionId('all-stale'))
  293. await mkdir(dirname(path), { recursive: true })
  294. await writeFile(path, JSON.stringify({
  295. version: projectionCacheDomainSpec.version + 1,
  296. record: { identity: { createdAt: 0 }, rows: { 'cache-test/marks': { ver: 1, seq: 4, val: { marks: ['old'] } } } },
  297. }))
  298. const { cache } = await harness({ root })
  299. expect(cache.cachedSnapshot(headerOf(SessionId('all-stale')))).toBeUndefined()
  300. })
  301. it('returns undefined when every stored row is version-mismatched', async () => {
  302. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  303. roots.push(root)
  304. // A current document whose rows all fail the live unit's stateVersion:
  305. // the listing view is empty, so no block is served.
  306. await seedRecord(root, 'row-stale', { 'cache-test/marks': { ver: 99, seq: 4, val: { marks: ['old'] } } })
  307. const { cache } = await harness({ root })
  308. expect(cache.cachedSnapshot(headerOf(SessionId('row-stale')))).toBeUndefined()
  309. })
  310. it('binds identity on cwd too: a matching cwd serves, a moved session does not', async () => {
  311. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  312. roots.push(root)
  313. await seedRecord(root, 'homed', { 'cache-test/marks': { ver: 1, seq: 2, val: { marks: ['w'] } } }, { createdAt: 0, cwd: '/work' })
  314. const { cache } = await harness({ root })
  315. const id = SessionId('homed')
  316. expect(cache.cachedSnapshot(headerOf(id, 0, '/work'))?.values['cache-test/marks']).toEqual({ marks: ['w'] })
  317. expect(cache.cachedSnapshot(headerOf(id, 0, '/elsewhere'))).toBeUndefined()
  318. expect(cache.cachedSnapshot(headerOf(id, 0))).toBeUndefined()
  319. })
  320. it('returns undefined for a malformed record document (refold from the log on the caller side)', async () => {
  321. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  322. roots.push(root)
  323. const path = recordPath(root, SessionId('malformed'))
  324. await mkdir(dirname(path), { recursive: true })
  325. await writeFile(path, 'not json at all')
  326. const { cache } = await harness({ root })
  327. expect(cache.cachedSnapshot(headerOf(SessionId('malformed')))).toBeUndefined()
  328. })
  329. })
  330. describe('SessionProjectionCache cold-read seeding', () => {
  331. /** One session's event log: turn/start, one mark per group, turn/end. */
  332. const storedLog = (marks: string[][]): SessionEvent[] => {
  333. const events: SessionEvent[] = [
  334. { type: 'turn/start', seq: 0, time: 0, data: { turn: 1 } },
  335. ]
  336. for (const m of marks) {
  337. events.push({ type: 'cache-test/mark', seq: events.length, time: events.length, data: { marks: m } })
  338. }
  339. events.push({ type: 'turn/end', seq: events.length, time: events.length, data: { turn: 1, reason: { kind: 'completed' } } })
  340. return events
  341. }
  342. it('hydratePrepared seeds from a matching row and retries from the exact log on a malformed one', async () => {
  343. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  344. roots.push(root)
  345. // Records land on disk before the domain opens, so the in-memory table
  346. // picks them up at init.
  347. await seedRecord(root, 'prepared-seeded', {
  348. 'cache-test/marks': { ver: 1, seq: 1, val: { marks: ['cached'] } },
  349. })
  350. await seedRecord(root, 'prepared-fallback', {
  351. 'cache-test/marks': { ver: 1, seq: 1, val: { marks: 'malformed' } },
  352. })
  353. const { cache } = await harness({ root })
  354. const events = storedLog([['fresh']])
  355. // A matching row hydrates the prepared Session without a persistence read.
  356. const seeded = headerOf(SessionId('prepared-seeded'))
  357. const seededSession = Session.create(seeded.id, events, seeded)
  358. expect(cache.hydratePrepared(seededSession, seeded, events)).toEqual({
  359. asOfSeq: 2,
  360. values: { 'cache-test/marks': { marks: ['cached'] } },
  361. })
  362. // A malformed row cannot seed the fold; hydration falls back to the
  363. // exact log so a valid Session stays readable.
  364. const fallback = headerOf(SessionId('prepared-fallback'))
  365. const fallbackSession = Session.create(fallback.id, events, fallback)
  366. expect(cache.hydratePrepared(fallbackSession, fallback, events)).toEqual({
  367. asOfSeq: 2,
  368. values: { 'cache-test/marks': { marks: ['fresh'] } },
  369. })
  370. // No row at all: hydrate from init over the exact log.
  371. const bare = headerOf(SessionId('prepared-bare'))
  372. const bareSession = Session.create(bare.id, events, bare)
  373. expect(cache.hydratePrepared(bareSession, bare, events)).toEqual({
  374. asOfSeq: 2,
  375. values: { 'cache-test/marks': { marks: ['fresh'] } },
  376. })
  377. })
  378. it('coldSnapshot traverses the full log but applies only the events after each cached watermark', async () => {
  379. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  380. roots.push(root)
  381. // A cached row covering the prefix through seq 2 (three applies folded).
  382. await seedRecord(root, 'cold-snap', {
  383. 'cache-test/count': { ver: 1, seq: 2, val: 3 },
  384. }, { createdAt: 9 })
  385. const { cache, ctx } = await harness({ root })
  386. const apply = vi.fn((_state: number, _event: SessionEvent) => 1)
  387. ctx.sessionProjections.register({
  388. key: 'cache-test/count',
  389. stateSchema: z.number().int().nonnegative(),
  390. init: () => 0,
  391. apply,
  392. stateVersion: 1,
  393. } satisfies ProjectionDefinition<'cache-test/count', number>)
  394. const meta = headerOf(SessionId('cold-snap'), 9)
  395. const events = Array.from({ length: 5 }, (_, seq) => ({
  396. type: 'cache-test/mark', seq, time: seq, data: { marks: [`m${seq}`] },
  397. })) as SessionEvent[]
  398. const snapshot = cache.coldSnapshot(meta, events)
  399. // The full log was traversed, but the fold applied only seqs 3 and 4.
  400. expect(apply).toHaveBeenCalledTimes(2)
  401. expect(apply.mock.calls.map(call => call[1].seq)).toEqual([3, 4])
  402. expect(snapshot.asOfSeq).toBe(4)
  403. // Host-only unit: folded but not served; the refreshed row is written
  404. // back (fail-soft, fire-and-forget) once the write lands.
  405. expect(Object.keys(snapshot.values)).not.toContain('cache-test/count')
  406. await vi.waitFor(async () => {
  407. expect((await storedRows(root, meta.id))?.['cache-test/count']?.seq).toBe(4)
  408. })
  409. // No cached row yet: the first cold read folds from init over the full
  410. // log and creates the cache row (the `?? {}` seed path).
  411. const fresh = headerOf(SessionId('cold-fresh'), 10)
  412. cache.coldSnapshot(fresh, events)
  413. expect(apply).toHaveBeenCalledTimes(7) // 2 tail + 5 full
  414. await vi.waitFor(async () => {
  415. expect((await storedRows(root, fresh.id))?.['cache-test/count']?.seq).toBe(4)
  416. })
  417. })
  418. it('coldSnapshot write-back is fail-soft: a failed durable write logs and never throws', async () => {
  419. const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-'))
  420. roots.push(root)
  421. const ctx = new Context()
  422. contexts.push(ctx)
  423. await ctx.plugin(Storage)
  424. await ctx.plugin({ name: storageJsonName, inject: storageJsonInject, apply: storageJsonApply, Config: storageJsonConfig }, { root })
  425. await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
  426. await ctx.plugin(SessionStore)
  427. await ctx.plugin(SessionProjectionRegistry)
  428. ctx.sessionProjections.register(marksUnit())
  429. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  430. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  431. // A directory where the record document must land makes the write-back
  432. // fail; the cold read itself still succeeds and never throws.
  433. const meta = headerOf(SessionId('cold-fail'))
  434. await mkdir(recordPath(root, meta.id), { recursive: true })
  435. expect(ctx.sessionProjectionCache.coldSnapshot(meta, [])).toBeDefined()
  436. await settle()
  437. expect(warn).toHaveBeenCalledWith(expect.stringContaining('cold-read write-back for "cold-fail" failed'))
  438. })
  439. })