session-fixture-layout.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /** Canonical packed-row and envelope projection helpers for repository session fixtures. */
  2. import { deepStrictEqual } from 'node:assert'
  3. import { execFileSync } from 'node:child_process'
  4. import { existsSync, readFileSync } from 'node:fs'
  5. import { resolve } from 'node:path'
  6. import {
  7. decodeSeqRanges,
  8. SessionLogOffset,
  9. type SessionEvent,
  10. } from '@deepseek-ai/dsh-session'
  11. import type { SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
  12. import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
  13. /** Physical persistence artifacts validated by the WebWorker runtime fixture spec. */
  14. const WEBWORKER_PHYSICAL_SESSION_FIXTURE_ROOT =
  15. 'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/'
  16. /** Installed-runtime snapshots that preserve the JSONL writer's physical encoding. */
  17. const PYTHON_RUNTIME_PHYSICAL_SESSION_FIXTURE_ROOT =
  18. 'scripts/snapshots/python-sdk-single-exe/'
  19. /** One repository session fixture and its canonical projected representation. */
  20. export interface SessionFixtureLayout {
  21. /** Repository-relative path with `/` separators. */
  22. path: string
  23. /** Current fixture bytes decoded as UTF-8. */
  24. source: string
  25. /** Canonical projected fixture bytes. */
  26. canonical: string
  27. }
  28. /**
  29. * Whether a repository JSONL preserves physical persistence encoding rather
  30. * than the logical event projection owned by this script.
  31. * @param path - Repository-relative path with `/` separators.
  32. * @returns True for physical WebWorker and installed-runtime session logs.
  33. */
  34. export function isPhysicalSessionFixture(path: string): boolean {
  35. if (path.startsWith(WEBWORKER_PHYSICAL_SESSION_FIXTURE_ROOT)) {
  36. return /\/session(?:\.v[1-9]\d*)?\.jsonl$/.test(path)
  37. }
  38. return path.startsWith(PYTHON_RUNTIME_PHYSICAL_SESSION_FIXTURE_ROOT)
  39. && /\/session(?:\.[1-9]\d*)?(?:\.v[1-9]\d*)?\.jsonl$/.test(path)
  40. }
  41. function isSessionHeader(value: unknown): boolean {
  42. return value !== null && typeof value === 'object' && (value as { type?: unknown }).type === 'session'
  43. }
  44. function validationHeader(value: unknown): unknown {
  45. if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
  46. const header = { ...value as Record<string, unknown> }
  47. if (header.version === 0 && !Object.hasOwn(header, 'delegationDepth')) header.delegationDepth = 0
  48. if (typeof header.cwd === 'string' && /^\{\{cwd\}\}(?:\/|$)/.test(header.cwd)) {
  49. header.cwd = header.cwd.replace('{{cwd}}', '/dsh-snapshot-cwd')
  50. }
  51. return header
  52. }
  53. function validationRow(source: Readonly<Record<string, unknown>>): Record<string, unknown> {
  54. if (source.type !== 'request/header') return { ...source }
  55. const data = source.data
  56. if (data === null || typeof data !== 'object' || Array.isArray(data)) return { ...source }
  57. const header = (data as Record<string, unknown>).header
  58. if (header === null || typeof header !== 'object' || Array.isArray(header)) return { ...source }
  59. if ((header as Record<string, unknown>).tools !== '{{tools}}') return { ...source }
  60. return {
  61. ...source,
  62. data: {
  63. ...data,
  64. header: { ...header, tools: [] },
  65. },
  66. }
  67. }
  68. function restoreRequestHeaderTokens(
  69. events: readonly SessionEvent[],
  70. rows: readonly Readonly<Record<string, unknown>>[],
  71. ): SessionEvent[] {
  72. const sources = rows.filter(row => row.type === 'request/header')
  73. let sourceIndex = 0
  74. return events.map((event) => {
  75. if (event.type !== 'request/header') return event
  76. const source = sources[sourceIndex]
  77. sourceIndex += 1
  78. const sourceData = source?.data
  79. const sourceHeader = sourceData !== null && typeof sourceData === 'object' && !Array.isArray(sourceData)
  80. ? (sourceData as Record<string, unknown>).header
  81. : undefined
  82. if (sourceHeader === null || typeof sourceHeader !== 'object' || Array.isArray(sourceHeader)
  83. || (sourceHeader as Record<string, unknown>).tools !== '{{tools}}') return event
  84. return {
  85. ...event,
  86. data: {
  87. ...event.data,
  88. header: {
  89. ...(event.data as unknown as { header: Record<string, unknown> }).header,
  90. tools: '{{tools}}',
  91. },
  92. },
  93. } as SessionEvent
  94. })
  95. }
  96. function renderFixture(headerLine: string, events: readonly SessionEvent[]): string {
  97. return [
  98. headerLine,
  99. ...events.map((event) => {
  100. const record = { ...event } as unknown as Record<string, unknown>
  101. delete record.seq
  102. delete record.time
  103. return JSON.stringify(record)
  104. }),
  105. '',
  106. ].join('\n')
  107. }
  108. function projectedRowCardinality(record: Readonly<Record<string, unknown>>): number {
  109. const data = record.data
  110. if (data === null || typeof data !== 'object' || Array.isArray(data)) return 1
  111. const key = record.type === 'tool-call-chunks' ? 'args' : 'texts'
  112. const values = (data as Record<string, unknown>)[key]
  113. return Array.isArray(values) && values.length > 0 ? values.length : 1
  114. }
  115. function parseFixtureObjectLine(line: string, lineNumber: number): Record<string, unknown> {
  116. let value: unknown
  117. try {
  118. value = JSON.parse(line) as unknown
  119. } catch (error) {
  120. throw new Error(`session snapshot line ${lineNumber} contains invalid JSON`, { cause: error })
  121. }
  122. if (value === null || typeof value !== 'object' || Array.isArray(value)) {
  123. throw new Error(`session snapshot line ${lineNumber} must be a JSON object`)
  124. }
  125. return value as Record<string, unknown>
  126. }
  127. function parseFixtureRows(content: string, headerValue: unknown): SessionEvent[] {
  128. const rows: Record<string, unknown>[] = []
  129. const rowLines: number[] = []
  130. const eventLines: number[] = []
  131. let nextSeq: SessionLogOffsetType = SessionLogOffset(0)
  132. let headerSkipped = false
  133. for (const [index, line] of content.split(/\r?\n/).entries()) {
  134. if (line.trim().length === 0) continue
  135. if (!headerSkipped) {
  136. headerSkipped = true
  137. continue
  138. }
  139. const record = parseFixtureObjectLine(line, index + 1)
  140. const packed = record.type === 'text-chunks'
  141. || record.type === 'reasoning-chunks'
  142. || record.type === 'tool-call-chunks'
  143. const seqKey = packed ? 'seq0' : 'seq'
  144. const timeKey = packed ? 'time0' : 'time'
  145. if (!Object.hasOwn(record, seqKey)) record[seqKey] = nextSeq
  146. if (!Object.hasOwn(record, timeKey)) record[timeKey] = 0
  147. rows.push(record)
  148. rowLines.push(index + 1)
  149. const cardinality = projectedRowCardinality(record)
  150. for (let offset = 0; offset < cardinality; offset += 1) eventLines.push(index + 1)
  151. nextSeq = SessionLogOffset(nextSeq + cardinality)
  152. }
  153. // Versionless protocol fixtures and current projected snapshots use scalar
  154. // event rows. Current snapshots may contain owner-restored scrub tokens such
  155. // as `{{tools}}`; semantic replay restores those sidecars, while this layout
  156. // gate owns only envelopes, provenance ranges, and one-event-per-row form.
  157. const projectedCurrent = headerValue !== null
  158. && typeof headerValue === 'object'
  159. && !Array.isArray(headerValue)
  160. && (headerValue as Record<string, unknown>).version === sessionFormatCatalog.currentVersion
  161. if (headerValue === null || typeof headerValue !== 'object' || Array.isArray(headerValue)
  162. || !Object.hasOwn(headerValue, 'version') || projectedCurrent) {
  163. return rows.map((source, index) => {
  164. const record = { ...source }
  165. try {
  166. if (record.type === 'text-chunks'
  167. || record.type === 'reasoning-chunks'
  168. || record.type === 'tool-call-chunks') {
  169. throw new Error('current projected fixtures cannot contain legacy packed rows')
  170. }
  171. if (Object.hasOwn(record, 'sourceEventSeqs')) {
  172. record.sourceEventSeqs = decodeSeqRanges(record.sourceEventSeqs)
  173. }
  174. return record as unknown as SessionEvent
  175. } catch (error) {
  176. const detail = error instanceof Error ? error.message : String(error)
  177. throw new Error(`session snapshot line ${rowLines[index] ?? 1}: ${detail}`, { cause: error })
  178. }
  179. })
  180. }
  181. let restore: ReturnType<typeof sessionFormatCatalog.createRestore>
  182. try {
  183. restore = sessionFormatCatalog.createRestore(validationHeader(headerValue), {
  184. recovery: 'strict',
  185. validation: 'current',
  186. })
  187. } catch (error) {
  188. const detail = error instanceof Error ? error.message : String(error)
  189. throw new Error(`session snapshot line 1: ${detail}`, { cause: error })
  190. }
  191. for (const [index, row] of rows.entries()) {
  192. try {
  193. restore.decodeRow(validationRow(row))
  194. } catch (error) {
  195. const detail = error instanceof Error ? error.message : String(error)
  196. throw new Error(`session snapshot line ${rowLines[index] ?? 1}: ${detail}`, { cause: error })
  197. }
  198. }
  199. try {
  200. return restoreRequestHeaderTokens(
  201. [...restore.finish().events] as unknown as SessionEvent[],
  202. rows,
  203. )
  204. } catch (error) {
  205. const detail = error instanceof Error ? error.message : String(error)
  206. const line = fixtureDiagnosticLine(error, rowLines, eventLines)
  207. throw new Error(`session snapshot line ${line}: ${detail}`, { cause: error })
  208. }
  209. }
  210. function fixtureDiagnosticLine(
  211. error: unknown,
  212. rowLines: readonly number[],
  213. eventLines: readonly number[],
  214. ): number {
  215. const detail = error instanceof Error && error.cause instanceof Error
  216. ? error.cause.message
  217. : error instanceof Error ? error.message : String(error)
  218. const physicalRow = /^released Session row (\d+)/.exec(detail)
  219. if (physicalRow !== null) return rowLines[Number(physicalRow[1])] ?? 1
  220. const event = /Session event (\d+)/.exec(detail)
  221. ?? / at seq (\d+)/.exec(detail)
  222. ?? /inherited Session cut (\d+)/.exec(detail)
  223. return event === null ? 1 : eventLines[Number(event[1])] ?? 1
  224. }
  225. function withoutEnvelope(events: readonly SessionEvent[]): Array<Omit<SessionEvent, 'seq' | 'time'>> {
  226. return events.map((event) => {
  227. const { seq: _seq, time: _time, ...projected } = event
  228. return projected
  229. })
  230. }
  231. /**
  232. * Canonicalize one JSONL document when its first record is a session header.
  233. * The header line remains byte-identical; body records decode to logical events,
  234. * re-encode one event per row, and omit storage sequence/time envelopes.
  235. * Non-session JSONL returns undefined.
  236. *
  237. * @param content - JSONL source text.
  238. * @param label - path-like diagnostic label.
  239. * @returns Canonical text for a session fixture, otherwise undefined.
  240. */
  241. export function canonicalSessionFixture(content: string, label = '<session-fixture>'): string | undefined {
  242. const headerLine = content.split(/\r?\n/).find(line => line.trim().length > 0)
  243. if (headerLine === undefined) return undefined
  244. let headerValue: unknown
  245. try {
  246. headerValue = JSON.parse(headerLine) as unknown
  247. } catch {
  248. return undefined
  249. }
  250. if (!isSessionHeader(headerValue)) return undefined
  251. let events
  252. try {
  253. events = parseFixtureRows(content, headerValue)
  254. } catch (error) {
  255. const detail = error instanceof Error ? error.message : String(error)
  256. throw new Error(`${label}: ${detail}`, { cause: error })
  257. }
  258. const storedVersion = headerValue !== null
  259. && typeof headerValue === 'object'
  260. && !Array.isArray(headerValue)
  261. && typeof (headerValue as Record<string, unknown>).version === 'number'
  262. ? (headerValue as Record<string, number>).version
  263. : undefined
  264. // Released predecessor generations are immutable compatibility fixtures.
  265. // Parsing above still validates their physical rows, but canonicalization
  266. // never rewrites their committed bytes into the current scalar layout.
  267. if (storedVersion !== undefined && storedVersion < sessionFormatCatalog.currentVersion) {
  268. return content
  269. }
  270. const canonical = renderFixture(headerLine, events)
  271. const decoded = parseFixtureRows(canonical, headerValue)
  272. try {
  273. deepStrictEqual(withoutEnvelope(decoded), withoutEnvelope(events))
  274. } catch (error) {
  275. throw new Error(`${label}: packed snapshot rewrite changed the event payload stream`, { cause: error })
  276. }
  277. if (renderFixture(headerLine, decoded) !== canonical) {
  278. throw new Error(`${label}: packed rewrite is not idempotent`)
  279. }
  280. return canonical
  281. }
  282. /**
  283. * Discover tracked and unignored untracked JSONL files through Git.
  284. *
  285. * @param root - repository root.
  286. * @returns Stable repository-relative paths.
  287. */
  288. function discoverJsonlFiles(root: string): string[] {
  289. return execFileSync(
  290. 'git',
  291. ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '*.jsonl'],
  292. { cwd: root, encoding: 'utf8' },
  293. ).split('\0')
  294. .filter(path => path.length > 0 && existsSync(resolve(root, path)))
  295. .sort()
  296. }
  297. /**
  298. * Inspect every repository JSONL whose first record is a session header.
  299. *
  300. * @param root - repository root.
  301. * @returns Session fixtures with current and canonical text.
  302. */
  303. export function inspectSessionFixtureLayouts(root: string): SessionFixtureLayout[] {
  304. return discoverJsonlFiles(root).flatMap((path) => {
  305. if (isPhysicalSessionFixture(path)) return []
  306. const source = readFileSync(resolve(root, path), 'utf8')
  307. const canonical = canonicalSessionFixture(source, path)
  308. return canonical === undefined ? [] : [{ path, source, canonical }]
  309. })
  310. }