jsonl.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { appendFile, mkdtemp, mkdir, rm, readFile, writeFile, readdir, stat } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { isAbsolute, join, relative, resolve } from 'node:path'
  6. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  7. import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
  8. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  9. import { encodeSegment, logPath, scanLog, sessionDir, toHeaderLine } from '../src/format.ts'
  10. import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts'
  11. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  12. let root: string
  13. const dirs: string[] = []
  14. type MutableSessionHeader = { -readonly [K in keyof SessionHeader]: SessionHeader[K] }
  15. /** Test-only mutable view used to verify that backends detach returned/caller metadata. */
  16. function mutableHeader(header: SessionHeader): MutableSessionHeader {
  17. return header
  18. }
  19. async function expectParallelFlushError(promise: Promise<unknown>, message: RegExp): Promise<void> {
  20. try {
  21. await promise
  22. } catch (error) {
  23. expect(error).toBeInstanceOf(AggregateError)
  24. const [cause] = (error as AggregateError).errors as unknown[]
  25. expect(cause).toBeInstanceOf(Error)
  26. expect((cause as Error).message).toMatch(message)
  27. return
  28. }
  29. throw new Error('expected parallel flush to reject')
  30. }
  31. async function freshRoot(): Promise<string> {
  32. const dir = await mkdtemp(join(tmpdir(), 'dsh-jsonl-'))
  33. dirs.push(dir)
  34. return dir
  35. }
  36. afterEach(async () => {
  37. for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true })
  38. })
  39. function appendClosedTurn(session: Session): void {
  40. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  41. session.append('user/message', {
  42. content: [{ type: 'text', text: 'hello' }],
  43. source: { kind: 'user' },
  44. }, { surfaceOp: 'append' })
  45. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  46. }
  47. // Run the shared backend contract against the real JSONL backend.
  48. runPersistenceContract('jsonl', async () => {
  49. const dir = await mkdtemp(join(tmpdir(), 'dsh-jsonl-'))
  50. const ctx = new Context()
  51. await ctx.plugin(SessionStore)
  52. const fiber = await ctx.plugin(SessionPersistenceJsonl, { root: dir })
  53. return {
  54. persistence: ctx.sessionPersistence,
  55. dispose: async () => {
  56. await fiber.dispose()
  57. await rm(dir, { recursive: true, force: true })
  58. },
  59. }
  60. })
  61. // Two mounts share this temp root to exercise reload. `corruptTail` appends a partial,
  62. // newline-less fragment past the committed region so coordinator repair runs on real file bytes.
  63. runCoordinatorContract('jsonl', async (): Promise<CoordinatorFixture> => {
  64. const dir = await mkdtemp(join(tmpdir(), 'dsh-jsonl-coord-'))
  65. return {
  66. mount: async (ctx) => {
  67. const fiber = await ctx.plugin(SessionPersistenceJsonl, { root: dir })
  68. return fiber
  69. },
  70. corruptTail: async (id, cwd) => {
  71. // A half-written record with no trailing newline: scanLog treats it as an
  72. // uncommitted crash fragment and reports committedBytes < byteLength, so
  73. // the coordinator sees a tornMarker to truncate.
  74. await appendFile(logPath(dir, cwd, id), '{"type":"assistant/chunk","seq":8,"ti')
  75. },
  76. cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
  77. }
  78. })
  79. describe('SessionPersistenceJsonl: format helpers', () => {
  80. it('encodeSegment neutralizes traversal, separators, and absolute paths', () => {
  81. expect(encodeSegment('..')).toBe('~002E~002E')
  82. expect(encodeSegment('.')).toBe('~002E')
  83. expect(encodeSegment('a/b')).toBe('a~002Fb')
  84. expect(encodeSegment('/etc/passwd')).toBe('~002Fetc~002Fpasswd')
  85. expect(encodeSegment('a\u0000b')).toBe('a~0000b')
  86. expect(encodeSegment('plain-ID_1.2')).toBe('plain-ID_1.2') // safe chars pass through
  87. expect(encodeSegment('a~b')).toBe('a~007Eb') // ~ itself is escaped
  88. })
  89. it('encodeSegment is injective over UTF-16, incl. lone surrogates', () => {
  90. // Distinct lone surrogates must NOT collide (Buffer.from would normalize
  91. // both to U+FFFD; code-unit escaping keeps them distinct).
  92. const hi = encodeSegment(String.fromCharCode(0xD800))
  93. const lo = encodeSegment(String.fromCharCode(0xDC00))
  94. expect(hi).toBe('~D800')
  95. expect(lo).toBe('~DC00')
  96. expect(hi).not.toBe(lo)
  97. // A literal "~002F" input cannot collide with the encoding of "/".
  98. expect(encodeSegment('~002F')).not.toBe(encodeSegment('/'))
  99. })
  100. it('encodeSegment rejects an empty id', () => {
  101. expect(() => encodeSegment('')).toThrow(/empty/)
  102. })
  103. it('resolves a relative custom root before locating a session', async () => {
  104. const absoluteRoot = await freshRoot()
  105. const ctx = new Context()
  106. await ctx.plugin(SessionStore)
  107. const fiber = await ctx.plugin(SessionPersistenceJsonl, { root: relative(process.cwd(), absoluteRoot) })
  108. const m = meta('relative-location', '/work')
  109. expect(ctx.sessionPersistence.locate(m)).toEqual({
  110. kind: 'jsonl',
  111. path: logPath(resolve(absoluteRoot), '/work', m.id),
  112. })
  113. await fiber.dispose()
  114. })
  115. })
  116. describe('SessionPersistenceJsonl: durability and crash semantics', () => {
  117. let ctx: Context
  118. beforeEach(async () => {
  119. root = await freshRoot()
  120. ctx = new Context()
  121. await ctx.plugin(SessionStore)
  122. await ctx.plugin(SessionPersistenceJsonl, { root })
  123. })
  124. afterEach(async () => { await ctx.fiber.dispose() })
  125. it('lazy materialization: create() writes no file until the first append', async () => {
  126. const m = meta('lazy', '/work')
  127. const location = ctx.sessionPersistence.locate(m)
  128. expect(location).toEqual({ kind: 'jsonl', path: logPath(root, '/work', m.id) })
  129. expect(isAbsolute(location!.path)).toBe(true)
  130. await ctx.sessionPersistence.create(m)
  131. // locate() is a pure target-path calculation: neither it nor create()
  132. // materializes a file before the first append.
  133. const dir = sessionDir(root, '/work')
  134. await expect(stat(logPath(root, '/work', m.id))).rejects.toThrow()
  135. expect((await ctx.sessionPersistence.list()).map(h => h.id)).not.toContain(m.id)
  136. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  137. // now materialized
  138. expect((await stat(logPath(root, '/work', m.id))).isFile()).toBe(true)
  139. expect((await ctx.sessionPersistence.list()).map(h => h.id)).toContain(m.id)
  140. void dir
  141. })
  142. it('keeps the same location on resume and gives a fork its own location', async () => {
  143. const parent = meta('location-parent', '/work')
  144. const parentLocation = ctx.sessionPersistence.locate(parent)
  145. await ctx.sessionPersistence.create(parent)
  146. await ctx.sessionPersistence.append(parent.id, oneTurnLog())
  147. const loaded = await ctx.sessionPersistence.load(parent.id)
  148. expect(ctx.sessionPersistence.locate(loaded.meta)).toEqual(parentLocation)
  149. const child = {
  150. ...loaded.meta,
  151. id: SessionId('location-child'),
  152. parentSession: parent.id,
  153. seedLength: loaded.events.length,
  154. }
  155. const childLocation = ctx.sessionPersistence.locate(child)
  156. expect(childLocation?.path).not.toBe(parentLocation?.path)
  157. expect(childLocation).toEqual({ kind: 'jsonl', path: logPath(root, '/work', child.id) })
  158. })
  159. it('round-trip is byte-identical (incl. assistant/chunk verbatim)', async () => {
  160. const m = meta('chunks')
  161. const log: SessionEvent[] = [
  162. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  163. { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } },
  164. { type: 'assistant/chunk', seq: 2, time: 3, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'he' } } },
  165. { type: 'assistant/chunk', seq: 3, time: 4, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'llo' } } },
  166. { type: 'assistant/message', seq: 4, time: 5, data: { turn: 1, step: 1, content: [{ type: 'text', text: 'hello' }], provenance: { provider: 'mock', model: 'mock' } }, surfaceOp: 'append', sourceEventSeqs: [2, 3] },
  167. { type: 'step/end', seq: 5, time: 6, data: { turn: 1, step: 1 } },
  168. { type: 'turn/end', seq: 6, time: 7, data: { turn: 1, reason: { kind: 'completed' } } },
  169. ]
  170. await ctx.sessionPersistence.create(m)
  171. await ctx.sessionPersistence.append(m.id, log)
  172. const loaded = await ctx.sessionPersistence.load(m.id)
  173. expect(loaded.events).toEqual(log) // chunks preserved, contiguous seqs
  174. })
  175. it('rejects a stored v0 log containing a legacy request/header-delta event', async () => {
  176. const m = meta('legacy-header-delta', '/legacy')
  177. const path = logPath(root, m.cwd, m.id)
  178. await mkdir(sessionDir(root, m.cwd), { recursive: true })
  179. await writeFile(path, [
  180. JSON.stringify(toHeaderLine(m)),
  181. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  182. JSON.stringify({ type: 'request/header-delta', seq: 1, time: 2, data: { config: { model: 'legacy' } } }),
  183. JSON.stringify({ type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } }),
  184. '',
  185. ].join('\n'))
  186. await expect(ctx.sessionPersistence.load(m.id)).rejects.toThrow(/unsupported legacy request\/header-delta event at seq 1/)
  187. })
  188. it('rejects a stored v0 full header carrying the legacy fallback reason', async () => {
  189. const m = meta('legacy-header-fallback', '/legacy')
  190. const path = logPath(root, m.cwd, m.id)
  191. await mkdir(sessionDir(root, m.cwd), { recursive: true })
  192. await writeFile(path, [
  193. JSON.stringify(toHeaderLine(m)),
  194. JSON.stringify({
  195. type: 'request/header',
  196. seq: 0,
  197. time: 1,
  198. data: { header: { config: { model: 'legacy' } }, reason: 'fallback' },
  199. }),
  200. '',
  201. ].join('\n'))
  202. await expect(ctx.sessionPersistence.load(m.id))
  203. .rejects.toThrow(/unsupported legacy request\/header reason "fallback" at seq 0/)
  204. })
  205. it('persists a forked child seed through the existing session write path', async () => {
  206. const source = ctx.sessions.create(SessionId('persist-parent'), { meta: { cwd: '/workspace' } })
  207. appendClosedTurn(source)
  208. const child = ctx.sessions.fork(source, undefined, SessionId('persist-child'))
  209. await ctx.parallel('session/flush', child)
  210. const loaded = await ctx.sessionPersistence.load(child.id)
  211. expect(loaded.events).toEqual(source.events)
  212. expect(loaded.meta).toMatchObject({
  213. id: SessionId('persist-child'),
  214. cwd: '/workspace',
  215. parentSession: SessionId('persist-parent'),
  216. seedLength: source.events.length,
  217. })
  218. })
  219. it('crash recovery: load preserves the interrupted turn and closes it with a synthetic turn/end {interrupted}', async () => {
  220. const m = meta('crash', '/proj')
  221. await ctx.sessionPersistence.create(m)
  222. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5, turn/end at 5
  223. // Simulate a crash mid-second-turn: append raw lines that are NOT closed by
  224. // a turn/end (turn/start + step/start are fully written), plus a final
  225. // partial line with no newline (a torn fragment never fully flushed).
  226. const path = logPath(root, '/proj', m.id)
  227. await writeFile(path, [
  228. JSON.stringify({ type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  229. JSON.stringify({ type: 'step/start', seq: 7, time: 9, data: { turn: 2, step: 1 } }),
  230. '{"type":"assistant/chunk","seq":8,"ti', // truncated partial line (no newline)
  231. ].join('\n'), { flag: 'a' })
  232. // load PRESERVES the interrupted turn's real events (turn/start 6, step/start
  233. // 7) — a turn can be huge, so they must not be truncated — and durably closes
  234. // the orphaned turn with synthetic step/end (8) + turn/end {interrupted} (9).
  235. const loaded = await ctx.sessionPersistence.load(m.id)
  236. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  237. const last = loaded.events.at(-1)!
  238. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  239. const stepEnd = loaded.events[8]!
  240. expect(stepEnd.type).toBe('step/end')
  241. // the torn seq-8 chunk fragment did not survive
  242. expect(loaded.events.some(e => e.type === 'assistant/chunk' && e.seq === 8)).toBe(false)
  243. // The next append continues at seq 10 (the balanced length).
  244. const turn3 = [
  245. { type: 'turn/start', seq: 10, time: 11, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  246. { type: 'turn/end', seq: 11, time: 12, data: { turn: 3, reason: { kind: 'completed' } } },
  247. ] as SessionEvent[]
  248. await ctx.sessionPersistence.append(m.id, turn3)
  249. const reloaded = await ctx.sessionPersistence.load(m.id)
  250. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  251. })
  252. it('committed events are never rewritten: only the crash tail is repaired', async () => {
  253. const m = meta('append-only')
  254. await ctx.sessionPersistence.create(m)
  255. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  256. const before = await readFile(logPath(root, undefined, m.id), 'utf8')
  257. const committedPrefix = before // the whole committed log
  258. // A crash tail then a repair-append.
  259. await writeFile(logPath(root, undefined, m.id), '\n{"partial', { flag: 'a' })
  260. await ctx.sessionPersistence.load(m.id)
  261. await ctx.sessionPersistence.append(m.id, [
  262. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  263. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  264. ] as SessionEvent[])
  265. const after = await readFile(logPath(root, undefined, m.id), 'utf8')
  266. // the committed prefix is byte-for-byte intact at the head of the file
  267. expect(after.startsWith(committedPrefix)).toBe(true)
  268. })
  269. it('a failed appendLines truncates partial bytes so a retry has no seq gap', async () => {
  270. const m = meta('truncate-retry')
  271. await ctx.sessionPersistence.create(m)
  272. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // materialized, seqs 0..5
  273. const sizeBefore = (await stat(logPath(root, undefined, m.id))).size
  274. // Force the NEXT fsync (inside appendLines) to fail once, AFTER writeFile
  275. // has already put bytes on disk — simulating an ENOSPC/fsync error
  276. // mid-append. The recovery truncate() also fsyncs, so allow that one.
  277. const handle = await (await import('node:fs/promises')).open(logPath(root, undefined, m.id), 'r')
  278. const proto = Object.getPrototypeOf(handle) as { sync: () => Promise<void> }
  279. await handle.close()
  280. const realSync = proto.sync
  281. let failed = false
  282. const spy = vi.spyOn(proto, 'sync').mockImplementation(async function (this: unknown) {
  283. if (!failed) { failed = true; throw new Error('simulated fsync ENOSPC') }
  284. return realSync.call(this)
  285. })
  286. const turn2 = [
  287. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  288. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  289. ] as SessionEvent[]
  290. // The append rejects, but the partial bytes are truncated back: the file is
  291. // its pre-append size and the cursor is unchanged.
  292. await expect(ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/ENOSPC/)
  293. expect((await stat(logPath(root, undefined, m.id))).size).toBe(sizeBefore)
  294. spy.mockRestore()
  295. // The retry now succeeds with NO seq gap — the log is contiguous 0..7.
  296. await ctx.sessionPersistence.append(m.id, turn2)
  297. const loaded = await ctx.sessionPersistence.load(m.id)
  298. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  299. })
  300. it('reports both the append failure and a failed rollback', async () => {
  301. const m = meta('rollback-failure')
  302. await ctx.sessionPersistence.create(m)
  303. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  304. const path = logPath(root, undefined, m.id)
  305. const handle = await (await import('node:fs/promises')).open(path, 'r')
  306. const proto = Object.getPrototypeOf(handle) as { sync: () => Promise<void> }
  307. await handle.close()
  308. const realSync = proto.sync
  309. let failed = false
  310. const syncSpy = vi.spyOn(proto, 'sync').mockImplementation(async function (this: unknown) {
  311. if (!failed) { failed = true; throw new Error('simulated append fsync failure') }
  312. return realSync.call(this)
  313. })
  314. const backend = ctx.sessionPersistence as unknown as {
  315. rollbackAppend: (path: string, size: number) => Promise<void>
  316. }
  317. const realRollback = backend.rollbackAppend.bind(backend)
  318. backend.rollbackAppend = () => Promise.reject(new Error('simulated rollback failure'))
  319. try {
  320. await ctx.sessionPersistence.append(m.id, [
  321. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  322. ] as SessionEvent[])
  323. throw new Error('expected append to reject')
  324. } catch (error) {
  325. expect(error).toBeInstanceOf(AggregateError)
  326. const aggregate = error as AggregateError
  327. expect(aggregate.message).toContain(`failed to roll back append to "${path}"`)
  328. expect(aggregate.errors).toHaveLength(2)
  329. expect(aggregate.errors[0]).toMatchObject({ message: 'simulated append fsync failure' })
  330. expect(aggregate.errors[1]).toMatchObject({ message: 'simulated rollback failure' })
  331. } finally {
  332. backend.rollbackAppend = realRollback
  333. syncSpy.mockRestore()
  334. }
  335. })
  336. it('load returns a meta copy: mutating it does not corrupt backend pathing', async () => {
  337. const m = meta('meta-copy', '/proj')
  338. await ctx.sessionPersistence.create(m)
  339. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  340. const loaded = await ctx.sessionPersistence.load(m.id)
  341. // A consumer mutates the returned meta's cwd. The backend's stored pathing
  342. // metadata must be unaffected, so a later append still finds the right log.
  343. mutableHeader(loaded.meta).cwd = '/evil'
  344. await ctx.sessionPersistence.append(m.id, [
  345. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  346. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  347. ] as SessionEvent[])
  348. // The append landed in the ORIGINAL /proj log, not beside an /evil path.
  349. const reloaded = await ctx.sessionPersistence.load(m.id)
  350. expect(reloaded.meta.cwd).toBe('/proj')
  351. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  352. })
  353. it('rejects a re-append of an already-stored seq', async () => {
  354. const m = meta('reappend')
  355. await ctx.sessionPersistence.create(m)
  356. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  357. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow(/seq mismatch/)
  358. })
  359. it('path-traversal session ids are neutralized (no escape from root)', async () => {
  360. const evil = SessionId('../../etc/pwn')
  361. const m = { version: 0, id: evil, createdAt: 1 }
  362. await ctx.sessionPersistence.create(m)
  363. await ctx.sessionPersistence.append(evil, oneTurnLog())
  364. // The file lives UNDER root, not at ../../etc.
  365. const all: string[] = []
  366. async function walk(dir: string): Promise<void> {
  367. for (const e of await readdir(dir, { withFileTypes: true })) {
  368. const p = join(dir, e.name)
  369. if (e.isDirectory()) await walk(p)
  370. else all.push(p)
  371. }
  372. }
  373. await walk(root)
  374. expect(all.length).toBeGreaterThan(0)
  375. expect(all.every(p => p.startsWith(root))).toBe(true)
  376. })
  377. })
  378. describe('SessionPersistenceJsonl: write path (session/event → flush)', () => {
  379. it('concurrent sessions do not cross buffers', async () => {
  380. root = await freshRoot()
  381. const ctx = new Context()
  382. await ctx.plugin(SessionStore)
  383. await ctx.plugin(SessionPersistenceJsonl, { root })
  384. const a = ctx.sessions.create(SessionId('sa'))
  385. const b = ctx.sessions.create(SessionId('sb'))
  386. a.append('user/message', { content: [{ type: 'text', text: 'A' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  387. b.append('user/message', { content: [{ type: 'text', text: 'B' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  388. a.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  389. b.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  390. await ctx.parallel('session/flush', a)
  391. await ctx.parallel('session/flush', b)
  392. const la = await ctx.sessionPersistence.load(SessionId('sa'))
  393. const lb = await ctx.sessionPersistence.load(SessionId('sb'))
  394. expect(JSON.stringify(la.events)).toContain('"A"')
  395. expect(JSON.stringify(la.events)).not.toContain('"B"')
  396. expect(JSON.stringify(lb.events)).toContain('"B"')
  397. expect(JSON.stringify(lb.events)).not.toContain('"A"')
  398. await ctx.fiber.dispose()
  399. })
  400. })
  401. describe('SessionPersistenceJsonl: scanLog unit', () => {
  402. it('rejects a header-less / empty log', () => {
  403. expect(() => scanLog(Buffer.from(''))).toThrow()
  404. })
  405. it('rejects a corrupt header line', () => {
  406. expect(() => scanLog(Buffer.from('not json\n'))).toThrow(/header/)
  407. })
  408. it('rejects a non-session first line', () => {
  409. expect(() => scanLog(Buffer.from('{"type":"event"}\n'))).toThrow(/session header/)
  410. })
  411. it('a seq gap after the last turn/end bounds the preserved tail (torn fragment tolerated)', () => {
  412. const log = [
  413. JSON.stringify({ type: 'session', version: 0, id: 'g', createdAt: 1 }),
  414. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  415. JSON.stringify({ type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }), // gap: missing seq 1
  416. ].join('\n') + '\n'
  417. // No committed turn/end, so the gap is a tolerated crash boundary: scanLog PRESERVES the
  418. // contiguous prefix (turn/start seq 0) — real interrupted-turn work, not discarded — and
  419. // stops at the gap. `loadCore`, not this scanner, later closes the orphaned turn.
  420. expect(scanLog(Buffer.from(log)).events.map(e => e.seq)).toEqual([0])
  421. })
  422. it('rejects a seq gap BEFORE a later committed turn/end (committed data damaged)', () => {
  423. const log = [
  424. JSON.stringify({ type: 'session', version: 0, id: 'g2', createdAt: 1 }),
  425. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  426. JSON.stringify({ type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }), // gap: missing seq 1
  427. JSON.stringify({ type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } }),
  428. ].join('\n') + '\n'
  429. // A turn/end exists, so the prefix up to it is committed — but it has a hole.
  430. // Truncating it would silently drop committed data → unloadable.
  431. expect(() => scanLog(Buffer.from(log))).toThrow(/seq gap in committed region/)
  432. })
  433. it('rejects a corrupt line BEFORE a later committed turn/end (committed data damaged)', () => {
  434. const log = [
  435. JSON.stringify({ type: 'session', version: 0, id: 'c', createdAt: 1 }),
  436. '{not json', // corrupt, sits in the committed region (a turn/end follows)
  437. JSON.stringify({ type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } }),
  438. ].join('\n') + '\n'
  439. expect(() => scanLog(Buffer.from(log))).toThrow(/unparsable committed event/)
  440. })
  441. it('a header-only log (no event lines at all) preserves nothing — committedBytes is the header', () => {
  442. const log = JSON.stringify({ type: 'session', version: 0, id: 'h0', createdAt: 1 }) + '\n'
  443. const scanned = scanLog(Buffer.from(log))
  444. expect(scanned.events).toEqual([])
  445. // committedBytes falls back to the header line's end (no preserved events).
  446. expect(scanned.committedBytes).toBe(Buffer.byteLength(log, 'utf8'))
  447. })
  448. it('a corrupt line after the last turn/end bounds the preserved tail', () => {
  449. const log = [
  450. JSON.stringify({ type: 'session', version: 0, id: 'c2', createdAt: 1 }),
  451. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  452. '{not json', // corrupt crash fragment, no turn/end committed
  453. ].join('\n') + '\n'
  454. // The contiguous prefix (turn/start seq 0) is preserved; the corrupt
  455. // fragment after it is the tolerated crash boundary.
  456. expect(scanLog(Buffer.from(log)).events.map(e => e.seq)).toEqual([0])
  457. })
  458. it('tolerates a seq gap AFTER a turn/end (uncommitted tail)', () => {
  459. const log = [
  460. JSON.stringify({ type: 'session', version: 0, id: 't', createdAt: 1 }),
  461. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  462. JSON.stringify({ type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } }),
  463. JSON.stringify({ type: 'step/start', seq: 9, time: 3, data: { turn: 2, step: 1 } }), // gap in uncommitted tail
  464. ].join('\n') + '\n'
  465. const { events } = scanLog(Buffer.from(log))
  466. expect(events.map(e => e.seq)).toEqual([0, 1]) // tail dropped
  467. })
  468. })
  469. describe('SessionPersistenceJsonl: edge cases', () => {
  470. let ctx: Context
  471. beforeEach(async () => {
  472. root = await freshRoot()
  473. ctx = new Context()
  474. await ctx.plugin(SessionStore)
  475. await ctx.plugin(SessionPersistenceJsonl, { root })
  476. })
  477. afterEach(async () => { await ctx.fiber.dispose() })
  478. it('append rejects non-JSON-serializable undefined-producing data', async () => {
  479. const m = meta('undef')
  480. await ctx.sessionPersistence.create(m)
  481. // A value whose JSON.stringify yields undefined (a bare function as data).
  482. const bad = [{ type: 'user/message', seq: 0, time: 1, data: (() => 0) as unknown }] as unknown as SessionEvent[]
  483. await expect(ctx.sessionPersistence.append(m.id, bad)).rejects.toThrow(/non-JSON-serializable/)
  484. })
  485. it('create snapshots its meta: mutating the caller object after the call is ignored', async () => {
  486. const m = meta('create-snap', '/orig')
  487. const p = ctx.sessionPersistence.create(m)
  488. // Mutate the caller's meta object immediately after calling create.
  489. mutableHeader(m).cwd = '/mutated'
  490. await p
  491. await ctx.sessionPersistence.append(SessionId('create-snap'), oneTurnLog())
  492. // The log materialized under the ORIGINAL cwd, not the mutated one.
  493. expect((await stat(logPath(root, '/orig', SessionId('create-snap')))).isFile()).toBe(true)
  494. await expect(stat(logPath(root, '/mutated', SessionId('create-snap')))).rejects.toThrow()
  495. })
  496. it('list discovers sessions across multiple cwd buckets', async () => {
  497. await ctx.sessionPersistence.create(meta('p1', '/projA'))
  498. await ctx.sessionPersistence.append(SessionId('p1'), oneTurnLog())
  499. await ctx.sessionPersistence.create(meta('p2', '/projB'))
  500. await ctx.sessionPersistence.append(SessionId('p2'), oneTurnLog())
  501. await ctx.sessionPersistence.create(meta('p3')) // no cwd → _no-cwd bucket
  502. await ctx.sessionPersistence.append(SessionId('p3'), oneTurnLog())
  503. const ids = (await ctx.sessionPersistence.list()).map(x => x.id).sort()
  504. expect(ids).toEqual(['p1', 'p2', 'p3'])
  505. })
  506. it('list on an empty root returns nothing', async () => {
  507. expect(await ctx.sessionPersistence.list()).toEqual([])
  508. })
  509. it('list skips empty and non-header .jsonl files (metadata-only read)', async () => {
  510. // A real session…
  511. await ctx.sessionPersistence.create(meta('real', '/p'))
  512. await ctx.sessionPersistence.append(SessionId('real'), oneTurnLog())
  513. // …alongside two junk files in the _no-cwd bucket: an EMPTY file (readFirstLine
  514. // returns undefined) and a file whose first line is not a session header
  515. // (parseHeaderMeta returns undefined). Both are skipped, not listed.
  516. const bucket = join(root, '_no-cwd')
  517. await mkdir(bucket, { recursive: true })
  518. await writeFile(join(bucket, 'empty.jsonl'), '')
  519. await writeFile(join(bucket, 'notheader.jsonl'), '{"type":"turn/start"}\n')
  520. await writeFile(join(bucket, 'badjson.jsonl'), 'not json at all\n')
  521. const ids = (await ctx.sessionPersistence.list()).map(x => x.id).sort()
  522. expect(ids).toEqual(['real'])
  523. })
  524. it('list reads a header line longer than the 8KB read chunk', async () => {
  525. // A tolerated extra field makes this valid header exceed the 8192-byte read buffer, proving
  526. // `readFirstLine` accumulates chunks before `list()` parses it.
  527. const bucket = join(root, '_no-cwd')
  528. await mkdir(bucket, { recursive: true })
  529. const bigHeader = JSON.stringify({ type: 'session', version: 0, id: 'big', createdAt: 1, pad: 'x'.repeat(9000) })
  530. await writeFile(join(bucket, 'big.jsonl'), bigHeader + '\n')
  531. const ids = (await ctx.sessionPersistence.list()).map(x => x.id)
  532. expect(ids).toContain('big')
  533. })
  534. it('a DIFFERENT live session object reusing a disposed id gets its own init (no stale cache)', async () => {
  535. // Session A materializes a log under id "reuse".
  536. const sessFiberA = await ctx.plugin(Object.assign((inner: Context) => {
  537. const a = inner.sessions.create(SessionId('reuse'), { meta: { cwd: '/a' } })
  538. appendLog(a, oneTurnLog())
  539. }, { inject: ['sessions'] }))
  540. // Drain A, then dispose ITS fiber (the live session A is gone) while the
  541. // backend stays loaded.
  542. for (const s of ctx.sessions.list()) await ctx.parallel('session/flush', s)
  543. await sessFiberA.dispose()
  544. // A new Session object reuses the id. Object-keyed initialization must run independently,
  545. // detect the disk collision, and reject instead of appending through session A's stale cursor.
  546. let b!: Session
  547. await ctx.plugin(Object.assign((inner: Context) => {
  548. b = inner.sessions.create(SessionId('reuse'), { meta: { cwd: '/a' } })
  549. }, { inject: ['sessions'] }))
  550. await expect(ctx.sessions.flush(b)).rejects.toThrow(/already bound to a different live session|already has a persisted log on disk/)
  551. })
  552. it('a NO-CWD live session does NOT cross-cwd-adopt a same-id log from a real cwd bucket (loadLive is scope-exact)', async () => {
  553. // Backend 1: materialize a log under id "x" in the cwd "/w" bucket, then
  554. // dispose the WHOLE backend (so backend 2 mounts with an EMPTY states map —
  555. // the HMR/reload path where onCreated goes through loadLive, not a tracked
  556. // collision).
  557. await ctx.sessionPersistence.create(meta('x', '/w'))
  558. await ctx.sessionPersistence.append(SessionId('x'), oneTurnLog())
  559. await ctx.fiber.dispose()
  560. // Backend 2 creates a no-cwd session whose id exists only in `/w`. Exact `loadLive(id,
  561. // undefined)` must not adopt across buckets; the any-cwd collision check then rejects instead
  562. // of grafting no-cwd events onto a log with mismatched cwd.
  563. const ctx2 = new Context()
  564. await ctx2.plugin(SessionStore)
  565. await ctx2.plugin(SessionPersistenceJsonl, { root })
  566. let b!: Session
  567. await ctx2.plugin(Object.assign((inner: Context) => {
  568. b = inner.sessions.create(SessionId('x')) // no cwd
  569. }, { inject: ['sessions'] }))
  570. await expect(ctx2.sessions.flush(b)).rejects.toThrow(/already has a persisted log on disk/)
  571. // The "/w" log is untouched — no no-cwd events were grafted onto it, and no
  572. // `_no-cwd` log for "x" was created.
  573. const inW = scanLog(await readFile(logPath(root, '/w', SessionId('x'))))
  574. expect(inW.meta.cwd).toBe('/w')
  575. expect(inW.events).toHaveLength(6)
  576. await expect(stat(logPath(root, undefined, SessionId('x')))).rejects.toThrow()
  577. await ctx2.fiber.dispose()
  578. })
  579. it('a seed with matching seq/type/time but DIFFERENT data is rejected (deep prefix compare)', async () => {
  580. // Materialize and load (ownerless, cursor = 6).
  581. await ctx.sessionPersistence.create(meta('divergent', '/a'))
  582. await ctx.sessionPersistence.append(SessionId('divergent'), oneTurnLog())
  583. await ctx.sessionPersistence.load(SessionId('divergent'))
  584. // A seed that keeps every seq/type/time but mutates a payload must NOT be
  585. // accepted as "the same session" — otherwise drain filters those seqs as
  586. // already persisted and the divergent payload is silently lost.
  587. const tampered = oneTurnLog()
  588. const userMsg = tampered[1]
  589. if (userMsg?.type === 'user/message') userMsg.data.content = [{ type: 'text', text: 'DIFFERENT' }]
  590. let bad!: Session
  591. await ctx.plugin(Object.assign((inner: Context) => {
  592. bad = inner.sessions.create(SessionId('divergent'), { seed: tampered, meta: { cwd: '/a' } })
  593. }, { inject: ['sessions'] }))
  594. await expect(ctx.sessions.flush(bad)).rejects.toThrow(/do not match this live session|already has a persisted log/)
  595. })
  596. it('a second live session reusing a bound id is rejected', async () => {
  597. // A live session materializes and owns the id.
  598. const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
  599. const a = inner.sessions.create(SessionId('bound'), { meta: { cwd: '/a' } })
  600. a.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  601. a.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  602. }, { inject: ['sessions'] }))
  603. for (const s of ctx.sessions.list()) await ctx.parallel('session/flush', s)
  604. await firstFiber.dispose()
  605. let second!: Session
  606. await ctx.plugin(Object.assign((inner: Context) => {
  607. second = inner.sessions.create(SessionId('bound'), { meta: { cwd: '/a' } })
  608. }, { inject: ['sessions'] }))
  609. await expect(ctx.sessions.flush(second))
  610. .rejects.toThrow(/already bound to a different live session|already has a persisted log|do not match/)
  611. })
  612. it('list returns nothing when the root directory does not exist', async () => {
  613. const ctx2 = new Context()
  614. await ctx2.plugin(SessionStore)
  615. await ctx2.plugin(SessionPersistenceJsonl, { root: join(root, 'does-not-exist-yet') })
  616. expect(await ctx2.sessionPersistence.list()).toEqual([])
  617. await ctx2.fiber.dispose()
  618. })
  619. it('list surfaces a non-ENOENT root error (ENOTDIR) instead of reporting no sessions', async () => {
  620. // A durable backend must not collapse a storage fault to "no sessions". Making the root a
  621. // regular file forces ENOTDIR from `readdir`, which must propagate.
  622. const filePath = join(root, 'not-a-dir')
  623. await writeFile(filePath, 'x')
  624. const ctx2 = new Context()
  625. await ctx2.plugin(SessionStore)
  626. await ctx2.plugin(SessionPersistenceJsonl, { root: filePath })
  627. await expect(ctx2.sessionPersistence.list()).rejects.toThrow(/ENOTDIR/)
  628. await ctx2.fiber.dispose()
  629. })
  630. it('loadLive surfaces a non-ENOENT lookup error (ENOTDIR) instead of reporting absent', async () => {
  631. // A non-ENOENT per-id open error must surface rather than become "not found" and permit false
  632. // live adoption. Making the cwd bucket a regular file forces ENOTDIR for its child log path.
  633. const cwd = '/x'
  634. const ctx2 = new Context()
  635. await ctx2.plugin(SessionStore)
  636. await ctx2.plugin(SessionPersistenceJsonl, { root })
  637. await writeFile(sessionDir(root, cwd), 'x') // bucket path is now a FILE
  638. let s!: Session
  639. await ctx2.plugin(Object.assign((inner: Context) => {
  640. s = inner.sessions.create(SessionId('exists-fault'), { meta: { cwd } })
  641. }, { inject: ['sessions'] }))
  642. await expect(ctx2.sessions.flush(s)).rejects.toThrow(/ENOTDIR/)
  643. await ctx2.fiber.dispose()
  644. })
  645. it('append() to a disk-only session adopts it and repairs a crash tail', async () => {
  646. // Persist a session, then corrupt its tail, all through ONE backend.
  647. const m = meta('disk-append', '/d')
  648. await ctx.sessionPersistence.create(m)
  649. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  650. await writeFile(logPath(root, '/d', m.id), '\n{"partial crash', { flag: 'a' })
  651. // A FRESH backend with no in-memory state: append directly (no prior load)
  652. // → append must adopt from disk, and the adopt's load schedules a repair
  653. // that the same append then performs before writing.
  654. const ctx2 = new Context()
  655. await ctx2.plugin(SessionStore)
  656. await ctx2.plugin(SessionPersistenceJsonl, { root })
  657. await ctx2.sessionPersistence.append(m.id, [
  658. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  659. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  660. ] as SessionEvent[])
  661. const loaded = await ctx2.sessionPersistence.load(m.id)
  662. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  663. await ctx2.fiber.dispose()
  664. })
  665. it('a header-only log (open turn, no turn/end) preserves the open turn on load and closes it', async () => {
  666. // A session whose only durable content is an unclosed first turn. scanLog
  667. // preserves the turn/start; loadCore closes it with a synthetic
  668. // turn/end {interrupted} so the returned log is balanced.
  669. const m = meta('open-turn', '/h')
  670. await ctx.sessionPersistence.create(m)
  671. await ctx.sessionPersistence.append(m.id, [
  672. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  673. ] as SessionEvent[])
  674. const { events } = await ctx.sessionPersistence.load(m.id)
  675. expect(events.map(e => e.type)).toEqual(['turn/start', 'turn/end'])
  676. const end = events[1]!
  677. expect(end.type === 'turn/end' && end.data.reason).toEqual({ kind: 'interrupted' })
  678. })
  679. it('createCore rejects an id already on disk under a DIFFERENT cwd bucket', async () => {
  680. // Persist the id under cwd A.
  681. const a = meta('dup-id', '/projA')
  682. await ctx.sessionPersistence.create(a)
  683. await ctx.sessionPersistence.append(a.id, oneTurnLog())
  684. // A fresh backend creating the SAME id under cwd B must still refuse: load
  685. // identifies by id across all buckets, so a second log would make resume
  686. // nondeterministic. create scans every bucket, not just meta.cwd's.
  687. const ctx2 = new Context()
  688. await ctx2.plugin(SessionStore)
  689. await ctx2.plugin(SessionPersistenceJsonl, { root })
  690. await expect(ctx2.sessionPersistence.create(meta('dup-id', '/projB')))
  691. .rejects.toThrow(/already has a persisted log on disk/)
  692. await ctx2.fiber.dispose()
  693. })
  694. it('flush keeps buffered events when the append fails (no silent loss)', async () => {
  695. root = await freshRoot()
  696. const ctx2 = new Context()
  697. await ctx2.plugin(SessionStore)
  698. await ctx2.plugin(SessionPersistenceJsonl, { root })
  699. const session = ctx2.sessions.create(SessionId('flush-fail'))
  700. // A full turn lands in the write-behind buffer.
  701. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  702. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  703. // Make the durable materialize fail on the next flush.
  704. const backend = ctx2.sessionPersistence as unknown as { materialize: (...args: unknown[]) => Promise<void> }
  705. const origMat = backend.materialize.bind(backend)
  706. backend.materialize = () => Promise.reject(new Error('disk full'))
  707. await expectParallelFlushError(ctx2.parallel('session/flush', session), /disk full/)
  708. // The events are STILL buffered (not silently dropped): a retry persists them.
  709. backend.materialize = origMat
  710. await ctx2.parallel('session/flush', session)
  711. const loaded = await ctx2.sessionPersistence.load(SessionId('flush-fail'))
  712. expect(loaded.events.map(e => e.seq)).toEqual([0, 1])
  713. await ctx2.fiber.dispose()
  714. })
  715. it('rejects non-JSON event data: BigInt, function, circular, Map, undefined property', async () => {
  716. const m = meta('serial')
  717. await ctx.sessionPersistence.create(m)
  718. const bad = (extra: unknown) => [{ type: 'user/message', seq: 0, time: 1, data: { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, extra } }] as unknown as SessionEvent[]
  719. await expect(ctx.sessionPersistence.append(m.id, bad(1n))).rejects.toThrow(/non-JSON-serializable/)
  720. await expect(ctx.sessionPersistence.append(m.id, bad(() => 0))).rejects.toThrow(/non-JSON-serializable/)
  721. await expect(ctx.sessionPersistence.append(m.id, bad(Symbol('s')))).rejects.toThrow(/non-JSON-serializable/)
  722. await expect(ctx.sessionPersistence.append(m.id, bad(new Map()))).rejects.toThrow(/non-JSON-serializable/)
  723. await expect(ctx.sessionPersistence.append(m.id, bad(undefined))).rejects.toThrow(/non-JSON-serializable/)
  724. await expect(ctx.sessionPersistence.append(m.id, bad(Infinity))).rejects.toThrow(/non-JSON-serializable/)
  725. // a circular structure
  726. const circ: Record<string, unknown> = {}
  727. circ.self = circ
  728. await expect(ctx.sessionPersistence.append(m.id, bad(circ))).rejects.toThrow(/non-JSON-serializable/)
  729. // The session was never materialized by any of the rejected appends.
  730. expect((await ctx.sessionPersistence.list()).map(h => h.id)).not.toContain(m.id)
  731. })
  732. it('accepts well-formed JSON values (null, booleans, nested arrays/objects)', async () => {
  733. const m = meta('json-ok')
  734. await ctx.sessionPersistence.create(m)
  735. const ev = [{ type: 'user/message', seq: 0, time: 1, data: { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, extra: { a: null, b: true, c: [1, 2, { d: 'nested' }] } } }] as unknown as SessionEvent[]
  736. await ctx.sessionPersistence.append(m.id, ev)
  737. expect((await ctx.sessionPersistence.list()).map(h => h.id)).toContain(m.id)
  738. })
  739. it('Session.append rejects a non-serializable event at the source (never enters the log)', () => {
  740. const session = ctx.sessions.create(SessionId('reject-bad'))
  741. // Serializability is enforced at the source: Session.append throws on a BigInt-bearing
  742. // event before it enters session.events, so the durable log can never diverge from the live
  743. // log. The error therefore surfaces synchronously at append, not later during backend flush.
  744. expect(() => {
  745. session.append('user/message', { content: [{ type: 'text', text: 'bad' }], source: { kind: 'user' }, bad: 1n } as never, { surfaceOp: 'append' })
  746. }).toThrow(/non-JSON-serializable/)
  747. // The bad event was rejected, so the log stayed empty.
  748. expect(session.events.length).toBe(0)
  749. })
  750. })