jsonl.spec.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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 } 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' }] }, 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('persists a forked child seed through the existing session write path', async () => {
  176. const source = ctx.sessions.create(SessionId('persist-parent'), { meta: { cwd: '/workspace' } })
  177. appendClosedTurn(source)
  178. const child = ctx.sessions.fork(source, undefined, SessionId('persist-child'))
  179. await ctx.parallel('session/flush', child)
  180. const loaded = await ctx.sessionPersistence.load(child.id)
  181. expect(loaded.events).toEqual(source.events)
  182. expect(loaded.meta).toMatchObject({
  183. id: SessionId('persist-child'),
  184. cwd: '/workspace',
  185. parentSession: SessionId('persist-parent'),
  186. seedLength: source.events.length,
  187. })
  188. })
  189. it('crash recovery: load preserves the interrupted turn and closes it with a synthetic turn/end {interrupted}', async () => {
  190. const m = meta('crash', '/proj')
  191. await ctx.sessionPersistence.create(m)
  192. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5, turn/end at 5
  193. // Simulate a crash mid-second-turn: append raw lines that are NOT closed by
  194. // a turn/end (turn/start + step/start are fully written), plus a final
  195. // partial line with no newline (a torn fragment never fully flushed).
  196. const path = logPath(root, '/proj', m.id)
  197. await writeFile(path, [
  198. JSON.stringify({ type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  199. JSON.stringify({ type: 'step/start', seq: 7, time: 9, data: { turn: 2, step: 1 } }),
  200. '{"type":"assistant/chunk","seq":8,"ti', // truncated partial line (no newline)
  201. ].join('\n'), { flag: 'a' })
  202. // load PRESERVES the interrupted turn's real events (turn/start 6, step/start
  203. // 7) — a turn can be huge, so they must not be truncated — and durably closes
  204. // the orphaned turn with synthetic step/end (8) + turn/end {interrupted} (9).
  205. const loaded = await ctx.sessionPersistence.load(m.id)
  206. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  207. const last = loaded.events.at(-1)!
  208. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  209. const stepEnd = loaded.events[8]!
  210. expect(stepEnd.type).toBe('step/end')
  211. // the torn seq-8 chunk fragment did not survive
  212. expect(loaded.events.some(e => e.type === 'assistant/chunk' && e.seq === 8)).toBe(false)
  213. // The next append continues at seq 10 (the balanced length).
  214. const turn3 = [
  215. { type: 'turn/start', seq: 10, time: 11, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  216. { type: 'turn/end', seq: 11, time: 12, data: { turn: 3, reason: { kind: 'completed' } } },
  217. ] as SessionEvent[]
  218. await ctx.sessionPersistence.append(m.id, turn3)
  219. const reloaded = await ctx.sessionPersistence.load(m.id)
  220. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  221. })
  222. it('committed events are never rewritten: only the crash tail is repaired', async () => {
  223. const m = meta('append-only')
  224. await ctx.sessionPersistence.create(m)
  225. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  226. const before = await readFile(logPath(root, undefined, m.id), 'utf8')
  227. const committedPrefix = before // the whole committed log
  228. // A crash tail then a repair-append.
  229. await writeFile(logPath(root, undefined, m.id), '\n{"partial', { flag: 'a' })
  230. await ctx.sessionPersistence.load(m.id)
  231. await ctx.sessionPersistence.append(m.id, [
  232. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  233. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  234. ] as SessionEvent[])
  235. const after = await readFile(logPath(root, undefined, m.id), 'utf8')
  236. // the committed prefix is byte-for-byte intact at the head of the file
  237. expect(after.startsWith(committedPrefix)).toBe(true)
  238. })
  239. it('a failed appendLines truncates partial bytes so a retry has no seq gap', async () => {
  240. const m = meta('truncate-retry')
  241. await ctx.sessionPersistence.create(m)
  242. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // materialized, seqs 0..5
  243. const sizeBefore = (await stat(logPath(root, undefined, m.id))).size
  244. // Force the NEXT fsync (inside appendLines) to fail once, AFTER writeFile
  245. // has already put bytes on disk — simulating an ENOSPC/fsync error
  246. // mid-append. The recovery truncate() also fsyncs, so allow that one.
  247. const handle = await (await import('node:fs/promises')).open(logPath(root, undefined, m.id), 'r')
  248. const proto = Object.getPrototypeOf(handle) as { sync: () => Promise<void> }
  249. await handle.close()
  250. const realSync = proto.sync
  251. let failed = false
  252. const spy = vi.spyOn(proto, 'sync').mockImplementation(async function (this: unknown) {
  253. if (!failed) { failed = true; throw new Error('simulated fsync ENOSPC') }
  254. return realSync.call(this)
  255. })
  256. const turn2 = [
  257. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  258. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  259. ] as SessionEvent[]
  260. // The append rejects, but the partial bytes are truncated back: the file is
  261. // its pre-append size and the cursor is unchanged.
  262. await expect(ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/ENOSPC/)
  263. expect((await stat(logPath(root, undefined, m.id))).size).toBe(sizeBefore)
  264. spy.mockRestore()
  265. // The retry now succeeds with NO seq gap — the log is contiguous 0..7.
  266. await ctx.sessionPersistence.append(m.id, turn2)
  267. const loaded = await ctx.sessionPersistence.load(m.id)
  268. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  269. })
  270. it('load returns a meta copy: mutating it does not corrupt backend pathing', async () => {
  271. const m = meta('meta-copy', '/proj')
  272. await ctx.sessionPersistence.create(m)
  273. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  274. const loaded = await ctx.sessionPersistence.load(m.id)
  275. // A consumer mutates the returned meta's cwd. The backend's stored pathing
  276. // metadata must be unaffected, so a later append still finds the right log.
  277. mutableHeader(loaded.meta).cwd = '/evil'
  278. await ctx.sessionPersistence.append(m.id, [
  279. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  280. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  281. ] as SessionEvent[])
  282. // The append landed in the ORIGINAL /proj log, not beside an /evil path.
  283. const reloaded = await ctx.sessionPersistence.load(m.id)
  284. expect(reloaded.meta.cwd).toBe('/proj')
  285. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  286. })
  287. it('rejects a re-append of an already-stored seq', async () => {
  288. const m = meta('reappend')
  289. await ctx.sessionPersistence.create(m)
  290. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  291. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow(/seq mismatch/)
  292. })
  293. it('path-traversal session ids are neutralized (no escape from root)', async () => {
  294. const evil = SessionId('../../etc/pwn')
  295. const m = { version: 0, id: evil, createdAt: 1 }
  296. await ctx.sessionPersistence.create(m)
  297. await ctx.sessionPersistence.append(evil, oneTurnLog())
  298. // The file lives UNDER root, not at ../../etc.
  299. const all: string[] = []
  300. async function walk(dir: string): Promise<void> {
  301. for (const e of await readdir(dir, { withFileTypes: true })) {
  302. const p = join(dir, e.name)
  303. if (e.isDirectory()) await walk(p)
  304. else all.push(p)
  305. }
  306. }
  307. await walk(root)
  308. expect(all.length).toBeGreaterThan(0)
  309. expect(all.every(p => p.startsWith(root))).toBe(true)
  310. })
  311. })
  312. describe('SessionPersistenceJsonl: write path (session/event → flush)', () => {
  313. it('concurrent sessions do not cross buffers', async () => {
  314. root = await freshRoot()
  315. const ctx = new Context()
  316. await ctx.plugin(SessionStore)
  317. await ctx.plugin(SessionPersistenceJsonl, { root })
  318. const a = ctx.sessions.create(SessionId('sa'))
  319. const b = ctx.sessions.create(SessionId('sb'))
  320. a.append('user/message', { content: [{ type: 'text', text: 'A' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  321. b.append('user/message', { content: [{ type: 'text', text: 'B' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  322. a.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  323. b.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  324. await ctx.parallel('session/flush', a)
  325. await ctx.parallel('session/flush', b)
  326. const la = await ctx.sessionPersistence.load(SessionId('sa'))
  327. const lb = await ctx.sessionPersistence.load(SessionId('sb'))
  328. expect(JSON.stringify(la.events)).toContain('"A"')
  329. expect(JSON.stringify(la.events)).not.toContain('"B"')
  330. expect(JSON.stringify(lb.events)).toContain('"B"')
  331. expect(JSON.stringify(lb.events)).not.toContain('"A"')
  332. await ctx.fiber.dispose()
  333. })
  334. })
  335. describe('SessionPersistenceJsonl: scanLog unit', () => {
  336. it('rejects a header-less / empty log', () => {
  337. expect(() => scanLog(Buffer.from(''))).toThrow()
  338. })
  339. it('rejects a corrupt header line', () => {
  340. expect(() => scanLog(Buffer.from('not json\n'))).toThrow(/header/)
  341. })
  342. it('rejects a non-session first line', () => {
  343. expect(() => scanLog(Buffer.from('{"type":"event"}\n'))).toThrow(/session header/)
  344. })
  345. it('a seq gap after the last turn/end bounds the preserved tail (torn fragment tolerated)', () => {
  346. const log = [
  347. JSON.stringify({ type: 'session', version: 0, id: 'g', createdAt: 1 }),
  348. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  349. JSON.stringify({ type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }), // gap: missing seq 1
  350. ].join('\n') + '\n'
  351. // No committed turn/end, so the gap is a tolerated crash boundary: scanLog PRESERVES the
  352. // contiguous prefix (turn/start seq 0) — real interrupted-turn work, not discarded — and
  353. // stops at the gap. `loadCore`, not this scanner, later closes the orphaned turn.
  354. expect(scanLog(Buffer.from(log)).events.map(e => e.seq)).toEqual([0])
  355. })
  356. it('rejects a seq gap BEFORE a later committed turn/end (committed data damaged)', () => {
  357. const log = [
  358. JSON.stringify({ type: 'session', version: 0, id: 'g2', createdAt: 1 }),
  359. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  360. JSON.stringify({ type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }), // gap: missing seq 1
  361. JSON.stringify({ type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } }),
  362. ].join('\n') + '\n'
  363. // A turn/end exists, so the prefix up to it is committed — but it has a hole.
  364. // Truncating it would silently drop committed data → unloadable.
  365. expect(() => scanLog(Buffer.from(log))).toThrow(/seq gap in committed region/)
  366. })
  367. it('rejects a corrupt line BEFORE a later committed turn/end (committed data damaged)', () => {
  368. const log = [
  369. JSON.stringify({ type: 'session', version: 0, id: 'c', createdAt: 1 }),
  370. '{not json', // corrupt, sits in the committed region (a turn/end follows)
  371. JSON.stringify({ type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } }),
  372. ].join('\n') + '\n'
  373. expect(() => scanLog(Buffer.from(log))).toThrow(/unparsable committed event/)
  374. })
  375. it('a header-only log (no event lines at all) preserves nothing — committedBytes is the header', () => {
  376. const log = JSON.stringify({ type: 'session', version: 0, id: 'h0', createdAt: 1 }) + '\n'
  377. const scanned = scanLog(Buffer.from(log))
  378. expect(scanned.events).toEqual([])
  379. // committedBytes falls back to the header line's end (no preserved events).
  380. expect(scanned.committedBytes).toBe(Buffer.byteLength(log, 'utf8'))
  381. })
  382. it('a corrupt line after the last turn/end bounds the preserved tail', () => {
  383. const log = [
  384. JSON.stringify({ type: 'session', version: 0, id: 'c2', createdAt: 1 }),
  385. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  386. '{not json', // corrupt crash fragment, no turn/end committed
  387. ].join('\n') + '\n'
  388. // The contiguous prefix (turn/start seq 0) is preserved; the corrupt
  389. // fragment after it is the tolerated crash boundary.
  390. expect(scanLog(Buffer.from(log)).events.map(e => e.seq)).toEqual([0])
  391. })
  392. it('tolerates a seq gap AFTER a turn/end (uncommitted tail)', () => {
  393. const log = [
  394. JSON.stringify({ type: 'session', version: 0, id: 't', createdAt: 1 }),
  395. JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }),
  396. JSON.stringify({ type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } }),
  397. JSON.stringify({ type: 'step/start', seq: 9, time: 3, data: { turn: 2, step: 1 } }), // gap in uncommitted tail
  398. ].join('\n') + '\n'
  399. const { events } = scanLog(Buffer.from(log))
  400. expect(events.map(e => e.seq)).toEqual([0, 1]) // tail dropped
  401. })
  402. })
  403. describe('SessionPersistenceJsonl: edge cases', () => {
  404. let ctx: Context
  405. beforeEach(async () => {
  406. root = await freshRoot()
  407. ctx = new Context()
  408. await ctx.plugin(SessionStore)
  409. await ctx.plugin(SessionPersistenceJsonl, { root })
  410. })
  411. afterEach(async () => { await ctx.fiber.dispose() })
  412. it('append rejects non-JSON-serializable undefined-producing data', async () => {
  413. const m = meta('undef')
  414. await ctx.sessionPersistence.create(m)
  415. // A value whose JSON.stringify yields undefined (a bare function as data).
  416. const bad = [{ type: 'user/message', seq: 0, time: 1, data: (() => 0) as unknown }] as unknown as SessionEvent[]
  417. await expect(ctx.sessionPersistence.append(m.id, bad)).rejects.toThrow(/non-JSON-serializable/)
  418. })
  419. it('create snapshots its meta: mutating the caller object after the call is ignored', async () => {
  420. const m = meta('create-snap', '/orig')
  421. const p = ctx.sessionPersistence.create(m)
  422. // Mutate the caller's meta object immediately after calling create.
  423. mutableHeader(m).cwd = '/mutated'
  424. await p
  425. await ctx.sessionPersistence.append(SessionId('create-snap'), oneTurnLog())
  426. // The log materialized under the ORIGINAL cwd, not the mutated one.
  427. expect((await stat(logPath(root, '/orig', SessionId('create-snap')))).isFile()).toBe(true)
  428. await expect(stat(logPath(root, '/mutated', SessionId('create-snap')))).rejects.toThrow()
  429. })
  430. it('list discovers sessions across multiple cwd buckets', async () => {
  431. await ctx.sessionPersistence.create(meta('p1', '/projA'))
  432. await ctx.sessionPersistence.append(SessionId('p1'), oneTurnLog())
  433. await ctx.sessionPersistence.create(meta('p2', '/projB'))
  434. await ctx.sessionPersistence.append(SessionId('p2'), oneTurnLog())
  435. await ctx.sessionPersistence.create(meta('p3')) // no cwd → _no-cwd bucket
  436. await ctx.sessionPersistence.append(SessionId('p3'), oneTurnLog())
  437. const ids = (await ctx.sessionPersistence.list()).map(x => x.id).sort()
  438. expect(ids).toEqual(['p1', 'p2', 'p3'])
  439. })
  440. it('list on an empty root returns nothing', async () => {
  441. expect(await ctx.sessionPersistence.list()).toEqual([])
  442. })
  443. it('list skips empty and non-header .jsonl files (metadata-only read)', async () => {
  444. // A real session…
  445. await ctx.sessionPersistence.create(meta('real', '/p'))
  446. await ctx.sessionPersistence.append(SessionId('real'), oneTurnLog())
  447. // …alongside two junk files in the _no-cwd bucket: an EMPTY file (readFirstLine
  448. // returns undefined) and a file whose first line is not a session header
  449. // (parseHeaderMeta returns undefined). Both are skipped, not listed.
  450. const bucket = join(root, '_no-cwd')
  451. await mkdir(bucket, { recursive: true })
  452. await writeFile(join(bucket, 'empty.jsonl'), '')
  453. await writeFile(join(bucket, 'notheader.jsonl'), '{"type":"turn/start"}\n')
  454. await writeFile(join(bucket, 'badjson.jsonl'), 'not json at all\n')
  455. const ids = (await ctx.sessionPersistence.list()).map(x => x.id).sort()
  456. expect(ids).toEqual(['real'])
  457. })
  458. it('list reads a header line longer than the 8KB read chunk', async () => {
  459. // A tolerated extra field makes this valid header exceed the 8192-byte read buffer, proving
  460. // `readFirstLine` accumulates chunks before `list()` parses it.
  461. const bucket = join(root, '_no-cwd')
  462. await mkdir(bucket, { recursive: true })
  463. const bigHeader = JSON.stringify({ type: 'session', version: 0, id: 'big', createdAt: 1, pad: 'x'.repeat(9000) })
  464. await writeFile(join(bucket, 'big.jsonl'), bigHeader + '\n')
  465. const ids = (await ctx.sessionPersistence.list()).map(x => x.id)
  466. expect(ids).toContain('big')
  467. })
  468. it('a DIFFERENT live session object reusing a disposed id gets its own init (no stale cache)', async () => {
  469. // Session A materializes a log under id "reuse".
  470. const sessFiberA = await ctx.plugin(Object.assign((inner: Context) => {
  471. const a = inner.sessions.create(SessionId('reuse'), { meta: { cwd: '/a' } })
  472. appendLog(a, oneTurnLog())
  473. }, { inject: ['sessions'] }))
  474. // Drain A, then dispose ITS fiber (the live session A is gone) while the
  475. // backend stays loaded.
  476. for (const s of ctx.sessions.list()) await ctx.parallel('session/flush', s)
  477. await sessFiberA.dispose()
  478. // A new Session object reuses the id. Object-keyed initialization must run independently,
  479. // detect the disk collision, and reject instead of appending through session A's stale cursor.
  480. let b!: Session
  481. await ctx.plugin(Object.assign((inner: Context) => {
  482. b = inner.sessions.create(SessionId('reuse'), { meta: { cwd: '/a' } })
  483. }, { inject: ['sessions'] }))
  484. await expect(ctx.sessions.flush(b)).rejects.toThrow(/already bound to a different live session|already has a persisted log on disk/)
  485. })
  486. 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 () => {
  487. // Backend 1: materialize a log under id "x" in the cwd "/w" bucket, then
  488. // dispose the WHOLE backend (so backend 2 mounts with an EMPTY states map —
  489. // the HMR/reload path where onCreated goes through loadLive, not a tracked
  490. // collision).
  491. await ctx.sessionPersistence.create(meta('x', '/w'))
  492. await ctx.sessionPersistence.append(SessionId('x'), oneTurnLog())
  493. await ctx.fiber.dispose()
  494. // Backend 2 creates a no-cwd session whose id exists only in `/w`. Exact `loadLive(id,
  495. // undefined)` must not adopt across buckets; the any-cwd collision check then rejects instead
  496. // of grafting no-cwd events onto a log with mismatched cwd.
  497. const ctx2 = new Context()
  498. await ctx2.plugin(SessionStore)
  499. await ctx2.plugin(SessionPersistenceJsonl, { root })
  500. let b!: Session
  501. await ctx2.plugin(Object.assign((inner: Context) => {
  502. b = inner.sessions.create(SessionId('x')) // no cwd
  503. }, { inject: ['sessions'] }))
  504. await expect(ctx2.sessions.flush(b)).rejects.toThrow(/already has a persisted log on disk/)
  505. // The "/w" log is untouched — no no-cwd events were grafted onto it, and no
  506. // `_no-cwd` log for "x" was created.
  507. const inW = scanLog(await readFile(logPath(root, '/w', SessionId('x'))))
  508. expect(inW.meta.cwd).toBe('/w')
  509. expect(inW.events).toHaveLength(6)
  510. await expect(stat(logPath(root, undefined, SessionId('x')))).rejects.toThrow()
  511. await ctx2.fiber.dispose()
  512. })
  513. it('a seed with matching seq/type/time but DIFFERENT data is rejected (deep prefix compare)', async () => {
  514. // Materialize and load (ownerless, cursor = 6).
  515. await ctx.sessionPersistence.create(meta('divergent', '/a'))
  516. await ctx.sessionPersistence.append(SessionId('divergent'), oneTurnLog())
  517. await ctx.sessionPersistence.load(SessionId('divergent'))
  518. // A seed that keeps every seq/type/time but mutates a payload must NOT be
  519. // accepted as "the same session" — otherwise drain filters those seqs as
  520. // already persisted and the divergent payload is silently lost.
  521. const tampered = oneTurnLog()
  522. const userMsg = tampered[1]
  523. if (userMsg?.type === 'user/message') userMsg.data.content = [{ type: 'text', text: 'DIFFERENT' }]
  524. let bad!: Session
  525. await ctx.plugin(Object.assign((inner: Context) => {
  526. bad = inner.sessions.create(SessionId('divergent'), { seed: tampered, meta: { cwd: '/a' } })
  527. }, { inject: ['sessions'] }))
  528. await expect(ctx.sessions.flush(bad)).rejects.toThrow(/do not match this live session|already has a persisted log/)
  529. })
  530. it('a second live session reusing a bound id is rejected', async () => {
  531. // A live session materializes and owns the id.
  532. const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
  533. const a = inner.sessions.create(SessionId('bound'), { meta: { cwd: '/a' } })
  534. a.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  535. a.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  536. }, { inject: ['sessions'] }))
  537. for (const s of ctx.sessions.list()) await ctx.parallel('session/flush', s)
  538. await firstFiber.dispose()
  539. let second!: Session
  540. await ctx.plugin(Object.assign((inner: Context) => {
  541. second = inner.sessions.create(SessionId('bound'), { meta: { cwd: '/a' } })
  542. }, { inject: ['sessions'] }))
  543. await expect(ctx.sessions.flush(second))
  544. .rejects.toThrow(/already bound to a different live session|already has a persisted log|do not match/)
  545. })
  546. it('list returns nothing when the root directory does not exist', async () => {
  547. const ctx2 = new Context()
  548. await ctx2.plugin(SessionStore)
  549. await ctx2.plugin(SessionPersistenceJsonl, { root: join(root, 'does-not-exist-yet') })
  550. expect(await ctx2.sessionPersistence.list()).toEqual([])
  551. await ctx2.fiber.dispose()
  552. })
  553. it('list surfaces a non-ENOENT root error (ENOTDIR) instead of reporting no sessions', async () => {
  554. // A durable backend must not collapse a storage fault to "no sessions". Making the root a
  555. // regular file forces ENOTDIR from `readdir`, which must propagate.
  556. const filePath = join(root, 'not-a-dir')
  557. await writeFile(filePath, 'x')
  558. const ctx2 = new Context()
  559. await ctx2.plugin(SessionStore)
  560. await ctx2.plugin(SessionPersistenceJsonl, { root: filePath })
  561. await expect(ctx2.sessionPersistence.list()).rejects.toThrow(/ENOTDIR/)
  562. await ctx2.fiber.dispose()
  563. })
  564. it('loadLive surfaces a non-ENOENT lookup error (ENOTDIR) instead of reporting absent', async () => {
  565. // A non-ENOENT per-id open error must surface rather than become "not found" and permit false
  566. // live adoption. Making the cwd bucket a regular file forces ENOTDIR for its child log path.
  567. const cwd = '/x'
  568. const ctx2 = new Context()
  569. await ctx2.plugin(SessionStore)
  570. await ctx2.plugin(SessionPersistenceJsonl, { root })
  571. await writeFile(sessionDir(root, cwd), 'x') // bucket path is now a FILE
  572. let s!: Session
  573. await ctx2.plugin(Object.assign((inner: Context) => {
  574. s = inner.sessions.create(SessionId('exists-fault'), { meta: { cwd } })
  575. }, { inject: ['sessions'] }))
  576. await expect(ctx2.sessions.flush(s)).rejects.toThrow(/ENOTDIR/)
  577. await ctx2.fiber.dispose()
  578. })
  579. it('append() to a disk-only session adopts it and repairs a crash tail', async () => {
  580. // Persist a session, then corrupt its tail, all through ONE backend.
  581. const m = meta('disk-append', '/d')
  582. await ctx.sessionPersistence.create(m)
  583. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  584. await writeFile(logPath(root, '/d', m.id), '\n{"partial crash', { flag: 'a' })
  585. // A FRESH backend with no in-memory state: append directly (no prior load)
  586. // → append must adopt from disk, and the adopt's load schedules a repair
  587. // that the same append then performs before writing.
  588. const ctx2 = new Context()
  589. await ctx2.plugin(SessionStore)
  590. await ctx2.plugin(SessionPersistenceJsonl, { root })
  591. await ctx2.sessionPersistence.append(m.id, [
  592. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  593. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  594. ] as SessionEvent[])
  595. const loaded = await ctx2.sessionPersistence.load(m.id)
  596. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  597. await ctx2.fiber.dispose()
  598. })
  599. it('a header-only log (open turn, no turn/end) preserves the open turn on load and closes it', async () => {
  600. // A session whose only durable content is an unclosed first turn. scanLog
  601. // preserves the turn/start; loadCore closes it with a synthetic
  602. // turn/end {interrupted} so the returned log is balanced.
  603. const m = meta('open-turn', '/h')
  604. await ctx.sessionPersistence.create(m)
  605. await ctx.sessionPersistence.append(m.id, [
  606. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  607. ] as SessionEvent[])
  608. const { events } = await ctx.sessionPersistence.load(m.id)
  609. expect(events.map(e => e.type)).toEqual(['turn/start', 'turn/end'])
  610. const end = events[1]!
  611. expect(end.type === 'turn/end' && end.data.reason).toEqual({ kind: 'interrupted' })
  612. })
  613. it('createCore rejects an id already on disk under a DIFFERENT cwd bucket', async () => {
  614. // Persist the id under cwd A.
  615. const a = meta('dup-id', '/projA')
  616. await ctx.sessionPersistence.create(a)
  617. await ctx.sessionPersistence.append(a.id, oneTurnLog())
  618. // A fresh backend creating the SAME id under cwd B must still refuse: load
  619. // identifies by id across all buckets, so a second log would make resume
  620. // nondeterministic. create scans every bucket, not just meta.cwd's.
  621. const ctx2 = new Context()
  622. await ctx2.plugin(SessionStore)
  623. await ctx2.plugin(SessionPersistenceJsonl, { root })
  624. await expect(ctx2.sessionPersistence.create(meta('dup-id', '/projB')))
  625. .rejects.toThrow(/already has a persisted log on disk/)
  626. await ctx2.fiber.dispose()
  627. })
  628. it('flush keeps buffered events when the append fails (no silent loss)', async () => {
  629. root = await freshRoot()
  630. const ctx2 = new Context()
  631. await ctx2.plugin(SessionStore)
  632. await ctx2.plugin(SessionPersistenceJsonl, { root })
  633. const session = ctx2.sessions.create(SessionId('flush-fail'))
  634. // A full turn lands in the write-behind buffer.
  635. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  636. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  637. // Make the durable materialize fail on the next flush.
  638. const backend = ctx2.sessionPersistence as unknown as { materialize: (...args: unknown[]) => Promise<void> }
  639. const origMat = backend.materialize.bind(backend)
  640. backend.materialize = () => Promise.reject(new Error('disk full'))
  641. await expectParallelFlushError(ctx2.parallel('session/flush', session), /disk full/)
  642. // The events are STILL buffered (not silently dropped): a retry persists them.
  643. backend.materialize = origMat
  644. await ctx2.parallel('session/flush', session)
  645. const loaded = await ctx2.sessionPersistence.load(SessionId('flush-fail'))
  646. expect(loaded.events.map(e => e.seq)).toEqual([0, 1])
  647. await ctx2.fiber.dispose()
  648. })
  649. it('rejects non-JSON event data: BigInt, function, circular, Map, undefined property', async () => {
  650. const m = meta('serial')
  651. await ctx.sessionPersistence.create(m)
  652. 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[]
  653. await expect(ctx.sessionPersistence.append(m.id, bad(1n))).rejects.toThrow(/non-JSON-serializable/)
  654. await expect(ctx.sessionPersistence.append(m.id, bad(() => 0))).rejects.toThrow(/non-JSON-serializable/)
  655. await expect(ctx.sessionPersistence.append(m.id, bad(Symbol('s')))).rejects.toThrow(/non-JSON-serializable/)
  656. await expect(ctx.sessionPersistence.append(m.id, bad(new Map()))).rejects.toThrow(/non-JSON-serializable/)
  657. await expect(ctx.sessionPersistence.append(m.id, bad(undefined))).rejects.toThrow(/non-JSON-serializable/)
  658. await expect(ctx.sessionPersistence.append(m.id, bad(Infinity))).rejects.toThrow(/non-JSON-serializable/)
  659. // a circular structure
  660. const circ: Record<string, unknown> = {}
  661. circ.self = circ
  662. await expect(ctx.sessionPersistence.append(m.id, bad(circ))).rejects.toThrow(/non-JSON-serializable/)
  663. // The session was never materialized by any of the rejected appends.
  664. expect((await ctx.sessionPersistence.list()).map(h => h.id)).not.toContain(m.id)
  665. })
  666. it('accepts well-formed JSON values (null, booleans, nested arrays/objects)', async () => {
  667. const m = meta('json-ok')
  668. await ctx.sessionPersistence.create(m)
  669. 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[]
  670. await ctx.sessionPersistence.append(m.id, ev)
  671. expect((await ctx.sessionPersistence.list()).map(h => h.id)).toContain(m.id)
  672. })
  673. it('Session.append rejects a non-serializable event at the source (never enters the log)', () => {
  674. const session = ctx.sessions.create(SessionId('reject-bad'))
  675. // Serializability is enforced at the source: Session.append throws on a BigInt-bearing
  676. // event before it enters session.events, so the durable log can never diverge from the live
  677. // log. The error therefore surfaces synchronously at append, not later during backend flush.
  678. expect(() => {
  679. session.append('user/message', { content: [{ type: 'text', text: 'bad' }], source: { kind: 'user' }, bad: 1n } as never, { surfaceOp: 'append' })
  680. }).toThrow(/non-JSON-serializable/)
  681. // The bad event was rejected, so the log stayed empty.
  682. expect(session.events.length).toBe(0)
  683. })
  684. })