storage-contract.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * Unit tests for the backend-shared storage validation helpers and the
  3. * stable error vocabulary.
  4. */
  5. import { describe, expect, it } from 'vitest'
  6. import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  7. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  8. import {
  9. SessionAlreadyExistsError,
  10. SessionAlreadyOwnedError,
  11. SessionFormatUnsupportedError,
  12. SessionHandleClosedError,
  13. SessionOwnershipLostError,
  14. SessionPersistenceCorruptionError,
  15. SessionPersistenceNotFoundError,
  16. SessionPersistenceRevision,
  17. SessionReadOnlyError,
  18. assertContiguous,
  19. assertStoredId,
  20. assertVersion,
  21. materializeAppendBatch,
  22. sessionFormatVersionRefusal,
  23. validateStoredEvents,
  24. } from '../src/index.ts'
  25. import type { SessionLocation } from '../src/index.ts'
  26. import { meta } from './contract.ts'
  27. const LOCATION: SessionLocation = { kind: 'jsonl', path: '/store/session.jsonl' }
  28. /** A stored user/message event with a well-formed identified message. */
  29. function userMessage(seq: number): SessionEvent {
  30. return {
  31. type: 'user/message',
  32. seq,
  33. time: seq + 1,
  34. data: {
  35. id: 'stored-user',
  36. role: 'user',
  37. content: [{ type: 'text', text: 'hi' }],
  38. source: { kind: 'user' },
  39. },
  40. surfaceOp: 'append',
  41. } as unknown as SessionEvent
  42. }
  43. describe('assertStoredId', () => {
  44. it('accepts a bound header and names both ids on a mismatch', () => {
  45. const m = meta('bound')
  46. expect(() => { assertStoredId(m.id, m) }).not.toThrow()
  47. expect(() => { assertStoredId(SessionId('requested'), m) })
  48. .toThrow('stored session identity mismatch: requested "requested", header contains "bound"')
  49. })
  50. })
  51. describe('assertVersion', () => {
  52. it('accepts the current format version', () => {
  53. expect(() => { assertVersion(meta('current')) }).not.toThrow()
  54. })
  55. it('refuses a newer version with the upgrade direction and the artifact location', () => {
  56. const newer = { ...meta('newer'), version: SESSION_FORMAT_VERSION + 42 }
  57. let refusal: unknown
  58. try {
  59. assertVersion(newer, LOCATION)
  60. } catch (error) {
  61. refusal = error
  62. }
  63. expect(refusal).toBeInstanceOf(SessionFormatUnsupportedError)
  64. expect((refusal as Error).message).toContain('written by a newer harness — upgrade the harness to open it')
  65. expect((refusal as Error).message).toContain(`(raw log: ${LOCATION.path})`)
  66. expect((refusal as SessionFormatUnsupportedError).location).toBe(LOCATION)
  67. })
  68. it('refuses an older version without a location suffix when the backend has no artifact', () => {
  69. const older = { ...meta('older'), version: SESSION_FORMAT_VERSION - 1 }
  70. let refusal: unknown
  71. try {
  72. assertVersion(older)
  73. } catch (error) {
  74. refusal = error
  75. }
  76. expect(refusal).toBeInstanceOf(SessionFormatUnsupportedError)
  77. expect((refusal as Error).message).toBe(sessionFormatVersionRefusal('older', SESSION_FORMAT_VERSION - 1))
  78. expect((refusal as Error).message).toContain('this build ships no upgrade path for it')
  79. expect((refusal as Error).message).not.toContain('raw log')
  80. expect((refusal as SessionFormatUnsupportedError).location).toBeUndefined()
  81. })
  82. })
  83. describe('sessionFormatVersionRefusal', () => {
  84. it('states the direction for newer and older stored versions', () => {
  85. expect(sessionFormatVersionRefusal('s', SESSION_FORMAT_VERSION + 1))
  86. .toBe(`session "s" uses log format v${SESSION_FORMAT_VERSION + 1}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it`)
  87. expect(sessionFormatVersionRefusal('s', SESSION_FORMAT_VERSION - 1))
  88. .toBe(`session "s" uses log format v${SESSION_FORMAT_VERSION - 1}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it`)
  89. })
  90. })
  91. describe('validateStoredEvents', () => {
  92. it('adopts and freezes the events in place, returning the same array', () => {
  93. const m = meta('adopted')
  94. const events = [
  95. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  96. userMessage(1),
  97. ] as SessionEvent[]
  98. const validated = validateStoredEvents(m, events)
  99. expect(validated).toBe(events)
  100. expect(Object.isFrozen(validated[1]!.data)).toBe(true)
  101. })
  102. it('adopts a merge-extended turn/end reason outside the closed built-in set', () => {
  103. const m = meta('extended-reason')
  104. const events = [
  105. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  106. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'plugin/custom-outcome' } } },
  107. ] as SessionEvent[]
  108. expect(validateStoredEvents(m, events)).toBe(events)
  109. })
  110. it('refuses an unknown event type before adopting anything', () => {
  111. const m = meta('unknown-type')
  112. const events = [
  113. { type: 'mystery/event', seq: 0, time: 1, data: {} },
  114. ] as unknown as SessionEvent[]
  115. expect(() => validateStoredEvents(m, events)).toThrow(SessionFormatUnsupportedError)
  116. expect(() => validateStoredEvents(m, events)).toThrow(
  117. 'session "unknown-type" contains event type "mystery/event" (seq 0) unknown to this harness',
  118. )
  119. // With an artifact, the refusal points at the raw log.
  120. let refusal: unknown
  121. try {
  122. validateStoredEvents(m, events, LOCATION)
  123. } catch (error) {
  124. refusal = error
  125. }
  126. expect((refusal as Error).message).toContain(`(raw log: ${LOCATION.path})`)
  127. expect((refusal as SessionFormatUnsupportedError).location).toBe(LOCATION)
  128. })
  129. it('retains an unknown event type its writer marked ignorable', () => {
  130. const m = meta('ignorable-unknown')
  131. const events = [
  132. { type: 'foreign/telemetry', seq: 0, time: 1, data: {}, ignorable: true },
  133. ] as unknown as SessionEvent[]
  134. expect(validateStoredEvents(m, events)).toBe(events)
  135. expect(events[0]).toMatchObject({ type: 'foreign/telemetry', ignorable: true })
  136. })
  137. it('refuses the retired request/header "fallback" reason while accepting current headers', () => {
  138. const m = meta('retired-reason')
  139. const retired = [
  140. {
  141. type: 'request/header',
  142. seq: 0,
  143. time: 1,
  144. data: { header: { config: { provider: 'mock', model: 'legacy' } }, reason: 'fallback' },
  145. },
  146. ] as unknown as SessionEvent[]
  147. expect(() => validateStoredEvents(m, retired)).toThrow(SessionFormatUnsupportedError)
  148. expect(() => validateStoredEvents(m, retired)).toThrow(
  149. 'session "retired-reason" contains a request/header event (seq 0) with the unsupported legacy reason "fallback"',
  150. )
  151. const current = [
  152. {
  153. type: 'request/header',
  154. seq: 0,
  155. time: 1,
  156. data: { header: { config: { provider: 'mock', model: 'current' } }, reason: 'initial' },
  157. },
  158. ] as unknown as SessionEvent[]
  159. expect(validateStoredEvents(m, current)).toBe(current)
  160. })
  161. it('wraps a record validation failure as corruption with its cause', () => {
  162. const m = meta('damaged')
  163. const events = [
  164. {
  165. type: 'user/message',
  166. seq: 0,
  167. time: 1,
  168. // No identified message: adoption refuses the record.
  169. data: { role: 'user', content: [], source: { kind: 'user' } },
  170. surfaceOp: 'append',
  171. },
  172. ] as unknown as SessionEvent[]
  173. let failure: unknown
  174. try {
  175. validateStoredEvents(m, events)
  176. } catch (error) {
  177. failure = error
  178. }
  179. expect(failure).toBeInstanceOf(SessionPersistenceCorruptionError)
  180. expect((failure as Error).message).toContain('stored session "damaged" failed validation')
  181. expect((failure as Error).message).toContain('lacks an identified message')
  182. expect((failure as Error).cause).toBeInstanceOf(Error)
  183. })
  184. it('passes an adoption-side format refusal through unwrapped', () => {
  185. // The adoption step may itself refuse a record as unsupported rather than
  186. // damaged; such a refusal must reach the caller as-is, never rebranded as
  187. // corruption.
  188. const m = meta('adoption-refusal')
  189. const passthrough = new SessionFormatUnsupportedError('refused during adoption')
  190. const trap = {
  191. type: 'user/message',
  192. seq: 0,
  193. time: 1,
  194. get data(): never {
  195. throw passthrough
  196. },
  197. } as unknown as SessionEvent
  198. expect(() => validateStoredEvents(m, [trap])).toThrow(passthrough)
  199. })
  200. })
  201. describe('materializeAppendBatch', () => {
  202. it('returns a detached lossless-JSON snapshot of the batch', () => {
  203. const original = [
  204. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  205. ] as SessionEvent[]
  206. const batch = materializeAppendBatch(original)
  207. expect(batch).not.toBe(original)
  208. expect(batch).toEqual(original)
  209. // The snapshot is detached: mutating the caller's batch afterwards cannot
  210. // change what a backend persists.
  211. ;(original[0]!.data as { turn: number }).turn = 99
  212. expect((batch[0]!.data as { turn: number }).turn).toBe(1)
  213. })
  214. it('rejects every non-JSON value, not only BigInt', () => {
  215. // Every value `snapshotJsonValue` refuses must be refused here — a backend
  216. // passing this helper cannot accept values that corrupt the durable
  217. // round-trip.
  218. const cyclic: Record<string, unknown> = { type: 'text', text: 'x' }
  219. cyclic['self'] = cyclic
  220. const badValues: unknown[] = [
  221. 1n, // BigInt
  222. undefined, // dropped by JSON.stringify
  223. Infinity, // → null
  224. () => 0, // function
  225. Symbol('s'), // symbol
  226. new Map(), // exotic object
  227. cyclic, // circular ref
  228. ]
  229. for (const bad of badValues) {
  230. const events = [
  231. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, extra: bad } },
  232. ] as unknown as SessionEvent[]
  233. expect(() => materializeAppendBatch(events)).toThrow(TypeError)
  234. expect(() => materializeAppendBatch(events)).toThrow(/losslessly JSON-serializable/)
  235. }
  236. })
  237. })
  238. describe('assertContiguous', () => {
  239. it('accepts a batch continuing exactly at the cursor', () => {
  240. const events = [
  241. { type: 'turn/start', seq: 6, time: 1, data: { turn: 2 } },
  242. { type: 'turn/end', seq: 7, time: 2, data: { turn: 2, reason: { kind: 'completed' } } },
  243. ] as SessionEvent[]
  244. expect(() => { assertContiguous(SessionId('ok'), events, 6) }).not.toThrow()
  245. expect(() => { assertContiguous(SessionId('ok'), [], 6) }).not.toThrow()
  246. })
  247. it('names the expected seq for a stale batch and for a mid-batch gap', () => {
  248. const stale = [
  249. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  250. ] as SessionEvent[]
  251. expect(() => { assertContiguous(SessionId('stale'), stale, 6) })
  252. .toThrow('append seq mismatch for "stale": expected 6 at index 0, got 0')
  253. const gapped = [
  254. { type: 'turn/start', seq: 6, time: 1, data: { turn: 2 } },
  255. { type: 'turn/end', seq: 8, time: 2, data: { turn: 2, reason: { kind: 'completed' } } },
  256. ] as SessionEvent[]
  257. expect(() => { assertContiguous(SessionId('gapped'), gapped, 6) })
  258. .toThrow('append seq mismatch for "gapped": expected 7 at index 1, got 8')
  259. })
  260. })
  261. describe('error vocabulary', () => {
  262. it('carries stable names, messages, and the session id', () => {
  263. const id = SessionId('errored')
  264. const notFound = new SessionPersistenceNotFoundError(id)
  265. expect(notFound.name).toBe('SessionPersistenceNotFoundError')
  266. expect(notFound.sessionId).toBe(id)
  267. expect(notFound.message).toBe('session "errored" not found')
  268. const exists = new SessionAlreadyExistsError(id)
  269. expect(exists.name).toBe('SessionAlreadyExistsError')
  270. expect(exists.message).toBe('session "errored" already exists')
  271. const owned = new SessionAlreadyOwnedError(id)
  272. expect(owned.name).toBe('SessionAlreadyOwnedError')
  273. expect(owned.message).toBe('session "errored" is already owned by an active write handle')
  274. const readOnly = new SessionReadOnlyError(id, 'append')
  275. expect(readOnly.name).toBe('SessionReadOnlyError')
  276. expect(readOnly.message).toBe('session "errored": append is not available on a read handle')
  277. const lost = new SessionOwnershipLostError(id)
  278. expect(lost.name).toBe('SessionOwnershipLostError')
  279. expect(lost.message).toBe('session "errored": write ownership was lost; close this handle and reopen')
  280. const closed = new SessionHandleClosedError(id, 'flush')
  281. expect(closed.name).toBe('SessionHandleClosedError')
  282. expect(closed.message).toBe('session "errored": flush on a closed handle')
  283. const cause = new Error('detail')
  284. const corruption = new SessionPersistenceCorruptionError('bad log', { cause })
  285. expect(corruption.name).toBe('SessionPersistenceCorruptionError')
  286. expect(corruption.cause).toBe(cause)
  287. })
  288. })
  289. describe('SessionPersistenceRevision', () => {
  290. it('brands the backend token without changing its runtime value', () => {
  291. expect(SessionPersistenceRevision('rev:1')).toBe('rev:1')
  292. })
  293. })