zstd.spec.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { appendFile, mkdir, mkdtemp, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
  4. import type { FileHandle } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  10. import { logPath, scanLog, sessionDir, toHeaderLine, type JsonlCompression } from '../src/format.ts'
  11. import { compressZstdFrame, decompressZstdFrame, scanZstdFrames } from '../src/zstd.ts'
  12. import { runPersistenceContract, meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
  13. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  14. const MAGIC = Buffer.from([0x28, 0xB5, 0x2F, 0xFD])
  15. const roots: string[] = []
  16. const contexts: Context[] = []
  17. interface ZstdReaderInternals {
  18. readZstdPrefix(buffer: Buffer, signal?: AbortSignal): Promise<unknown>
  19. }
  20. type HeaderRead = (
  21. this: FileHandle,
  22. buffer: Buffer,
  23. offset: number,
  24. length: number,
  25. position: number | null,
  26. ) => Promise<{ bytesRead: number; buffer: Buffer }>
  27. async function freshRoot(prefix = 'dsh-jsonl-zstd-'): Promise<string> {
  28. const root = await mkdtemp(join(tmpdir(), prefix))
  29. roots.push(root)
  30. return root
  31. }
  32. async function mount(root: string, compression?: JsonlCompression): Promise<Context> {
  33. const ctx = new Context()
  34. contexts.push(ctx)
  35. await ctx.plugin(SessionStore)
  36. await ctx.plugin(SessionPersistenceJsonl, {
  37. root,
  38. ...(compression === undefined ? {} : { compression }),
  39. })
  40. return ctx
  41. }
  42. async function decodeCompleteFrames(buffer: Buffer): Promise<Buffer> {
  43. const { frames, tornStart } = scanZstdFrames(buffer)
  44. expect(tornStart).toBeUndefined()
  45. const plaintext: Buffer[] = []
  46. for (const frame of frames) {
  47. plaintext.push(await decompressZstdFrame(buffer.subarray(frame.start, frame.end)))
  48. }
  49. return Buffer.concat(plaintext)
  50. }
  51. async function tornFrame(
  52. plaintext: string,
  53. accepts: (decoded: string) => boolean,
  54. ): Promise<Buffer> {
  55. const frame = await compressZstdFrame(plaintext)
  56. const candidateEnds = [
  57. frame.length - 1,
  58. frame.length - 4,
  59. ...[0.9, 0.75, 0.6, 0.5, 0.4, 0.25].map(ratio => Math.floor(frame.length * ratio)),
  60. ]
  61. for (const end of candidateEnds) {
  62. const candidate = frame.subarray(0, end)
  63. if (scanZstdFrames(candidate).tornStart !== 0) continue
  64. try {
  65. const decoded = (await decompressZstdFrame(candidate)).toString('utf8')
  66. if (accepts(decoded)) return candidate
  67. } catch {
  68. // Some early cuts precede the first decodable block; keep searching for
  69. // a cut that exercises partial-plaintext recovery.
  70. }
  71. }
  72. throw new Error('test fixture could not produce the requested torn Zstandard frame')
  73. }
  74. function deterministicNoise(length: number): string {
  75. let state = 0x12345678
  76. let output = ''
  77. for (let index = 0; index < length; index++) {
  78. state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0
  79. output += String.fromCharCode(33 + (state % 90))
  80. }
  81. return output
  82. }
  83. function emptyStructuralFrame(descriptor: number): Buffer {
  84. const contentSizeFlag = descriptor >>> 6
  85. const singleSegment = (descriptor & 0x20) !== 0
  86. const dictionaryBytes = [0, 1, 2, 4][descriptor & 0x03]!
  87. const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
  88. const variableHeader = Buffer.alloc((singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes)
  89. const lastEmptyRawBlock = Buffer.from([1, 0, 0])
  90. const checksum = (descriptor & 0x04) === 0 ? Buffer.alloc(0) : Buffer.alloc(4)
  91. return Buffer.concat([MAGIC, Buffer.from([descriptor]), variableHeader, lastEmptyRawBlock, checksum])
  92. }
  93. afterEach(async () => {
  94. vi.restoreAllMocks()
  95. for (const ctx of contexts.splice(0).reverse()) await ctx.fiber.dispose()
  96. for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
  97. })
  98. runPersistenceContract('jsonl-zstd', async () => {
  99. const root = await mkdtemp(join(tmpdir(), 'dsh-jsonl-zstd-contract-'))
  100. const ctx = new Context()
  101. await ctx.plugin(SessionStore)
  102. const fiber = await ctx.plugin(SessionPersistenceJsonl, { root })
  103. return {
  104. persistence: ctx.sessionPersistence,
  105. dispose: async () => {
  106. await fiber.dispose()
  107. await rm(root, { recursive: true, force: true })
  108. },
  109. }
  110. })
  111. runCoordinatorContract('jsonl-zstd', async (): Promise<CoordinatorFixture> => {
  112. const root = await mkdtemp(join(tmpdir(), 'dsh-jsonl-zstd-coordinator-'))
  113. return {
  114. mount: async ctx => ctx.plugin(SessionPersistenceJsonl, { root }),
  115. corruptTail: async (id, cwd) => {
  116. const line = JSON.stringify({
  117. type: 'assistant/chunk',
  118. seq: 8,
  119. time: 9,
  120. data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: deterministicNoise(300_000) } },
  121. }) + '\n'
  122. const partial = await tornFrame(line, decoded => decoded.length > 0 && !decoded.endsWith('\n'))
  123. await appendFile(logPath(root, cwd, id, 'zstd'), partial)
  124. },
  125. cleanup: async () => { await rm(root, { recursive: true, force: true }) },
  126. }
  127. })
  128. describe('Zstandard frame structure', () => {
  129. it('scans concatenated checksummed frames and honors a frame limit', async () => {
  130. const first = await compressZstdFrame('header\n')
  131. const second = await compressZstdFrame('event\n')
  132. const stream = Buffer.concat([first, second])
  133. expect(scanZstdFrames(Buffer.alloc(0))).toEqual({ frames: [] })
  134. expect(scanZstdFrames(stream)).toEqual({
  135. frames: [{ start: 0, end: first.length }, { start: first.length, end: stream.length }],
  136. })
  137. expect(scanZstdFrames(stream, 1)).toEqual({ frames: [{ start: 0, end: first.length }] })
  138. expect(first[4]! & 0x04).toBe(0x04)
  139. expect(second[4]! & 0x04).toBe(0x04)
  140. expect((await decompressZstdFrame(first)).toString()).toBe('header\n')
  141. })
  142. it('distinguishes incomplete frame regions from invalid complete structure', () => {
  143. expect(scanZstdFrames(MAGIC.subarray(0, 2))).toEqual({ frames: [], tornStart: 0 })
  144. expect(scanZstdFrames(MAGIC)).toEqual({ frames: [], tornStart: 0 })
  145. expect(() => scanZstdFrames(Buffer.alloc(4))).toThrow(/invalid frame magic/)
  146. expect(() => scanZstdFrames(Buffer.concat([MAGIC, Buffer.from([0x08])]))).toThrow(/reserved frame-header bit/)
  147. // Non-single-segment descriptor with no window descriptor.
  148. expect(scanZstdFrames(Buffer.concat([MAGIC, Buffer.from([0x00])]))).toEqual({ frames: [], tornStart: 0 })
  149. // Single-segment header followed by only two bytes of the three-byte block header.
  150. expect(scanZstdFrames(Buffer.concat([MAGIC, Buffer.from([0x20, 0x00, 0x01, 0x00])]))).toEqual({
  151. frames: [],
  152. tornStart: 0,
  153. })
  154. const rawFiveBytes = Buffer.from([(5 << 3) | 1, 0, 0])
  155. expect(scanZstdFrames(Buffer.concat([
  156. MAGIC,
  157. Buffer.from([0x20, 0x00]),
  158. rawFiveBytes,
  159. Buffer.from([0x01, 0x02]),
  160. ]))).toEqual({ frames: [], tornStart: 0 })
  161. const reservedBlock = Buffer.concat([
  162. MAGIC,
  163. Buffer.from([0x20, 0x00, 0x07, 0x00, 0x00]),
  164. ])
  165. expect(() => scanZstdFrames(reservedBlock)).toThrow(/reserved block type/)
  166. })
  167. it('covers standard header variants, RLE blocks, multiple blocks, and checksums', () => {
  168. for (const descriptor of [0x00, 0x21, 0x42, 0x83, 0xE3]) {
  169. const frame = emptyStructuralFrame(descriptor)
  170. expect(scanZstdFrames(frame)).toEqual({ frames: [{ start: 0, end: frame.length }] })
  171. }
  172. const rle = Buffer.concat([
  173. MAGIC,
  174. Buffer.from([0x20, 0x01]),
  175. Buffer.from([(1 << 3) | (1 << 1) | 1, 0, 0]),
  176. Buffer.from([0x41]),
  177. ])
  178. expect(scanZstdFrames(rle)).toEqual({ frames: [{ start: 0, end: rle.length }] })
  179. const twoBlocks = Buffer.concat([
  180. MAGIC,
  181. Buffer.from([0x20, 0x00]),
  182. Buffer.from([0, 0, 0]),
  183. Buffer.from([1, 0, 0]),
  184. ])
  185. expect(scanZstdFrames(twoBlocks)).toEqual({ frames: [{ start: 0, end: twoBlocks.length }] })
  186. const checksummed = emptyStructuralFrame(0x24)
  187. expect(scanZstdFrames(checksummed.subarray(0, -1))).toEqual({ frames: [], tornStart: 0 })
  188. expect(scanZstdFrames(checksummed)).toEqual({ frames: [{ start: 0, end: checksummed.length }] })
  189. })
  190. })
  191. describe('SessionPersistenceJsonl: default Zstandard encoding', () => {
  192. it('writes .jsonl.zstd by default with one header frame and one first-batch frame', async () => {
  193. const root = await freshRoot()
  194. const ctx = await mount(root)
  195. const header = meta('default-zstd', '/work')
  196. await ctx.sessionPersistence.create(header)
  197. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  198. const path = logPath(root, header.cwd, header.id, 'zstd')
  199. const buffer = await readFile(path)
  200. expect(buffer.subarray(0, 4)).toEqual(MAGIC)
  201. await expect(stat(logPath(root, header.cwd, header.id, 'none'))).rejects.toThrow()
  202. expect(ctx.sessionPersistence.locate(header)).toEqual({ kind: 'jsonl', path })
  203. const scan = scanZstdFrames(buffer)
  204. expect(scan.frames).toHaveLength(2)
  205. const plaintext = await decodeCompleteFrames(buffer)
  206. expect(plaintext.toString()).toBe([
  207. JSON.stringify(toHeaderLine(header)),
  208. ...oneTurnLog().map(e => JSON.stringify(e)),
  209. '',
  210. ].join('\n'))
  211. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual(oneTurnLog())
  212. })
  213. it('resolves the default when a programmatic wrapper bypasses Loader schema normalization', async () => {
  214. const root = await freshRoot()
  215. const ctx = new Context()
  216. contexts.push(ctx)
  217. await ctx.plugin(SessionStore)
  218. let backend!: SessionPersistenceJsonl
  219. await ctx.plugin(Object.assign((inner: Context) => {
  220. backend = new SessionPersistenceJsonl(inner, { root })
  221. }, { inject: ['sessions'] }))
  222. const header = meta('direct-default')
  223. expect(backend.locate(header)).toEqual({
  224. kind: 'jsonl',
  225. path: logPath(root, header.cwd, header.id, 'zstd'),
  226. })
  227. })
  228. it('appends one frame per durable batch without rewriting prior bytes', async () => {
  229. const root = await freshRoot()
  230. const ctx = await mount(root)
  231. const header = meta('append-frame')
  232. await ctx.sessionPersistence.create(header)
  233. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  234. const path = logPath(root, header.cwd, header.id, 'zstd')
  235. const before = await readFile(path)
  236. const secondTurn = [
  237. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  238. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  239. ] as SessionEvent[]
  240. await ctx.sessionPersistence.append(header.id, secondTurn)
  241. const after = await readFile(path)
  242. expect(after.subarray(0, before.length)).toEqual(before)
  243. expect(scanZstdFrames(after).frames).toHaveLength(3)
  244. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
  245. })
  246. it('lists from a multi-chunk header frame without decoding a corrupt event frame', async () => {
  247. const root = await freshRoot()
  248. const ctx = await mount(root)
  249. const header = meta('large-header', `/work/${'x'.repeat(24_000)}`)
  250. await ctx.sessionPersistence.create(header)
  251. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  252. const path = logPath(root, header.cwd, header.id, 'zstd')
  253. const buffer = Buffer.from(await readFile(path))
  254. const eventFrame = scanZstdFrames(buffer).frames[1]!
  255. buffer[eventFrame.end - 1] = buffer[eventFrame.end - 1]! ^ 0xFF
  256. await writeFile(path, buffer)
  257. expect((await ctx.sessionPersistence.list()).map(item => item.id)).toEqual([header.id])
  258. await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/frame at byte .* failed validation/)
  259. })
  260. it('stops multi-frame inspection after cancellation interrupts the active decode', async () => {
  261. const root = await freshRoot()
  262. const ctx = await mount(root)
  263. const header = meta('cancel-zstd-frames')
  264. const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`)
  265. const eventFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[0])}\n`)
  266. const laterFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[1])}\n`)
  267. const stream = Buffer.concat([headerFrame, eventFrame, laterFrame])
  268. expect(scanZstdFrames(stream).frames).toHaveLength(3)
  269. const controller = new AbortController()
  270. const reason = new Error('cancel after Zstandard decode starts')
  271. const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals
  272. const zstdModule = await import('../src/zstd.ts')
  273. const decode = vi.spyOn(zstdModule, 'decompressZstdFrame')
  274. // readZstdPrefix reaches its first asynchronous decompression before it
  275. // returns this promise. The microtask abort therefore occurs after decode
  276. // starts and must prevent every later frame from reaching the decoder.
  277. const pending = reader.readZstdPrefix(stream, controller.signal)
  278. queueMicrotask(() => { controller.abort(reason) })
  279. await expect(pending).rejects.toBe(reason)
  280. expect(decode).toHaveBeenCalledTimes(1)
  281. expect(decode).toHaveBeenCalledWith(headerFrame)
  282. })
  283. it.each(['none', 'zstd'] as const)(
  284. 'observes cancellation after each async %s header read during listing',
  285. async (compression) => {
  286. const root = await freshRoot()
  287. const ctx = await mount(root, compression)
  288. const header = meta(`cancel-${compression}-header-read`, '/work')
  289. await ctx.sessionPersistence.create(header)
  290. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  291. await ctx.sessionPersistence.list()
  292. const path = logPath(root, header.cwd, header.id, compression)
  293. const probe = await open(path, 'r')
  294. const prototype = Object.getPrototypeOf(probe) as { read: HeaderRead }
  295. const originalRead = prototype.read
  296. await probe.close()
  297. const controller = new AbortController()
  298. const reason = new Error(`cancel ${compression} header read`)
  299. const read = vi.spyOn(prototype, 'read').mockImplementation(async function (
  300. this: FileHandle,
  301. buffer: Buffer,
  302. offset: number,
  303. length: number,
  304. position: number | null,
  305. ) {
  306. const result = await originalRead.call(this, buffer, offset, length, position)
  307. controller.abort(reason)
  308. return result
  309. })
  310. await expect(ctx.sessionPersistence.list(controller.signal)).rejects.toBe(reason)
  311. expect(read).toHaveBeenCalledTimes(1)
  312. },
  313. )
  314. it('preserves complete records from a torn frame and re-encodes them with crash closers', async () => {
  315. const root = await freshRoot()
  316. const ctx = await mount(root)
  317. const header = meta('recover-torn', '/proj')
  318. await ctx.sessionPersistence.create(header)
  319. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  320. const path = logPath(root, header.cwd, header.id, 'zstd')
  321. const committed = await readFile(path)
  322. const openTurn = [
  323. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  324. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  325. { type: 'assistant/chunk', seq: 8, time: 9, data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: deterministicNoise(300_000) } } },
  326. ] as SessionEvent[]
  327. const plaintext = openTurn.map(e => JSON.stringify(e)).join('\n') + '\n'
  328. const partial = await tornFrame(plaintext, (decoded) => {
  329. const newlines = decoded.match(/\n/g)?.length ?? 0
  330. return newlines >= 2 && !decoded.endsWith('\n')
  331. })
  332. await appendFile(path, partial)
  333. const loaded = await ctx.sessionPersistence.load(header.id)
  334. expect(loaded.events.map(event => event.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  335. expect(loaded.events[6]).toEqual(openTurn[0])
  336. expect(loaded.events[7]).toEqual(openTurn[1])
  337. expect(loaded.events.some(event => event.type === 'assistant/chunk' && event.seq === 8)).toBe(false)
  338. expect(loaded.events[8]?.type).toBe('step/end')
  339. expect(loaded.events[9]?.type).toBe('turn/end')
  340. const repaired = await readFile(path)
  341. expect(repaired.subarray(0, committed.length)).toEqual(committed)
  342. expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
  343. expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual(loaded.events)
  344. })
  345. it('drops a frame torn in its header before it has produced plaintext', async () => {
  346. const root = await freshRoot()
  347. const ctx = await mount(root)
  348. const header = meta('partial-magic')
  349. await ctx.sessionPersistence.create(header)
  350. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  351. const path = logPath(root, header.cwd, header.id, 'zstd')
  352. const committed = await readFile(path)
  353. await appendFile(path, MAGIC.subarray(0, 2))
  354. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual(oneTurnLog())
  355. expect(await readFile(path)).toEqual(committed)
  356. })
  357. it('recovers complete events when EOF tears only the final frame checksum', async () => {
  358. const root = await freshRoot()
  359. const ctx = await mount(root)
  360. const header = meta('partial-checksum')
  361. await ctx.sessionPersistence.create(header)
  362. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  363. const path = logPath(root, header.cwd, header.id, 'zstd')
  364. const secondTurn = [
  365. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  366. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  367. ] as SessionEvent[]
  368. const frame = await compressZstdFrame(secondTurn.map(e => JSON.stringify(e)).join('\n') + '\n')
  369. await appendFile(path, frame.subarray(0, -1))
  370. const loaded = await ctx.sessionPersistence.load(header.id)
  371. expect(loaded.events).toEqual([...oneTurnLog(), ...secondTurn])
  372. const repaired = await readFile(path)
  373. expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
  374. expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual(loaded.events)
  375. })
  376. it('rejects a complete frame containing a torn JSONL record', async () => {
  377. const root = await freshRoot()
  378. const ctx = await mount(root)
  379. const header = meta('complete-bad-jsonl')
  380. await ctx.sessionPersistence.create(header)
  381. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  382. await appendFile(
  383. logPath(root, header.cwd, header.id, 'zstd'),
  384. await compressZstdFrame('{"type":"turn/start"'),
  385. )
  386. await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/complete frame contains a torn JSONL record/)
  387. })
  388. it('rolls back a checksummed append frame when fsync fails', async () => {
  389. const root = await freshRoot()
  390. const ctx = await mount(root)
  391. const header = meta('zstd-fsync-rollback')
  392. await ctx.sessionPersistence.create(header)
  393. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  394. const path = logPath(root, header.cwd, header.id, 'zstd')
  395. const before = await readFile(path)
  396. const handle = await open(path, 'r')
  397. const prototype = Object.getPrototypeOf(handle) as { sync: () => Promise<void> }
  398. await handle.close()
  399. const realSync = prototype.sync
  400. let failed = false
  401. const spy = vi.spyOn(prototype, 'sync').mockImplementation(async function (this: FileHandle) {
  402. if (!failed) {
  403. failed = true
  404. throw new Error('simulated Zstandard fsync failure')
  405. }
  406. return realSync.call(this)
  407. })
  408. const secondTurn = [
  409. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  410. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  411. ] as SessionEvent[]
  412. await expect(ctx.sessionPersistence.append(header.id, secondTurn)).rejects.toThrow(/simulated Zstandard fsync failure/)
  413. expect(await readFile(path)).toEqual(before)
  414. spy.mockRestore()
  415. await ctx.sessionPersistence.append(header.id, secondTurn)
  416. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
  417. })
  418. it('skips empty, incomplete, and non-header compressed artifacts while rejecting malformed header frames', async () => {
  419. const root = await freshRoot()
  420. for (const [id, content] of [
  421. ['empty', Buffer.alloc(0)],
  422. ['partial', MAGIC],
  423. ['not-header', await compressZstdFrame('{"type":"turn/start"}\n')],
  424. ] as const) {
  425. const sessionId = SessionId(id)
  426. await mkdir(sessionDir(root, undefined, sessionId), { recursive: true })
  427. await writeFile(logPath(root, undefined, sessionId, 'zstd'), content)
  428. }
  429. const ctx = await mount(root)
  430. expect(await ctx.sessionPersistence.list()).toEqual([])
  431. const twoLinesId = SessionId('two-lines')
  432. await mkdir(sessionDir(root, undefined, twoLinesId), { recursive: true })
  433. await writeFile(logPath(root, undefined, twoLinesId, 'zstd'), await compressZstdFrame([
  434. JSON.stringify(toHeaderLine(meta('two-lines'))),
  435. JSON.stringify({ type: 'turn/start' }),
  436. '',
  437. ].join('\n')))
  438. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/first frame is not exactly one header line/)
  439. await expect(ctx.sessionPersistence.load(SessionId('two-lines')))
  440. .rejects.toThrow(/first frame is not exactly one header line/)
  441. })
  442. it('rejects missing, empty, and checksum-corrupt header frames on targeted reads', async () => {
  443. const root = await freshRoot()
  444. for (const id of ['partial-only', 'empty-header', 'bad-checksum']) {
  445. await mkdir(sessionDir(root, undefined, SessionId(id)), { recursive: true })
  446. }
  447. await writeFile(logPath(root, undefined, SessionId('partial-only'), 'zstd'), MAGIC)
  448. await writeFile(logPath(root, undefined, SessionId('empty-header'), 'zstd'), await compressZstdFrame(''))
  449. const corruptHeader = Buffer.from(await compressZstdFrame(`${JSON.stringify(toHeaderLine(meta('bad-checksum')))}\n`))
  450. corruptHeader[corruptHeader.length - 1] = corruptHeader[corruptHeader.length - 1]! ^ 0xFF
  451. await writeFile(logPath(root, undefined, SessionId('bad-checksum'), 'zstd'), corruptHeader)
  452. const ctx = await mount(root)
  453. await expect(ctx.sessionPersistence.load(SessionId('partial-only')))
  454. .rejects.toThrow(/empty or header-less Zstandard session log/)
  455. await expect(ctx.sessionPersistence.load(SessionId('empty-header')))
  456. .rejects.toThrow(/first frame is not exactly one header line/)
  457. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/header frame failed validation/)
  458. })
  459. })
  460. describe('SessionPersistenceJsonl: encoding selection', () => {
  461. it('rejects roots owned by the opposite encoding in both directions', async () => {
  462. const rawRoot = await freshRoot('dsh-jsonl-raw-mismatch-')
  463. const raw = await mount(rawRoot, 'none')
  464. const rawHeader = meta('raw-log')
  465. await raw.sessionPersistence.create(rawHeader)
  466. await raw.sessionPersistence.append(rawHeader.id, oneTurnLog())
  467. const defaultBackend = await mount(rawRoot)
  468. await expect(defaultBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "zstd"/)
  469. const zstdRoot = await freshRoot('dsh-jsonl-zstd-mismatch-')
  470. const zstd = await mount(zstdRoot)
  471. const zstdHeader = meta('zstd-log')
  472. await zstd.sessionPersistence.create(zstdHeader)
  473. await zstd.sessionPersistence.append(zstdHeader.id, oneTurnLog())
  474. const rawBackend = await mount(zstdRoot, 'none')
  475. await expect(rawBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "none"/)
  476. })
  477. it('rechecks targeted artifacts and listing after an initially empty root', async () => {
  478. const root = await freshRoot()
  479. const ctx = await mount(root)
  480. expect(await ctx.sessionPersistence.list()).toEqual([])
  481. const loadHeader = meta('late-raw-load', '/late')
  482. await mkdir(sessionDir(root, loadHeader.cwd, loadHeader.id), { recursive: true })
  483. await writeFile(logPath(root, loadHeader.cwd, loadHeader.id, 'none'), [
  484. JSON.stringify(toHeaderLine(loadHeader)),
  485. ...oneTurnLog().map(e => JSON.stringify(e)),
  486. '',
  487. ].join('\n'))
  488. await expect(ctx.sessionPersistence.load(loadHeader.id)).rejects.toThrow(/uses \.jsonl/)
  489. await expect((ctx.sessionPersistence as SessionPersistenceJsonl).loadStored(loadHeader.id))
  490. .rejects.toThrow(/uses \.jsonl/)
  491. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/uses \.jsonl/)
  492. })
  493. it('refuses materialization when an opposite artifact appears after create', async () => {
  494. const root = await freshRoot()
  495. const ctx = await mount(root)
  496. await ctx.sessionPersistence.list()
  497. const header = meta('late-raw-materialize', '/late')
  498. await ctx.sessionPersistence.create(header)
  499. await mkdir(sessionDir(root, header.cwd, header.id), { recursive: true })
  500. await writeFile(logPath(root, header.cwd, header.id, 'none'), [
  501. JSON.stringify(toHeaderLine(header)),
  502. ...oneTurnLog().map(e => JSON.stringify(e)),
  503. '',
  504. ].join('\n'))
  505. await expect(ctx.sessionPersistence.append(header.id, oneTurnLog())).rejects.toThrow(/uses \.jsonl/)
  506. expect((await readdir(sessionDir(root, header.cwd, header.id))).some(name => name.endsWith('.jsonl.zstd'))).toBe(false)
  507. })
  508. })