session-fixture-layout.spec.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { resolve } from 'node:path'
  2. import { describe, expect, it } from 'vitest'
  3. import { createAssistantMessage } from '@deepseek-ai/dsh-llm'
  4. import { SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session'
  5. import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  6. import {
  7. canonicalSessionFixture,
  8. inspectSessionFixtureLayouts,
  9. isPhysicalSessionFixture,
  10. } from './session-fixture-layout.ts'
  11. const HEADER = ' {"type":"session","version":2,"id":"fixture","createdAt":1,"isSeeded":false,"delegationDepth":0} '
  12. const root = resolve(import.meta.dirname, '..')
  13. const FIXTURE_MESSAGE = createAssistantMessage({
  14. content: [{ type: 'text', text: 'part-0part-1part-2part-3' }],
  15. source: { provider: 'mock', model: 'mock' },
  16. })
  17. const FIXTURE_STREAM: SessionEvent<'assistant/message'>['data']['stream'] = [
  18. {
  19. type: 'text-chunks',
  20. time0: 10,
  21. index: 0,
  22. dt: [1, 1, 1],
  23. texts: ['part-0', 'part-1', 'part-2', 'part-3'],
  24. },
  25. { type: 'chunk', time: 14, chunk: { type: 'finish', reason: { kind: 'stop' } } },
  26. ]
  27. function assistantMessage(): SessionEvent<'assistant/message'> {
  28. return {
  29. type: 'assistant/message',
  30. seq: SessionSeq(2),
  31. time: 14,
  32. data: {
  33. turn: 1,
  34. step: 1,
  35. message: FIXTURE_MESSAGE,
  36. stream: FIXTURE_STREAM,
  37. },
  38. surfaceOp: 'append',
  39. }
  40. }
  41. function fixtureEvents(): SessionEvent[] {
  42. return [
  43. { type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
  44. { type: 'step/start', seq: SessionSeq(1), time: 2, data: { turn: 1, step: 1 } },
  45. assistantMessage(),
  46. ]
  47. }
  48. function unpackedFixture(): string {
  49. return [HEADER, ...fixtureEvents().map(event => JSON.stringify(event)), ''].join('\n')
  50. }
  51. function decodedBody(content: string): SessionEvent[] {
  52. return parseSessionLog(content)
  53. }
  54. describe('canonicalSessionFixture', () => {
  55. it('preserves the header line and nested compact stream losslessly', () => {
  56. const canonical = canonicalSessionFixture(unpackedFixture(), 'fixture.jsonl')
  57. expect(canonical).toBeDefined()
  58. expect(canonical?.split('\n')[0]).toBe(HEADER)
  59. const message = canonical?.split('\n')
  60. .map(line => JSON.parse(line || '{}') as Record<string, unknown>)
  61. .find(record => record.type === 'assistant/message')
  62. expect(message).toMatchObject({
  63. type: 'assistant/message',
  64. data: {
  65. stream: FIXTURE_STREAM,
  66. },
  67. })
  68. expect(message).not.toHaveProperty('seq')
  69. expect(message).not.toHaveProperty('time')
  70. expect(decodedBody(canonical ?? '').map(({ seq: _seq, time: _time, ...event }) => event))
  71. .toStrictEqual(fixtureEvents().map(({ seq: _seq, time: _time, ...event }) => event))
  72. })
  73. it('ignores JSONL whose first record is not a session header', () => {
  74. expect(canonicalSessionFixture('{"type":"session_event"}\n{"value":1}\n')).toBeUndefined()
  75. })
  76. it('is idempotent for an already packed fixture', () => {
  77. const packed = canonicalSessionFixture(unpackedFixture())
  78. expect(packed).toBeDefined()
  79. expect(canonicalSessionFixture(packed ?? '')).toBe(packed)
  80. })
  81. it('is idempotent for an already projected fixture', () => {
  82. const projected = [
  83. HEADER,
  84. '{"type":"turn/start","data":{"turn":1}}',
  85. '',
  86. ].join('\n')
  87. expect(canonicalSessionFixture(projected)).toBe(projected)
  88. })
  89. it('preserves owner-restored request-header tokens in current projected fixtures', () => {
  90. const projected = [
  91. HEADER,
  92. '{"type":"turn/start","data":{"turn":1}}',
  93. '{"type":"request/header","data":{"header":{"config":{"provider":"mock","model":"mock"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}}',
  94. '',
  95. ].join('\n')
  96. expect(canonicalSessionFixture(projected)).toBe(projected)
  97. })
  98. it('fails loud on malformed records after a session header', () => {
  99. expect(() => canonicalSessionFixture(`${HEADER}\n{not-json}\n`, 'broken.jsonl'))
  100. .toThrow(/broken\.jsonl: session snapshot line 2 contains invalid JSON/)
  101. })
  102. it('labels malformed packed rows with the fixture path and line', () => {
  103. const releasedHeader = '{"type":"session","version":0,"id":"fixture","createdAt":1,"delegationDepth":0}'
  104. expect(() => canonicalSessionFixture(`${releasedHeader}\n{"type":"text-chunks"}\n`, 'broken.jsonl'))
  105. .toThrow(/broken\.jsonl: session snapshot line 2: released text-chunks row 0 lacks required member "data"/)
  106. })
  107. })
  108. describe('isPhysicalSessionFixture', () => {
  109. it('recognizes fixtures that preserve physical persistence encoding', () => {
  110. expect(isPhysicalSessionFixture(
  111. 'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/main/session.jsonl',
  112. )).toBe(true)
  113. expect(isPhysicalSessionFixture(
  114. 'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/main/session.v1.jsonl',
  115. )).toBe(true)
  116. expect(isPhysicalSessionFixture(
  117. 'scripts/snapshots/python-sdk-single-exe/advanced/session.1.jsonl',
  118. )).toBe(true)
  119. expect(isPhysicalSessionFixture(
  120. 'scripts/snapshots/python-sdk-single-exe/advanced/session.1.v1.jsonl',
  121. )).toBe(true)
  122. expect(isPhysicalSessionFixture(
  123. 'scripts/snapshots/python-sdk-single-exe/advanced/session.jsonl',
  124. )).toBe(true)
  125. expect(isPhysicalSessionFixture(
  126. 'scripts/snapshots/python-sdk-single-exe/restart/session.2.jsonl',
  127. )).toBe(true)
  128. expect(isPhysicalSessionFixture(
  129. 'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/README.jsonl',
  130. )).toBe(false)
  131. expect(isPhysicalSessionFixture(
  132. 'scripts/snapshots/python-sdk-single-exe/advanced/requests.jsonl',
  133. )).toBe(false)
  134. expect(isPhysicalSessionFixture('apps/web/tests/snapshots/example/session.jsonl')).toBe(false)
  135. })
  136. })
  137. it('keeps every session-format JSONL fixture projected into canonical event layout', () => {
  138. const nonCanonical = inspectSessionFixtureLayouts(root)
  139. .filter(fixture => fixture.source !== fixture.canonical)
  140. .map(fixture => fixture.path)
  141. expect(
  142. nonCanonical,
  143. 'Run `pnpm run migrate:packed-session-fixtures` and commit the mechanical fixture rewrite.',
  144. ).toEqual([])
  145. })