zstd.spec.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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, decompressZstdPrefix, 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 decompressZstdPrefix(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. const path = logPath(root, header.cwd, header.id, 'zstd')
  224. expect(backend.locate(header)).toEqual({
  225. kind: 'jsonl',
  226. path,
  227. })
  228. const base = oneTurnLog()
  229. const events: SessionEvent[] = [
  230. ...base.slice(0, 3),
  231. ...Array.from({ length: 3 }, (_, index): SessionEvent => ({
  232. type: 'assistant/chunk',
  233. seq: 3 + index,
  234. time: 4 + index,
  235. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: `part-${index}` } },
  236. })),
  237. ...base.slice(3).map((event): SessionEvent => ({
  238. ...event,
  239. seq: event.seq + 3,
  240. time: event.time + 3,
  241. })),
  242. ]
  243. await backend.create(header)
  244. await backend.append(header.id, events)
  245. const plaintext = (await decodeCompleteFrames(await readFile(path))).toString()
  246. const recordTypes = plaintext.trimEnd().split('\n')
  247. .map(line => (JSON.parse(line) as { type: string }).type)
  248. expect(recordTypes).toContain('text-chunks')
  249. expect((await backend.load(header.id)).events).toEqual(events)
  250. })
  251. it('appends one frame per durable batch without rewriting prior bytes', async () => {
  252. const root = await freshRoot()
  253. const ctx = await mount(root)
  254. const header = meta('append-frame')
  255. await ctx.sessionPersistence.create(header)
  256. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  257. const path = logPath(root, header.cwd, header.id, 'zstd')
  258. const before = await readFile(path)
  259. const secondTurn = [
  260. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  261. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  262. ] as SessionEvent[]
  263. await ctx.sessionPersistence.append(header.id, secondTurn)
  264. const after = await readFile(path)
  265. expect(after.subarray(0, before.length)).toEqual(before)
  266. expect(scanZstdFrames(after).frames).toHaveLength(3)
  267. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
  268. })
  269. it('lists from a multi-chunk header frame without decoding a corrupt event frame', async () => {
  270. const root = await freshRoot()
  271. const ctx = await mount(root)
  272. const header = meta('large-header', `/work/${'x'.repeat(24_000)}`)
  273. await ctx.sessionPersistence.create(header)
  274. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  275. const path = logPath(root, header.cwd, header.id, 'zstd')
  276. const buffer = Buffer.from(await readFile(path))
  277. const eventFrame = scanZstdFrames(buffer).frames[1]!
  278. buffer[eventFrame.end - 1] = buffer[eventFrame.end - 1]! ^ 0xFF
  279. await writeFile(path, buffer)
  280. expect((await ctx.sessionPersistence.list()).map(item => item.id)).toEqual([header.id])
  281. await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/frame at byte .* failed validation/)
  282. })
  283. it('stops multi-frame inspection after cancellation interrupts the active decode', async () => {
  284. const root = await freshRoot()
  285. const ctx = await mount(root)
  286. const header = meta('cancel-zstd-frames')
  287. const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`)
  288. const eventFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[0])}\n`)
  289. const laterFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[1])}\n`)
  290. const stream = Buffer.concat([headerFrame, eventFrame, laterFrame])
  291. expect(scanZstdFrames(stream).frames).toHaveLength(3)
  292. const controller = new AbortController()
  293. const reason = new Error('cancel after Zstandard decode starts')
  294. const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals
  295. const zstdModule = await import('../src/zstd.ts')
  296. const decode = vi.spyOn(zstdModule, 'decompressZstdFrame')
  297. // readZstdPrefix reaches its first asynchronous decompression before it
  298. // returns this promise. The microtask abort therefore occurs after decode
  299. // starts and must prevent every later frame from reaching the decoder.
  300. const pending = reader.readZstdPrefix(stream, controller.signal)
  301. queueMicrotask(() => { controller.abort(reason) })
  302. await expect(pending).rejects.toBe(reason)
  303. expect(decode).toHaveBeenCalledTimes(1)
  304. expect(decode).toHaveBeenCalledWith(headerFrame)
  305. })
  306. it.each(['none', 'zstd'] as const)(
  307. 'observes cancellation after each async %s header read during listing',
  308. async (compression) => {
  309. const root = await freshRoot()
  310. const ctx = await mount(root, compression)
  311. const header = meta(`cancel-${compression}-header-read`, '/work')
  312. await ctx.sessionPersistence.create(header)
  313. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  314. await ctx.sessionPersistence.list()
  315. const path = logPath(root, header.cwd, header.id, compression)
  316. const probe = await open(path, 'r')
  317. const prototype = Object.getPrototypeOf(probe) as { read: HeaderRead }
  318. const originalRead = prototype.read
  319. await probe.close()
  320. const controller = new AbortController()
  321. const reason = new Error(`cancel ${compression} header read`)
  322. const read = vi.spyOn(prototype, 'read').mockImplementation(async function (
  323. this: FileHandle,
  324. buffer: Buffer,
  325. offset: number,
  326. length: number,
  327. position: number | null,
  328. ) {
  329. const result = await originalRead.call(this, buffer, offset, length, position)
  330. controller.abort(reason)
  331. return result
  332. })
  333. await expect(ctx.sessionPersistence.list(controller.signal)).rejects.toBe(reason)
  334. expect(read).toHaveBeenCalledTimes(1)
  335. },
  336. )
  337. it('preserves complete records from a torn frame and re-encodes them with crash closers', async () => {
  338. const root = await freshRoot()
  339. const ctx = await mount(root)
  340. const header = meta('recover-torn', '/proj')
  341. await ctx.sessionPersistence.create(header)
  342. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  343. const path = logPath(root, header.cwd, header.id, 'zstd')
  344. const committed = await readFile(path)
  345. const openTurn = [
  346. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  347. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  348. { type: 'assistant/chunk', seq: 8, time: 9, data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: deterministicNoise(300_000) } } },
  349. ] as SessionEvent[]
  350. const plaintext = openTurn.map(e => JSON.stringify(e)).join('\n') + '\n'
  351. const partial = await tornFrame(plaintext, (decoded) => {
  352. const newlines = decoded.match(/\n/g)?.length ?? 0
  353. return newlines >= 2 && !decoded.endsWith('\n')
  354. })
  355. await appendFile(path, partial)
  356. const loaded = await ctx.sessionPersistence.load(header.id)
  357. expect(loaded.events.map(event => event.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  358. expect(loaded.events[6]).toEqual(openTurn[0])
  359. expect(loaded.events[7]).toEqual(openTurn[1])
  360. expect(loaded.events.some(event => event.type === 'assistant/chunk' && event.seq === 8)).toBe(false)
  361. expect(loaded.events[8]?.type).toBe('step/end')
  362. expect(loaded.events[9]?.type).toBe('turn/end')
  363. const repaired = await readFile(path)
  364. expect(repaired.subarray(0, committed.length)).toEqual(committed)
  365. expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
  366. expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual(loaded.events)
  367. })
  368. it('drops a frame torn in its header before it has produced plaintext', async () => {
  369. const root = await freshRoot()
  370. const ctx = await mount(root)
  371. const header = meta('partial-magic')
  372. await ctx.sessionPersistence.create(header)
  373. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  374. const path = logPath(root, header.cwd, header.id, 'zstd')
  375. const committed = await readFile(path)
  376. await appendFile(path, MAGIC.subarray(0, 2))
  377. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual(oneTurnLog())
  378. expect(await readFile(path)).toEqual(committed)
  379. })
  380. it('recovers complete events when EOF tears only the final frame checksum', async () => {
  381. const root = await freshRoot()
  382. const ctx = await mount(root)
  383. const header = meta('partial-checksum')
  384. await ctx.sessionPersistence.create(header)
  385. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  386. const path = logPath(root, header.cwd, header.id, 'zstd')
  387. const secondTurn = [
  388. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  389. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  390. ] as SessionEvent[]
  391. const frame = await compressZstdFrame(secondTurn.map(e => JSON.stringify(e)).join('\n') + '\n')
  392. await appendFile(path, frame.subarray(0, -1))
  393. const loaded = await ctx.sessionPersistence.load(header.id)
  394. expect(loaded.events).toEqual([...oneTurnLog(), ...secondTurn])
  395. const repaired = await readFile(path)
  396. expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
  397. expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual(loaded.events)
  398. })
  399. it('rejects a complete frame containing a torn JSONL record', async () => {
  400. const root = await freshRoot()
  401. const ctx = await mount(root)
  402. const header = meta('complete-bad-jsonl')
  403. await ctx.sessionPersistence.create(header)
  404. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  405. await appendFile(
  406. logPath(root, header.cwd, header.id, 'zstd'),
  407. await compressZstdFrame('{"type":"turn/start"'),
  408. )
  409. await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/complete frame contains a torn JSONL record/)
  410. })
  411. it('rolls back a checksummed append frame when fsync fails', async () => {
  412. const root = await freshRoot()
  413. const ctx = await mount(root)
  414. const header = meta('zstd-fsync-rollback')
  415. await ctx.sessionPersistence.create(header)
  416. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  417. const path = logPath(root, header.cwd, header.id, 'zstd')
  418. const before = await readFile(path)
  419. const handle = await open(path, 'r')
  420. const prototype = Object.getPrototypeOf(handle) as { sync: () => Promise<void> }
  421. await handle.close()
  422. const realSync = prototype.sync
  423. let failed = false
  424. const spy = vi.spyOn(prototype, 'sync').mockImplementation(async function (this: FileHandle) {
  425. if (!failed) {
  426. failed = true
  427. throw new Error('simulated Zstandard fsync failure')
  428. }
  429. return realSync.call(this)
  430. })
  431. const secondTurn = [
  432. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  433. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  434. ] as SessionEvent[]
  435. await expect(ctx.sessionPersistence.append(header.id, secondTurn)).rejects.toThrow(/simulated Zstandard fsync failure/)
  436. expect(await readFile(path)).toEqual(before)
  437. spy.mockRestore()
  438. await ctx.sessionPersistence.append(header.id, secondTurn)
  439. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
  440. })
  441. it('skips empty, incomplete, and non-header compressed artifacts while rejecting malformed header frames', async () => {
  442. const root = await freshRoot()
  443. for (const [id, content] of [
  444. ['empty', Buffer.alloc(0)],
  445. ['partial', MAGIC],
  446. ['not-header', await compressZstdFrame('{"type":"turn/start"}\n')],
  447. ] as const) {
  448. const sessionId = SessionId(id)
  449. await mkdir(sessionDir(root, undefined, sessionId), { recursive: true })
  450. await writeFile(logPath(root, undefined, sessionId, 'zstd'), content)
  451. }
  452. const ctx = await mount(root)
  453. expect(await ctx.sessionPersistence.list()).toEqual([])
  454. const twoLinesId = SessionId('two-lines')
  455. await mkdir(sessionDir(root, undefined, twoLinesId), { recursive: true })
  456. await writeFile(logPath(root, undefined, twoLinesId, 'zstd'), await compressZstdFrame([
  457. JSON.stringify(toHeaderLine(meta('two-lines'))),
  458. JSON.stringify({ type: 'turn/start' }),
  459. '',
  460. ].join('\n')))
  461. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/first frame is not exactly one header line/)
  462. await expect(ctx.sessionPersistence.load(SessionId('two-lines')))
  463. .rejects.toThrow(/first frame is not exactly one header line/)
  464. })
  465. it('rejects missing, empty, and checksum-corrupt header frames on targeted reads', async () => {
  466. const root = await freshRoot()
  467. for (const id of ['partial-only', 'empty-header', 'bad-checksum']) {
  468. await mkdir(sessionDir(root, undefined, SessionId(id)), { recursive: true })
  469. }
  470. await writeFile(logPath(root, undefined, SessionId('partial-only'), 'zstd'), MAGIC)
  471. await writeFile(logPath(root, undefined, SessionId('empty-header'), 'zstd'), await compressZstdFrame(''))
  472. const corruptHeader = Buffer.from(await compressZstdFrame(`${JSON.stringify(toHeaderLine(meta('bad-checksum')))}\n`))
  473. corruptHeader[corruptHeader.length - 1] = corruptHeader[corruptHeader.length - 1]! ^ 0xFF
  474. await writeFile(logPath(root, undefined, SessionId('bad-checksum'), 'zstd'), corruptHeader)
  475. const ctx = await mount(root)
  476. await expect(ctx.sessionPersistence.load(SessionId('partial-only')))
  477. .rejects.toThrow(/empty or header-less Zstandard session log/)
  478. await expect(ctx.sessionPersistence.load(SessionId('empty-header')))
  479. .rejects.toThrow(/first frame is not exactly one header line/)
  480. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/header frame failed validation/)
  481. })
  482. })
  483. describe('SessionPersistenceJsonl: encoding selection', () => {
  484. it('rejects roots owned by the opposite encoding in both directions', async () => {
  485. const rawRoot = await freshRoot('dsh-jsonl-raw-mismatch-')
  486. const raw = await mount(rawRoot, 'none')
  487. const rawHeader = meta('raw-log')
  488. await raw.sessionPersistence.create(rawHeader)
  489. await raw.sessionPersistence.append(rawHeader.id, oneTurnLog())
  490. const defaultBackend = await mount(rawRoot)
  491. await expect(defaultBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "zstd"/)
  492. const zstdRoot = await freshRoot('dsh-jsonl-zstd-mismatch-')
  493. const zstd = await mount(zstdRoot)
  494. const zstdHeader = meta('zstd-log')
  495. await zstd.sessionPersistence.create(zstdHeader)
  496. await zstd.sessionPersistence.append(zstdHeader.id, oneTurnLog())
  497. const rawBackend = await mount(zstdRoot, 'none')
  498. await expect(rawBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "none"/)
  499. })
  500. it('rechecks targeted artifacts and listing after an initially empty root', async () => {
  501. const root = await freshRoot()
  502. const ctx = await mount(root)
  503. expect(await ctx.sessionPersistence.list()).toEqual([])
  504. const loadHeader = meta('late-raw-load', '/late')
  505. await mkdir(sessionDir(root, loadHeader.cwd, loadHeader.id), { recursive: true })
  506. await writeFile(logPath(root, loadHeader.cwd, loadHeader.id, 'none'), [
  507. JSON.stringify(toHeaderLine(loadHeader)),
  508. ...oneTurnLog().map(e => JSON.stringify(e)),
  509. '',
  510. ].join('\n'))
  511. await expect(ctx.sessionPersistence.load(loadHeader.id)).rejects.toThrow(/uses \.jsonl/)
  512. await expect((ctx.sessionPersistence as SessionPersistenceJsonl).loadStored(loadHeader.id))
  513. .rejects.toThrow(/uses \.jsonl/)
  514. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/uses \.jsonl/)
  515. })
  516. it('refuses materialization when an opposite artifact appears after create', async () => {
  517. const root = await freshRoot()
  518. const ctx = await mount(root)
  519. await ctx.sessionPersistence.list()
  520. const header = meta('late-raw-materialize', '/late')
  521. await ctx.sessionPersistence.create(header)
  522. await mkdir(sessionDir(root, header.cwd, header.id), { recursive: true })
  523. await writeFile(logPath(root, header.cwd, header.id, 'none'), [
  524. JSON.stringify(toHeaderLine(header)),
  525. ...oneTurnLog().map(e => JSON.stringify(e)),
  526. '',
  527. ].join('\n'))
  528. await expect(ctx.sessionPersistence.append(header.id, oneTurnLog())).rejects.toThrow(/uses \.jsonl/)
  529. expect((await readdir(sessionDir(root, header.cwd, header.id))).some(name => name.endsWith('.jsonl.zstd'))).toBe(false)
  530. })
  531. })