contract.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /**
  2. * Reusable contract test for any {@link SessionPersistence} backend. A backend
  3. * package imports {@link runPersistenceContract} and calls it with a factory
  4. * that yields a fresh, empty backend (and a teardown), so every backend is held
  5. * to the same append-only / contiguous-seq / lazy-materialization / crash
  6. * semantics. The JSONL backend's own spec adds file-specific tests on top.
  7. *
  8. * @module @deepseek-ai/dsh-session-persistence/tests/contract
  9. */
  10. import { describe, expect, it } from 'vitest'
  11. import { SESSION_FORMAT_VERSION, Session, SessionId, TOOL_NOT_STARTED, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session'
  12. import type { SessionEvent, SessionHeader, SurfaceEventType, SurfaceIntent } from '@deepseek-ai/dsh-session'
  13. import { CallId, MessageId, createMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
  14. import type { SessionPersistence } from '../src/index.ts'
  15. /** A backend under test plus its teardown. */
  16. export interface ContractBackend {
  17. persistence: SessionPersistence
  18. dispose: () => Promise<void>
  19. }
  20. /** Build a minimal {@link SessionHeader} for a session id. */
  21. export function meta(id: string, cwd?: string): SessionHeader {
  22. return {
  23. version: SESSION_FORMAT_VERSION,
  24. id: SessionId(id),
  25. createdAt: 1000,
  26. ...cwd !== undefined ? { cwd } : {},
  27. }
  28. }
  29. /** A well-formed one-turn event log (contiguous seqs from 0). */
  30. export function oneTurnLog(): SessionEvent[] {
  31. return [
  32. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  33. { type: 'user/message', seq: 1, time: 2, data: freezeMessage({
  34. id: MessageId('one-turn-user'),
  35. role: 'user',
  36. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  37. }), surfaceOp: 'append' },
  38. { type: 'step/start', seq: 2, time: 3, data: { turn: 1, step: 1 } },
  39. { type: 'assistant/message', seq: 3, time: 4, data: {
  40. turn: 1, step: 1,
  41. message: freezeMessage({
  42. id: MessageId('one-turn-assistant'),
  43. role: 'assistant',
  44. content: [{ type: 'text', text: 'hello' }],
  45. source: {
  46. kind: 'model',
  47. ...{ provider: 'mock', model: 'mock' },
  48. },
  49. }),
  50. }, surfaceOp: 'append' },
  51. { type: 'step/end', seq: 4, time: 5, data: { turn: 1, step: 1 } },
  52. { type: 'turn/end', seq: 5, time: 6, data: { turn: 1, reason: { kind: 'completed' } } },
  53. ]
  54. }
  55. /**
  56. * Append recorded events to a live session while forwarding surface metadata verbatim. The broad
  57. * `SessionEvent` union makes the typed marker optional, but the runtime guard must still reject a
  58. * surface event whose fixture omitted it; this helper never synthesizes a default.
  59. */
  60. export function appendLog(session: Session, events: readonly SessionEvent[]): void {
  61. for (const e of events) {
  62. const se = e as SessionEvent<SurfaceEventType>
  63. if (se.surfaceOp !== undefined) {
  64. const intent: SurfaceIntent = {
  65. surfaceOp: se.surfaceOp,
  66. ...se.sourceEventSeqs !== undefined ? { sourceEventSeqs: se.sourceEventSeqs } : {},
  67. }
  68. session.append(e.type, e.data, intent)
  69. } else {
  70. session.append(e.type, e.data)
  71. }
  72. }
  73. }
  74. /**
  75. * Run the backend-agnostic contract suite. `make()` MUST return a fresh, empty
  76. * backend each call.
  77. */
  78. export function runPersistenceContract(name: string, make: () => Promise<ContractBackend>): void {
  79. describe(`SessionPersistence contract: ${name}`, () => {
  80. it('round-trips a session: create + append → load returns identical meta and byte-identical events', async () => {
  81. const { persistence, dispose } = await make()
  82. try {
  83. const m = meta('s1', '/work')
  84. const log = oneTurnLog()
  85. await persistence.create(m)
  86. await persistence.append(m.id, log)
  87. const loaded = await persistence.load(m.id)
  88. expect(loaded.meta).toMatchObject({ version: SESSION_FORMAT_VERSION, id: m.id, cwd: '/work' })
  89. expect(loaded.events).toEqual(log)
  90. } finally {
  91. await dispose()
  92. }
  93. })
  94. it('rejects a fractional creation timestamp without reserving its session id', async () => {
  95. const { persistence, dispose } = await make()
  96. try {
  97. const m = { ...meta('fractional-created-at'), createdAt: 1.5 }
  98. await expect(persistence.create(m))
  99. .rejects.toThrow('session metadata createdAt must be a non-negative safe integer')
  100. const valid = meta('fractional-created-at')
  101. await persistence.create(valid)
  102. await persistence.append(valid.id, oneTurnLog())
  103. expect((await persistence.load(valid.id)).meta.createdAt).toBe(valid.createdAt)
  104. } finally {
  105. await dispose()
  106. }
  107. })
  108. it('crash recovery: load preserves an interrupted (unclosed) turn and closes it with turn/end {interrupted}', async () => {
  109. const { persistence, dispose } = await make()
  110. try {
  111. const m = meta('interrupted')
  112. await persistence.create(m)
  113. await persistence.append(m.id, oneTurnLog()) // turn 1, committed (seqs 0..5)
  114. // A second turn that crashed mid-flight: turn/start + step/start were
  115. // durably written, but no step/end / turn/end ever arrived.
  116. await persistence.append(m.id, [
  117. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  118. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  119. ])
  120. const beforeRepair = (await persistence.listSnapshots())
  121. .find(snapshot => snapshot.header.id === m.id)?.revision
  122. const inspected = await persistence.inspect(m.id)
  123. const afterInspect = (await persistence.listSnapshots())
  124. .find(snapshot => snapshot.header.id === m.id)?.revision
  125. expect(afterInspect).toBe(beforeRepair)
  126. expect(inspected.events.map(e => e.type)).toEqual([
  127. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end',
  128. 'turn/start', 'step/start', 'step/end', 'turn/end',
  129. ])
  130. // load PRESERVES the interrupted turn's events (a turn can be huge — they
  131. // must not be truncated) and closes the orphaned turn with synthetic
  132. // boundary events: step/end (the step was open) then turn/end {interrupted}.
  133. const loaded = await persistence.load(m.id)
  134. const afterRepair = (await persistence.listSnapshots())
  135. .find(snapshot => snapshot.header.id === m.id)?.revision
  136. expect(afterRepair).not.toBe(beforeRepair)
  137. expect(loaded.events.map(e => e.type)).toEqual([
  138. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  139. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  140. ])
  141. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  142. const last = loaded.events.at(-1)!
  143. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  144. // The closed log is durable and continuable: a fresh append continues at
  145. // the balanced length (seq 10), and a reload round-trips identically.
  146. await persistence.append(m.id, [
  147. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3 } },
  148. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  149. ])
  150. const reloaded = await persistence.load(m.id)
  151. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  152. } finally {
  153. await dispose()
  154. }
  155. })
  156. it('crash recovery: an unstarted assistant tool request gets a retryable synthetic result', async () => {
  157. const { persistence, dispose } = await make()
  158. try {
  159. const m = meta('interrupted-toolcall')
  160. await persistence.create(m)
  161. await persistence.append(m.id, oneTurnLog()) // turn 1, committed (seqs 0..5)
  162. // Turn 2 crashed AFTER the assistant message asked for a tool call but
  163. // BEFORE the tool/result was written (the loop runs tools after logging
  164. // the assistant message — a process killed mid-tool lands exactly here).
  165. await persistence.append(m.id, [
  166. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  167. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  168. { type: 'assistant/message', seq: 8, time: 9, data: {
  169. turn: 2, step: 1,
  170. message: createMessage({
  171. role: 'assistant',
  172. content: [
  173. { type: 'tool-call', id: CallId('call-x'), name: 'bash', arguments: '{}' },
  174. ],
  175. source: {
  176. kind: 'model',
  177. ...{ provider: 'mock', model: 'mock' },
  178. },
  179. }),
  180. }, surfaceOp: 'append' },
  181. ])
  182. const loaded = await persistence.load(m.id)
  183. // The orphaned call is answered by a synthetic error tool/result BEFORE
  184. // step/end + turn/end {interrupted}, so the step (and turn) are balanced
  185. // and a resumed session derives a valid transcript (no dangling call).
  186. expect(loaded.events.map(e => e.type)).toEqual([
  187. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  188. 'turn/start', 'step/start', 'assistant/message', 'tool/result', 'step/end', 'turn/end', // turn 2
  189. ])
  190. const synthetic = loaded.events.find(e => e.type === 'tool/result')
  191. expect(synthetic?.type === 'tool/result' && synthetic.data).toMatchObject({
  192. message: {
  193. source: { kind: 'tool', callId: CallId('call-x') },
  194. content: [{ type: 'tool-result', toolCallId: CallId('call-x'), isError: true }],
  195. },
  196. error: { code: TOOL_NOT_STARTED },
  197. })
  198. // The synthetic result carries the SAME callId as the orphaned tool-call,
  199. // so deriveMessages() pairs them — no provider-invalid dangling call.
  200. const call = loaded.events.findLast(e => e.type === 'assistant/message')
  201. const callId = call?.type === 'assistant/message'
  202. && call.data.message.content.find(b => b.type === 'tool-call')
  203. expect(callId && callId.type === 'tool-call' && callId.id).toBe(CallId('call-x'))
  204. } finally {
  205. await dispose()
  206. }
  207. })
  208. it('crash recovery: a recorded tool call with no result tells the model to assess retry risk', async () => {
  209. const { persistence, dispose } = await make()
  210. try {
  211. const m = meta('unknown-tool-outcome')
  212. await persistence.create(m)
  213. await persistence.append(m.id, [
  214. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  215. { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } },
  216. { type: 'assistant/message', seq: 2, time: 3, data: {
  217. turn: 1, step: 1,
  218. message: createMessage({
  219. role: 'assistant',
  220. content: [
  221. { type: 'tool-call', id: CallId('call-risk'), name: 'write', arguments: '{}' },
  222. ],
  223. source: {
  224. kind: 'model',
  225. ...{ provider: 'mock', model: 'mock' },
  226. },
  227. }),
  228. }, surfaceOp: 'append' },
  229. { type: 'tool/call', seq: 3, time: 4, data: { turn: 1, step: 1, callId: CallId('call-risk'), name: 'write', arguments: '{}' } },
  230. ])
  231. const loaded = await persistence.load(m.id)
  232. const synthetic = loaded.events.find(e => e.type === 'tool/result')
  233. expect(synthetic?.type === 'tool/result' && synthetic.data.error).toEqual({
  234. name: 'ToolOutcomeUnknownError', code: TOOL_OUTCOME_UNKNOWN,
  235. })
  236. if (synthetic?.type !== 'tool/result' || synthetic.data.message.content[0].content[0]?.type !== 'text') {
  237. throw new Error('expected a text tool result')
  238. }
  239. expect(synthetic.data.message.content[0].content[0].text).toContain('retry only if the operation is read-only or idempotent')
  240. expect(synthetic.data.message.content[0].content[0].text).toContain('if it may have side effects, first verify external state or ask the user')
  241. const resumed = Session.create(m.id, loaded.events, loaded.meta)
  242. const resumedResult = resumed.deriveMessages().find(message => message.content.some(block => block.type === 'tool-result'))
  243. expect(resumedResult?.content[0]).toMatchObject({
  244. type: 'tool-result', toolCallId: CallId('call-risk'), isError: true,
  245. })
  246. } finally {
  247. await dispose()
  248. }
  249. })
  250. it('list() excludes a created-but-never-appended (zero-event) session', async () => {
  251. const { persistence, dispose } = await make()
  252. try {
  253. await persistence.create(meta('empty'))
  254. expect((await persistence.list()).map(m => m.id)).not.toContain(SessionId('empty'))
  255. expect((await persistence.listSnapshots()).map(snapshot => snapshot.header.id))
  256. .not.toContain(SessionId('empty'))
  257. } finally {
  258. await dispose()
  259. }
  260. })
  261. it('rejects pre-aborted observation reads with the exact cancellation reason', async () => {
  262. const { persistence, dispose } = await make()
  263. try {
  264. const reason = new Error('persistence observation cancelled')
  265. const controller = new AbortController()
  266. await expect(persistence.listSnapshots(controller.signal)).resolves.toEqual([])
  267. controller.abort(reason)
  268. await expect(persistence.list(controller.signal)).rejects.toBe(reason)
  269. await expect(persistence.listSnapshots(controller.signal)).rejects.toBe(reason)
  270. await expect(persistence.inspect(SessionId('cancelled-inspect'), controller.signal))
  271. .rejects.toBe(reason)
  272. await expect(persistence.readFrom(SessionId('cancelled-read-from'), 0, controller.signal))
  273. .rejects.toBe(reason)
  274. } finally {
  275. await dispose()
  276. }
  277. })
  278. it('readFrom returns exactly the stored suffix from the requested seq, without mutating the log', async () => {
  279. const { persistence, dispose } = await make()
  280. try {
  281. const m = meta('read-from', '/work')
  282. const log = oneTurnLog()
  283. await persistence.create(m)
  284. await persistence.append(m.id, log)
  285. const whole = await persistence.readFrom(m.id, 0)
  286. expect(whole.meta).toMatchObject({ id: m.id, cwd: '/work' })
  287. expect(whole.events).toEqual(log)
  288. const suffix = await persistence.readFrom(m.id, 3)
  289. expect(suffix.events).toEqual(log.slice(3))
  290. expect(suffix.events[0]?.seq).toBe(3)
  291. // At/past the stored end: an empty tail, never an error.
  292. await expect(persistence.readFrom(m.id, log.length)).resolves.toMatchObject({ events: [] })
  293. await expect(persistence.readFrom(m.id, log.length + 100)).resolves.toMatchObject({ events: [] })
  294. // Non-mutating: an interrupted-turn log is served as stored, no closers.
  295. await persistence.append(m.id, [
  296. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  297. ])
  298. const tail = await persistence.readFrom(m.id, 6)
  299. expect(tail.events.map(event => event.type)).toEqual(['turn/start'])
  300. await expect(persistence.readFrom(SessionId('absent-read-from'), 0)).rejects.toThrow('not found')
  301. await expect(persistence.readFrom(m.id, -1)).rejects.toThrow('non-negative safe integer')
  302. await expect(persistence.readFrom(m.id, 1.5)).rejects.toThrow('non-negative safe integer')
  303. } finally {
  304. await dispose()
  305. }
  306. })
  307. it('lists stable lightweight revisions that change after an append', async () => {
  308. const { persistence, dispose } = await make()
  309. try {
  310. const m = meta('s2')
  311. await persistence.create(m)
  312. await persistence.append(m.id, oneTurnLog())
  313. expect((await persistence.list()).map(x => x.id)).toContain(m.id)
  314. const first = (await persistence.listSnapshots()).find(snapshot => snapshot.header.id === m.id)
  315. const repeated = (await persistence.listSnapshots()).find(snapshot => snapshot.header.id === m.id)
  316. expect(first).toBeDefined()
  317. expect(repeated?.revision).toBe(first?.revision)
  318. await persistence.append(m.id, [{
  319. type: 'turn/start',
  320. seq: 6,
  321. time: 7,
  322. data: { turn: 2 },
  323. }])
  324. const changed = (await persistence.listSnapshots()).find(snapshot => snapshot.header.id === m.id)
  325. expect(changed?.revision).not.toBe(first?.revision)
  326. } finally {
  327. await dispose()
  328. }
  329. })
  330. it('append rejects a batch whose first seq does not match the stored next-seq', async () => {
  331. const { persistence, dispose } = await make()
  332. try {
  333. const m = meta('s3')
  334. await persistence.create(m)
  335. await persistence.append(m.id, oneTurnLog()) // seqs 0..5, next-seq = 6
  336. // A re-append of an already-stored seq must be rejected, not duplicated.
  337. const restated = oneTurnLog()
  338. await expect(persistence.append(m.id, restated)).rejects.toThrow()
  339. } finally {
  340. await dispose()
  341. }
  342. })
  343. it('append rejects a mid-batch seq gap', async () => {
  344. const { persistence, dispose } = await make()
  345. try {
  346. const m = meta('s4')
  347. await persistence.create(m)
  348. const gapped: SessionEvent[] = [
  349. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  350. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // gap: missing seq 1
  351. ]
  352. await expect(persistence.append(m.id, gapped)).rejects.toThrow()
  353. } finally {
  354. await dispose()
  355. }
  356. })
  357. it('append rejects non-JSON-serializable event data, naming the event type', async () => {
  358. const { persistence, dispose } = await make()
  359. try {
  360. // Every value `isJsonValue` rejects must be rejected by the backend, not just BigInt —
  361. // otherwise a backend could pass this contract while still accepting values that
  362. // corrupt the durable round-trip. Each value is carried in a plugin-added field on one
  363. // user message so the contract covers the complete JSON-value boundary.
  364. const cyclic: Record<string, unknown> = { type: 'text', text: 'x' }
  365. cyclic['self'] = cyclic
  366. const badValues: unknown[] = [
  367. 1n, // BigInt
  368. undefined, // dropped by JSON.stringify
  369. Infinity, // → null
  370. () => 0, // function
  371. Symbol('s'), // symbol
  372. new Map(), // exotic object
  373. cyclic, // circular ref
  374. ]
  375. for (const [i, bad] of badValues.entries()) {
  376. // A fresh session per value isolates each rejection (a rejected append
  377. // must leave no state behind, but isolating keeps the assertion clean).
  378. const mi = meta(`s5-${i}`)
  379. await persistence.create(mi)
  380. const events = [
  381. {
  382. type: 'user/message',
  383. seq: 0,
  384. time: 1,
  385. data: {
  386. id: MessageId(`invalid-json-${i}`),
  387. role: 'user',
  388. content: [{ type: 'text', text: 'x' }],
  389. source: { kind: 'user' },
  390. extra: bad,
  391. },
  392. },
  393. ] as unknown as SessionEvent[]
  394. await expect(persistence.append(mi.id, events)).rejects.toThrow(/losslessly JSON-serializable/)
  395. }
  396. } finally {
  397. await dispose()
  398. }
  399. })
  400. })
  401. }