zstd.spec.ts 38 KB

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