zstd.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/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 { performance } from 'node:perf_hooks'
  8. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  9. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  10. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  11. import { logPath, scanLog, sessionDir, toHeaderLine, type JsonlCompression } from '../src/format.ts'
  12. import {
  13. compressZstdFrame, createZstdFrameDecoder, decompressZstdFrame, decompressZstdPrefix, scanZstdFrames,
  14. type ZstdFrameDecoder,
  15. } from '../src/zstd.ts'
  16. import { NodePrivateZstdFrameDecoder } from '../src/zstd-private-decoder.ts'
  17. import { PublicZstdFrameDecoder } from '../src/zstd-public-decoder.ts'
  18. import { runPersistenceContract, meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
  19. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  20. const MAGIC = Buffer.from([0x28, 0xB5, 0x2F, 0xFD])
  21. const roots: string[] = []
  22. const contexts: Context[] = []
  23. interface ZstdReaderInternals {
  24. readZstdPrefix(buffer: Buffer, signal?: AbortSignal): Promise<{ events: SessionEvent[] }>
  25. }
  26. type HeaderRead = (
  27. this: FileHandle,
  28. buffer: Buffer,
  29. offset: number,
  30. length: number,
  31. position: number | null,
  32. ) => Promise<{ bytesRead: number; buffer: Buffer }>
  33. async function freshRoot(prefix = 'dsh-jsonl-zstd-'): Promise<string> {
  34. const root = await mkdtemp(join(tmpdir(), prefix))
  35. roots.push(root)
  36. return root
  37. }
  38. async function mount(root: string, compression?: JsonlCompression): Promise<Context> {
  39. const ctx = new Context()
  40. contexts.push(ctx)
  41. await ctx.plugin(SessionStore)
  42. await ctx.plugin(JsonlSessionPersistence, {
  43. root,
  44. ...(compression === undefined ? {} : { compression }),
  45. })
  46. return ctx
  47. }
  48. async function decodeCompleteFrames(buffer: Buffer): Promise<Buffer> {
  49. const { frames, tornStart } = scanZstdFrames(buffer)
  50. expect(tornStart).toBeUndefined()
  51. const plaintext: Buffer[] = []
  52. for (const frame of frames) {
  53. plaintext.push(await decompressZstdFrame(buffer.subarray(frame.start, frame.end)))
  54. }
  55. return Buffer.concat(plaintext)
  56. }
  57. async function tornFrame(
  58. plaintext: string,
  59. accepts: (decoded: string) => boolean,
  60. ): Promise<Buffer> {
  61. const frame = await compressZstdFrame(plaintext)
  62. const candidateEnds = [
  63. frame.length - 1,
  64. frame.length - 4,
  65. ...[0.9, 0.75, 0.6, 0.5, 0.4, 0.25].map(ratio => Math.floor(frame.length * ratio)),
  66. ]
  67. for (const end of candidateEnds) {
  68. const candidate = frame.subarray(0, end)
  69. if (scanZstdFrames(candidate).tornStart !== 0) continue
  70. try {
  71. const decoded = (await decompressZstdPrefix(candidate)).toString('utf8')
  72. if (accepts(decoded)) return candidate
  73. } catch {
  74. // Some early cuts precede the first decodable block; keep searching for
  75. // a cut that exercises partial-plaintext recovery.
  76. }
  77. }
  78. throw new Error('test fixture could not produce the requested torn Zstandard frame')
  79. }
  80. function deterministicNoise(length: number): string {
  81. let state = 0x12345678
  82. let output = ''
  83. for (let index = 0; index < length; index++) {
  84. state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0
  85. output += String.fromCharCode(33 + (state % 90))
  86. }
  87. return output
  88. }
  89. function emptyStructuralFrame(descriptor: number): Buffer {
  90. const contentSizeFlag = descriptor >>> 6
  91. const singleSegment = (descriptor & 0x20) !== 0
  92. const dictionaryBytes = [0, 1, 2, 4][descriptor & 0x03]!
  93. const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
  94. const variableHeader = Buffer.alloc((singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes)
  95. const lastEmptyRawBlock = Buffer.from([1, 0, 0])
  96. const checksum = (descriptor & 0x04) === 0 ? Buffer.alloc(0) : Buffer.alloc(4)
  97. return Buffer.concat([MAGIC, Buffer.from([descriptor]), variableHeader, lastEmptyRawBlock, checksum])
  98. }
  99. afterEach(async () => {
  100. vi.restoreAllMocks()
  101. for (const ctx of contexts.splice(0).reverse()) await ctx.fiber.dispose()
  102. for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
  103. })
  104. runPersistenceContract('jsonl-zstd', async () => {
  105. const root = await mkdtemp(join(tmpdir(), 'dsh-jsonl-zstd-contract-'))
  106. const ctx = new Context()
  107. await ctx.plugin(SessionStore)
  108. const fiber = await ctx.plugin(JsonlSessionPersistence, { root })
  109. return {
  110. persistence: ctx.sessionPersistence,
  111. dispose: async () => {
  112. await fiber.dispose()
  113. await rm(root, { recursive: true, force: true })
  114. },
  115. }
  116. })
  117. runCoordinatorContract('jsonl-zstd', async (): Promise<CoordinatorFixture> => {
  118. const root = await mkdtemp(join(tmpdir(), 'dsh-jsonl-zstd-coordinator-'))
  119. return {
  120. mount: async ctx => ctx.plugin(JsonlSessionPersistence, { root }),
  121. corruptTail: async (id, cwd) => {
  122. const line = JSON.stringify({
  123. type: 'assistant/chunk',
  124. seq: 8,
  125. time: 9,
  126. data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: deterministicNoise(300_000) } },
  127. }) + '\n'
  128. const partial = await tornFrame(line, decoded => decoded.length > 0 && !decoded.endsWith('\n'))
  129. await appendFile(logPath(root, cwd, id, 'zstd'), partial)
  130. },
  131. cleanup: async () => { await rm(root, { recursive: true, force: true }) },
  132. }
  133. })
  134. describe('Zstandard frame structure', () => {
  135. it('scans concatenated checksummed frames and honors a frame limit', async () => {
  136. const first = await compressZstdFrame('header\n')
  137. const second = await compressZstdFrame('event\n')
  138. const stream = Buffer.concat([first, second])
  139. expect(scanZstdFrames(Buffer.alloc(0))).toEqual({ frames: [] })
  140. expect(scanZstdFrames(stream)).toEqual({
  141. frames: [{ start: 0, end: first.length }, { start: first.length, end: stream.length }],
  142. })
  143. expect(scanZstdFrames(stream, 1)).toEqual({ frames: [{ start: 0, end: first.length }] })
  144. expect(first[4]! & 0x04).toBe(0x04)
  145. expect(second[4]! & 0x04).toBe(0x04)
  146. expect((await decompressZstdFrame(first)).toString()).toBe('header\n')
  147. const decoder = createZstdFrameDecoder()
  148. try {
  149. const plaintext = Array.from(decoder.decode(stream, scanZstdFrames(stream).frames), chunk => Buffer.from(chunk))
  150. expect(Buffer.concat(plaintext).toString()).toBe('header\nevent\n')
  151. } finally {
  152. decoder.close()
  153. }
  154. })
  155. it('keeps the public and Node-private synchronous decoders interchangeable', async () => {
  156. const frames = [await compressZstdFrame('first\n'), await compressZstdFrame('second\n')]
  157. const stream = Buffer.concat(frames)
  158. const ranges = scanZstdFrames(stream).frames
  159. const privateDecoder = NodePrivateZstdFrameDecoder.create()
  160. expect(privateDecoder).toBeDefined()
  161. for (const decoder of [new PublicZstdFrameDecoder(), privateDecoder!]) {
  162. try {
  163. const plaintext = Array.from(decoder.decode(stream, ranges), chunk => Buffer.from(chunk))
  164. expect(plaintext).toHaveLength(2)
  165. expect(Buffer.concat(plaintext).toString()).toBe('first\nsecond\n')
  166. } finally {
  167. decoder.close()
  168. }
  169. }
  170. })
  171. it('falls back to the public decoder when the private Node contract is unavailable', () => {
  172. vi.spyOn(NodePrivateZstdFrameDecoder, 'create').mockReturnValue(undefined)
  173. const decoder = createZstdFrameDecoder()
  174. expect(decoder).toBeInstanceOf(PublicZstdFrameDecoder)
  175. decoder.close()
  176. })
  177. it('enforces decoder lifecycle and checksum errors through both implementations', async () => {
  178. const frame = await compressZstdFrame('frame\n')
  179. const range = [{ start: 0, end: frame.length }]
  180. const corrupt = Buffer.from(frame)
  181. corrupt[corrupt.length - 1] = corrupt[corrupt.length - 1]! ^ 0xFF
  182. const factories: Array<() => ZstdFrameDecoder> = [
  183. () => new PublicZstdFrameDecoder(),
  184. () => NodePrivateZstdFrameDecoder.create()!,
  185. ]
  186. for (const create of factories) {
  187. const interrupted = create()
  188. const iterator = interrupted.decode(frame, range)
  189. expect(iterator.next().value?.toString()).toBe('frame\n')
  190. iterator.return()
  191. expect(() => Array.from(interrupted.decode(frame, range))).toThrow(/already started/)
  192. interrupted.close()
  193. const closed = create()
  194. closed.close()
  195. closed.close()
  196. expect(() => Array.from(closed.decode(frame, range))).toThrow(/closed/)
  197. const invalid = create()
  198. expect(() => Array.from(invalid.decode(corrupt, range))).toThrow(/frame at byte 0 failed validation/)
  199. }
  200. })
  201. it('assembles private-decoder output at and beyond its reusable chunk boundary', async () => {
  202. for (const length of [8, 9]) {
  203. const plaintext = Buffer.alloc(length, 0x61)
  204. const frame = await compressZstdFrame(plaintext)
  205. const decoder = NodePrivateZstdFrameDecoder.create()!
  206. ;(decoder as unknown as { output: Buffer }).output = Buffer.allocUnsafe(8)
  207. const [decoded] = Array.from(
  208. decoder.decode(frame, [{ start: 0, end: frame.length }]),
  209. chunk => Buffer.from(chunk),
  210. )
  211. expect(decoded).toEqual(plaintext)
  212. }
  213. })
  214. it('normalizes private decoder stream failures', async () => {
  215. interface PrivateDecoderInternals {
  216. stream: {
  217. [key: symbol]: unknown
  218. emit(event: string, error: Error): boolean
  219. }
  220. errorKey: symbol
  221. }
  222. const frame = await compressZstdFrame('frame\n')
  223. const range = [{ start: 0, end: frame.length }]
  224. const emitted = NodePrivateZstdFrameDecoder.create()!
  225. const emittedInternals = emitted as unknown as PrivateDecoderInternals
  226. const first = new Error('first emitted decoder failure')
  227. emittedInternals.stream.emit('error', first)
  228. emittedInternals.stream.emit('error', new Error('later emitted decoder failure'))
  229. try {
  230. Array.from(emitted.decode(frame, range))
  231. throw new Error('expected emitted decoder failure')
  232. } catch (error) {
  233. expect((error as Error).cause).toBe(first)
  234. }
  235. for (const internalFailure of [new Error('internal decoder failure'), 'not an Error']) {
  236. const decoder = NodePrivateZstdFrameDecoder.create()!
  237. const internals = decoder as unknown as PrivateDecoderInternals
  238. internals.stream[internals.errorKey] = internalFailure
  239. try {
  240. Array.from(decoder.decode(frame, range))
  241. throw new Error('expected internal decoder failure')
  242. } catch (error) {
  243. const cause = (error as Error).cause
  244. if (internalFailure instanceof Error) {
  245. expect(cause).toBe(internalFailure)
  246. } else {
  247. expect(cause).toMatchObject({ message: 'Zstandard decoder exposed a non-Error internal failure' })
  248. }
  249. }
  250. }
  251. })
  252. it('distinguishes incomplete frame regions from invalid complete structure', () => {
  253. expect(scanZstdFrames(MAGIC.subarray(0, 2))).toEqual({ frames: [], tornStart: 0 })
  254. expect(scanZstdFrames(MAGIC)).toEqual({ frames: [], tornStart: 0 })
  255. expect(() => scanZstdFrames(Buffer.alloc(4))).toThrow(/invalid frame magic/)
  256. expect(() => scanZstdFrames(Buffer.concat([MAGIC, Buffer.from([0x08])]))).toThrow(/reserved frame-header bit/)
  257. // Non-single-segment descriptor with no window descriptor.
  258. expect(scanZstdFrames(Buffer.concat([MAGIC, Buffer.from([0x00])]))).toEqual({ frames: [], tornStart: 0 })
  259. // Single-segment header followed by only two bytes of the three-byte block header.
  260. expect(scanZstdFrames(Buffer.concat([MAGIC, Buffer.from([0x20, 0x00, 0x01, 0x00])]))).toEqual({
  261. frames: [],
  262. tornStart: 0,
  263. })
  264. const rawFiveBytes = Buffer.from([(5 << 3) | 1, 0, 0])
  265. expect(scanZstdFrames(Buffer.concat([
  266. MAGIC,
  267. Buffer.from([0x20, 0x00]),
  268. rawFiveBytes,
  269. Buffer.from([0x01, 0x02]),
  270. ]))).toEqual({ frames: [], tornStart: 0 })
  271. const reservedBlock = Buffer.concat([
  272. MAGIC,
  273. Buffer.from([0x20, 0x00, 0x07, 0x00, 0x00]),
  274. ])
  275. expect(() => scanZstdFrames(reservedBlock)).toThrow(/reserved block type/)
  276. })
  277. it('covers standard header variants, RLE blocks, multiple blocks, and checksums', () => {
  278. for (const descriptor of [0x00, 0x21, 0x42, 0x83, 0xE3]) {
  279. const frame = emptyStructuralFrame(descriptor)
  280. expect(scanZstdFrames(frame)).toEqual({ frames: [{ start: 0, end: frame.length }] })
  281. }
  282. const rle = Buffer.concat([
  283. MAGIC,
  284. Buffer.from([0x20, 0x01]),
  285. Buffer.from([(1 << 3) | (1 << 1) | 1, 0, 0]),
  286. Buffer.from([0x41]),
  287. ])
  288. expect(scanZstdFrames(rle)).toEqual({ frames: [{ start: 0, end: rle.length }] })
  289. const twoBlocks = Buffer.concat([
  290. MAGIC,
  291. Buffer.from([0x20, 0x00]),
  292. Buffer.from([0, 0, 0]),
  293. Buffer.from([1, 0, 0]),
  294. ])
  295. expect(scanZstdFrames(twoBlocks)).toEqual({ frames: [{ start: 0, end: twoBlocks.length }] })
  296. const checksummed = emptyStructuralFrame(0x24)
  297. expect(scanZstdFrames(checksummed.subarray(0, -1))).toEqual({ frames: [], tornStart: 0 })
  298. expect(scanZstdFrames(checksummed)).toEqual({ frames: [{ start: 0, end: checksummed.length }] })
  299. })
  300. })
  301. describe('JsonlSessionPersistence: default Zstandard encoding', () => {
  302. it('materializes an explicitly durable empty session as one header frame', async () => {
  303. const root = await freshRoot()
  304. const ctx = await mount(root)
  305. const session = ctx.sessions.create(SessionId('empty-zstd'), { meta: { cwd: '/work' } })
  306. await ctx.sessionPersistence.ensureMaterialized(session)
  307. const buffer = await readFile(logPath(root, '/work', session.id, 'zstd'))
  308. expect(scanZstdFrames(buffer).frames).toHaveLength(1)
  309. expect((await decodeCompleteFrames(buffer)).toString()).toBe(`${JSON.stringify(toHeaderLine(session.header))}\n`)
  310. await expect(ctx.sessionPersistence.load(session.id)).resolves.toEqual({ meta: session.header, events: [] })
  311. })
  312. it('writes .jsonl.zstd by default with one header frame and one first-batch frame', async () => {
  313. const root = await freshRoot()
  314. const ctx = await mount(root)
  315. const header = meta('default-zstd', '/work')
  316. await ctx.sessionPersistence.create(header)
  317. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  318. const path = logPath(root, header.cwd, header.id, 'zstd')
  319. const buffer = await readFile(path)
  320. expect(buffer.subarray(0, 4)).toEqual(MAGIC)
  321. await expect(stat(logPath(root, header.cwd, header.id, 'none'))).rejects.toThrow()
  322. expect(ctx.sessionPersistence.locate(header)).toEqual({ kind: 'jsonl', path })
  323. const scan = scanZstdFrames(buffer)
  324. expect(scan.frames).toHaveLength(2)
  325. const plaintext = await decodeCompleteFrames(buffer)
  326. expect(plaintext.toString()).toBe([
  327. JSON.stringify(toHeaderLine(header)),
  328. ...oneTurnLog().map(e => JSON.stringify(e)),
  329. '',
  330. ].join('\n'))
  331. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual(oneTurnLog())
  332. })
  333. it('readRaw decodes the compressed artifact back to the original JSONL text', async () => {
  334. const root = await freshRoot()
  335. const ctx = await mount(root)
  336. const header = meta('raw-read-zstd', '/work')
  337. await ctx.sessionPersistence.create(header)
  338. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  339. const raw = await ctx.sessionPersistence.readRaw(header.id)
  340. expect(raw).toBeDefined()
  341. // The logical name drops the physical encoding suffix.
  342. expect(raw!.filename).toBe('session.jsonl')
  343. expect(raw!.meta.id).toBe(header.id)
  344. expect(raw!.content).toBe([
  345. JSON.stringify(toHeaderLine(header)),
  346. ...oneTurnLog().map(e => JSON.stringify(e)),
  347. '',
  348. ].join('\n'))
  349. const scanned = scanLog(Buffer.from(raw!.content))
  350. expect(scanned.events.map(event => event.type)).toEqual(oneTurnLog().map(event => event.type))
  351. })
  352. it('readRaw rejects a present zstd artifact that carries no frame', async () => {
  353. const root = await freshRoot()
  354. const ctx = await mount(root)
  355. const header = meta('raw-zero-frame', '/work')
  356. await ctx.sessionPersistence.create(header)
  357. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  358. // The path still exists, so zero frames is corruption rather than absence.
  359. await writeFile(logPath(root, '/work', header.id, 'zstd'), Buffer.alloc(0))
  360. await expect(ctx.sessionPersistence.readRaw(header.id))
  361. .rejects.toThrow('empty or header-less Zstandard session log')
  362. })
  363. it('resolves the default when a programmatic wrapper bypasses Loader schema normalization', async () => {
  364. const root = await freshRoot()
  365. const ctx = new Context()
  366. contexts.push(ctx)
  367. await ctx.plugin(SessionStore)
  368. let backend!: JsonlSessionPersistence
  369. await ctx.plugin(Object.assign((inner: Context) => {
  370. backend = new JsonlSessionPersistence(inner, { root })
  371. }, { inject: ['sessions'] }))
  372. const header = meta('direct-default')
  373. const path = logPath(root, header.cwd, header.id, 'zstd')
  374. expect(backend.locate(header)).toEqual({
  375. kind: 'jsonl',
  376. path,
  377. })
  378. const base = oneTurnLog()
  379. const events: SessionEvent[] = [
  380. ...base.slice(0, 3),
  381. ...Array.from({ length: 3 }, (_, index): SessionEvent => ({
  382. type: 'assistant/chunk',
  383. seq: 3 + index,
  384. time: 4 + index,
  385. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: `part-${index}` } },
  386. })),
  387. ...base.slice(3).map((event): SessionEvent => ({
  388. ...event,
  389. seq: event.seq + 3,
  390. time: event.time + 3,
  391. })),
  392. ]
  393. await backend.create(header)
  394. await backend.append(header.id, events)
  395. const plaintext = (await decodeCompleteFrames(await readFile(path))).toString()
  396. const recordTypes = plaintext.trimEnd().split('\n')
  397. .map(line => (JSON.parse(line) as { type: string }).type)
  398. expect(recordTypes).toContain('text-chunks')
  399. expect((await backend.load(header.id)).events).toEqual(events)
  400. })
  401. it('appends one frame per durable batch without rewriting prior bytes', async () => {
  402. const root = await freshRoot()
  403. const ctx = await mount(root)
  404. const header = meta('append-frame')
  405. await ctx.sessionPersistence.create(header)
  406. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  407. const path = logPath(root, header.cwd, header.id, 'zstd')
  408. const before = await readFile(path)
  409. const secondTurn = [
  410. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  411. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  412. ] as SessionEvent[]
  413. await ctx.sessionPersistence.append(header.id, secondTurn)
  414. const after = await readFile(path)
  415. expect(after.subarray(0, before.length)).toEqual(before)
  416. expect(scanZstdFrames(after).frames).toHaveLength(3)
  417. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
  418. })
  419. it('lists from a multi-chunk header frame without decoding a corrupt event frame', async () => {
  420. const root = await freshRoot()
  421. const ctx = await mount(root)
  422. const header = meta('large-header', `/work/${'x'.repeat(24_000)}`)
  423. await ctx.sessionPersistence.create(header)
  424. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  425. const path = logPath(root, header.cwd, header.id, 'zstd')
  426. const buffer = Buffer.from(await readFile(path))
  427. const eventFrame = scanZstdFrames(buffer).frames[1]!
  428. buffer[eventFrame.end - 1] = buffer[eventFrame.end - 1]! ^ 0xFF
  429. await writeFile(path, buffer)
  430. expect((await ctx.sessionPersistence.list()).map(item => item.id)).toEqual([header.id])
  431. await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/frame at byte .* failed validation/)
  432. })
  433. it('stops multi-frame inspection when cancellation arrives at a slice deadline', async () => {
  434. const root = await freshRoot()
  435. const ctx = await mount(root)
  436. const header = meta('cancel-zstd-frames')
  437. const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`)
  438. const eventFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[0])}\n`)
  439. const laterFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[1])}\n`)
  440. const stream = Buffer.concat([headerFrame, eventFrame, laterFrame])
  441. const controller = new AbortController()
  442. const reason = new Error('cancel after Zstandard decode starts')
  443. const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals
  444. vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValue(501)
  445. const pending = reader.readZstdPrefix(stream, controller.signal)
  446. queueMicrotask(() => { controller.abort(reason) })
  447. await expect(pending).rejects.toBe(reason)
  448. })
  449. it('continues decoding every frame after a slice deadline yields', async () => {
  450. const root = await freshRoot()
  451. const ctx = await mount(root)
  452. const header = meta('yield-zstd-frames')
  453. const events = oneTurnLog().slice(0, 2)
  454. const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`)
  455. const eventFrames = await Promise.all(events.map(async event => (
  456. compressZstdFrame(`${JSON.stringify(event)}\n`)
  457. )))
  458. const stream = Buffer.concat([headerFrame, ...eventFrames])
  459. const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals
  460. vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValue(501)
  461. const prefix = await reader.readZstdPrefix(stream)
  462. expect(prefix.events).toEqual(events)
  463. })
  464. it.each(['none', 'zstd'] as const)(
  465. 'observes cancellation after each async %s header read during listing',
  466. async (compression) => {
  467. const root = await freshRoot()
  468. const ctx = await mount(root, compression)
  469. const header = meta(`cancel-${compression}-header-read`, '/work')
  470. await ctx.sessionPersistence.create(header)
  471. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  472. await ctx.sessionPersistence.list()
  473. const path = logPath(root, header.cwd, header.id, compression)
  474. const probe = await open(path, 'r')
  475. const prototype = Object.getPrototypeOf(probe) as { read: HeaderRead }
  476. const originalRead = prototype.read
  477. await probe.close()
  478. const controller = new AbortController()
  479. const reason = new Error(`cancel ${compression} header read`)
  480. const read = vi.spyOn(prototype, 'read').mockImplementation(async function (
  481. this: FileHandle,
  482. buffer: Buffer,
  483. offset: number,
  484. length: number,
  485. position: number | null,
  486. ) {
  487. const result = await originalRead.call(this, buffer, offset, length, position)
  488. controller.abort(reason)
  489. return result
  490. })
  491. await expect(ctx.sessionPersistence.list(controller.signal)).rejects.toBe(reason)
  492. expect(read).toHaveBeenCalledTimes(1)
  493. },
  494. )
  495. it('preserves complete records from a torn frame and re-encodes them with crash closers', async () => {
  496. const root = await freshRoot()
  497. const ctx = await mount(root)
  498. const header = meta('recover-torn', '/proj')
  499. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  500. await ctx.sessionPersistence.create(header)
  501. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  502. const path = logPath(root, header.cwd, header.id, 'zstd')
  503. const committed = await readFile(path)
  504. const openTurn = [
  505. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  506. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  507. { type: 'assistant/chunk', seq: 8, time: 9, data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: deterministicNoise(300_000) } } },
  508. ] as SessionEvent[]
  509. const plaintext = openTurn.map(e => JSON.stringify(e)).join('\n') + '\n'
  510. const partial = await tornFrame(plaintext, (decoded) => {
  511. const newlines = decoded.match(/\n/g)?.length ?? 0
  512. return newlines >= 2 && !decoded.endsWith('\n')
  513. })
  514. await appendFile(path, partial)
  515. const loaded = await ctx.sessionPersistence.load(header.id)
  516. expect(loaded.events.map(event => event.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  517. expect(loaded.events[6]).toEqual(openTurn[0])
  518. expect(loaded.events[7]).toEqual(openTurn[1])
  519. expect(loaded.events.some(event => event.type === 'assistant/chunk' && event.seq === 8)).toBe(false)
  520. expect(loaded.events[8]?.type).toBe('step/end')
  521. expect(loaded.events[9]?.type).toBe('turn/end')
  522. expect(warn).toHaveBeenCalledWith('session-persistence-jsonl: session "recover-torn" recovered from a torn tail; incomplete tail bytes were discarded')
  523. const repaired = await readFile(path)
  524. expect(repaired.subarray(0, committed.length)).toEqual(committed)
  525. expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
  526. expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual(loaded.events)
  527. })
  528. it('drops a frame torn in its header before it has produced plaintext', async () => {
  529. const root = await freshRoot()
  530. const ctx = await mount(root)
  531. const header = meta('partial-magic')
  532. await ctx.sessionPersistence.create(header)
  533. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  534. const path = logPath(root, header.cwd, header.id, 'zstd')
  535. const committed = await readFile(path)
  536. await appendFile(path, MAGIC.subarray(0, 2))
  537. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual(oneTurnLog())
  538. expect(await readFile(path)).toEqual(committed)
  539. })
  540. it('recovers complete events when EOF tears only the final frame checksum', async () => {
  541. const root = await freshRoot()
  542. const ctx = await mount(root)
  543. const header = meta('partial-checksum')
  544. await ctx.sessionPersistence.create(header)
  545. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  546. const path = logPath(root, header.cwd, header.id, 'zstd')
  547. const secondTurn = [
  548. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  549. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  550. ] as SessionEvent[]
  551. const frame = await compressZstdFrame(secondTurn.map(e => JSON.stringify(e)).join('\n') + '\n')
  552. await appendFile(path, frame.subarray(0, -1))
  553. const loaded = await ctx.sessionPersistence.load(header.id)
  554. expect(loaded.events).toEqual([...oneTurnLog(), ...secondTurn])
  555. const repaired = await readFile(path)
  556. expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
  557. expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual(loaded.events)
  558. })
  559. it('rejects a complete frame containing a torn JSONL record', async () => {
  560. const root = await freshRoot()
  561. const ctx = await mount(root)
  562. const header = meta('complete-bad-jsonl')
  563. await ctx.sessionPersistence.create(header)
  564. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  565. await appendFile(
  566. logPath(root, header.cwd, header.id, 'zstd'),
  567. await compressZstdFrame('{"type":"turn/start"'),
  568. )
  569. await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/complete frame contains a torn JSONL record/)
  570. })
  571. it('rolls back a checksummed append frame when fsync fails', async () => {
  572. const root = await freshRoot()
  573. const ctx = await mount(root)
  574. const header = meta('zstd-fsync-rollback')
  575. await ctx.sessionPersistence.create(header)
  576. await ctx.sessionPersistence.append(header.id, oneTurnLog())
  577. const path = logPath(root, header.cwd, header.id, 'zstd')
  578. const before = await readFile(path)
  579. const handle = await open(path, 'r')
  580. const prototype = Object.getPrototypeOf(handle) as { sync: () => Promise<void> }
  581. await handle.close()
  582. const realSync = prototype.sync
  583. let failed = false
  584. const spy = vi.spyOn(prototype, 'sync').mockImplementation(async function (this: FileHandle) {
  585. if (!failed) {
  586. failed = true
  587. throw new Error('simulated Zstandard fsync failure')
  588. }
  589. return realSync.call(this)
  590. })
  591. const secondTurn = [
  592. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  593. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  594. ] as SessionEvent[]
  595. await expect(ctx.sessionPersistence.append(header.id, secondTurn)).rejects.toThrow(/simulated Zstandard fsync failure/)
  596. expect(await readFile(path)).toEqual(before)
  597. spy.mockRestore()
  598. await ctx.sessionPersistence.append(header.id, secondTurn)
  599. expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
  600. })
  601. it('skips empty, incomplete, and non-header compressed artifacts while rejecting malformed header frames', async () => {
  602. const root = await freshRoot()
  603. for (const [id, content] of [
  604. ['empty', Buffer.alloc(0)],
  605. ['partial', MAGIC],
  606. ['not-header', await compressZstdFrame('{"type":"turn/start"}\n')],
  607. ] as const) {
  608. const sessionId = SessionId(id)
  609. await mkdir(sessionDir(root, undefined, sessionId), { recursive: true })
  610. await writeFile(logPath(root, undefined, sessionId, 'zstd'), content)
  611. }
  612. const ctx = await mount(root)
  613. expect(await ctx.sessionPersistence.list()).toEqual([])
  614. const twoLinesId = SessionId('two-lines')
  615. await mkdir(sessionDir(root, undefined, twoLinesId), { recursive: true })
  616. await writeFile(logPath(root, undefined, twoLinesId, 'zstd'), await compressZstdFrame([
  617. JSON.stringify(toHeaderLine(meta('two-lines'))),
  618. JSON.stringify({ type: 'turn/start' }),
  619. '',
  620. ].join('\n')))
  621. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/first frame is not exactly one header line/)
  622. await expect(ctx.sessionPersistence.load(SessionId('two-lines')))
  623. .rejects.toThrow(/first frame is not exactly one header line/)
  624. })
  625. it('rejects missing, empty, and checksum-corrupt header frames on targeted reads', async () => {
  626. const root = await freshRoot()
  627. for (const id of ['partial-only', 'empty-header', 'bad-checksum']) {
  628. await mkdir(sessionDir(root, undefined, SessionId(id)), { recursive: true })
  629. }
  630. await writeFile(logPath(root, undefined, SessionId('partial-only'), 'zstd'), MAGIC)
  631. await writeFile(logPath(root, undefined, SessionId('empty-header'), 'zstd'), await compressZstdFrame(''))
  632. const corruptHeader = Buffer.from(await compressZstdFrame(`${JSON.stringify(toHeaderLine(meta('bad-checksum')))}\n`))
  633. corruptHeader[corruptHeader.length - 1] = corruptHeader[corruptHeader.length - 1]! ^ 0xFF
  634. await writeFile(logPath(root, undefined, SessionId('bad-checksum'), 'zstd'), corruptHeader)
  635. const ctx = await mount(root)
  636. await expect(ctx.sessionPersistence.load(SessionId('partial-only')))
  637. .rejects.toThrow(/empty or header-less Zstandard session log/)
  638. await expect(ctx.sessionPersistence.load(SessionId('empty-header')))
  639. .rejects.toThrow(/first frame is not exactly one header line/)
  640. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/header frame failed validation/)
  641. })
  642. })
  643. describe('JsonlSessionPersistence: encoding selection', () => {
  644. it('rejects roots owned by the opposite encoding in both directions', async () => {
  645. const rawRoot = await freshRoot('dsh-jsonl-raw-mismatch-')
  646. const raw = await mount(rawRoot, 'none')
  647. const rawHeader = meta('raw-log')
  648. await raw.sessionPersistence.create(rawHeader)
  649. await raw.sessionPersistence.append(rawHeader.id, oneTurnLog())
  650. const defaultBackend = await mount(rawRoot)
  651. await expect(defaultBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "zstd"/)
  652. const zstdRoot = await freshRoot('dsh-jsonl-zstd-mismatch-')
  653. const zstd = await mount(zstdRoot)
  654. const zstdHeader = meta('zstd-log')
  655. await zstd.sessionPersistence.create(zstdHeader)
  656. await zstd.sessionPersistence.append(zstdHeader.id, oneTurnLog())
  657. const rawBackend = await mount(zstdRoot, 'none')
  658. await expect(rawBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "none"/)
  659. })
  660. it('rechecks targeted artifacts and listing after an initially empty root', async () => {
  661. const root = await freshRoot()
  662. const ctx = await mount(root)
  663. expect(await ctx.sessionPersistence.list()).toEqual([])
  664. const loadHeader = meta('late-raw-load', '/late')
  665. await mkdir(sessionDir(root, loadHeader.cwd, loadHeader.id), { recursive: true })
  666. await writeFile(logPath(root, loadHeader.cwd, loadHeader.id, 'none'), [
  667. JSON.stringify(toHeaderLine(loadHeader)),
  668. ...oneTurnLog().map(e => JSON.stringify(e)),
  669. '',
  670. ].join('\n'))
  671. await expect(ctx.sessionPersistence.load(loadHeader.id)).rejects.toThrow(/uses \.jsonl/)
  672. await expect((ctx.sessionPersistence as JsonlSessionPersistence).loadStored(loadHeader.id))
  673. .rejects.toThrow(/uses \.jsonl/)
  674. await expect(ctx.sessionPersistence.list()).rejects.toThrow(/uses \.jsonl/)
  675. })
  676. it('refuses materialization when an opposite artifact appears after create', async () => {
  677. const root = await freshRoot()
  678. const ctx = await mount(root)
  679. await ctx.sessionPersistence.list()
  680. const header = meta('late-raw-materialize', '/late')
  681. await ctx.sessionPersistence.create(header)
  682. await mkdir(sessionDir(root, header.cwd, header.id), { recursive: true })
  683. await writeFile(logPath(root, header.cwd, header.id, 'none'), [
  684. JSON.stringify(toHeaderLine(header)),
  685. ...oneTurnLog().map(e => JSON.stringify(e)),
  686. '',
  687. ].join('\n'))
  688. await expect(ctx.sessionPersistence.append(header.id, oneTurnLog())).rejects.toThrow(/uses \.jsonl/)
  689. expect((await readdir(sessionDir(root, header.cwd, header.id))).some(name => name.endsWith('.jsonl.zstd'))).toBe(false)
  690. })
  691. })