sqlite.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { mkdtemp, rm } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  7. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  8. import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
  9. import { openDatabase, scanRows, type EventRow } from '../src/schema.ts'
  10. import { runPersistenceContract, meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
  11. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  12. const dirs: string[] = []
  13. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  14. async function freshDbPath(): Promise<string> {
  15. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-'))
  16. dirs.push(dir)
  17. return join(dir, 'sessions.db')
  18. }
  19. /** A context with the session store + SQLite backend, plus a teardown. */
  20. async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
  21. const ctx = new Context()
  22. await ctx.plugin(SessionStore)
  23. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  24. return { ctx, dispose: () => fiber.dispose() }
  25. }
  26. // The payoff: the SAME backend-agnostic contract the JSONL backend runs, now
  27. // proving the SQLite backend satisfies identical semantics.
  28. runPersistenceContract('sqlite', async () => {
  29. const ctx = new Context()
  30. await ctx.plugin(SessionStore)
  31. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  32. return {
  33. persistence: ctx.sessionPersistence,
  34. dispose: async () => { await fiber.dispose() },
  35. }
  36. })
  37. // Run the shared coordinator orchestration suite against the real SQLite backend.
  38. // A FILE-backed db (not :memory:) is the shared storage scope so two mounted
  39. // instances see the same rows (HMR/reload). `corruptTail` INSERTs a row past the
  40. // committed seq whose `data` is invalid JSON — a never-committed torn tail that
  41. // drives the coordinator's commitRepair-with-tornMarker branch over real db rows.
  42. runCoordinatorContract('sqlite', async (): Promise<CoordinatorFixture> => {
  43. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-coord-'))
  44. const path = join(dir, 'sessions.db')
  45. return {
  46. mount: async ctx => ctx.plugin(SessionPersistenceSqlite, { path }),
  47. corruptTail: async (id) => {
  48. // A row past the committed region whose `data` does not parse: scanRows
  49. // bounds the preserved prefix at it and returns its seq as tornFrom, which
  50. // the backend surfaces to the coordinator as the tornMarker to delete from.
  51. const db = openDatabase(path)
  52. const next = (db.prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM events WHERE session_id = ?')
  53. .get(id) as { n: number }).n
  54. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  55. .run(id, next, 'assistant/chunk', 99, '{not valid json')
  56. db.close()
  57. },
  58. cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
  59. }
  60. })
  61. describe('scanRows', () => {
  62. // scanRows works off EventRows (data is a JSON string column); build them from
  63. // SessionEvents so the unit tests read in terms of the event vocabulary.
  64. const rows = (events: SessionEvent[]): EventRow[] =>
  65. events.map(e => ({ seq: e.seq, type: e.type, time: e.time, data: JSON.stringify(e.data) }))
  66. it('preserves the full log when it ends exactly on a turn/end (no torn tail)', () => {
  67. const { preserved, tornFrom } = scanRows(rows(oneTurnLog()))
  68. expect(preserved).toEqual(oneTurnLog())
  69. expect(tornFrom).toBeUndefined()
  70. })
  71. it('PRESERVES the real events of an interrupted turn after the last turn/end', () => {
  72. // turn 1 committed (0..5) + a crashed turn 2 (turn/start 6, step/start 7, no
  73. // close): all 8 rows are intact, so the whole prefix is preserved and there
  74. // is no torn fragment to delete. (load() then synthesizes the closers.)
  75. const withOpenTurn: SessionEvent[] = [
  76. ...oneTurnLog(),
  77. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  78. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  79. ]
  80. const { preserved, tornFrom } = scanRows(rows(withOpenTurn))
  81. expect(preserved.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  82. expect(tornFrom).toBeUndefined()
  83. })
  84. it('preserves the contiguous prefix and flags a torn tail at a seq gap', () => {
  85. // A gap after seq 0 (no committed turn/end): seq 0 is the preserved
  86. // interrupted-turn event; the gap bounds it and marks the torn fragment.
  87. const gapped: SessionEvent[] = [
  88. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  89. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  90. ]
  91. const { preserved, tornFrom } = scanRows(rows(gapped))
  92. expect(preserved.map(e => e.seq)).toEqual([0])
  93. expect(tornFrom).toBe(1)
  94. })
  95. it('an empty log preserves nothing and has no torn tail', () => {
  96. expect(scanRows([])).toEqual({ preserved: [] })
  97. })
  98. it('throws on a seq gap inside the committed region (before the last turn/end)', () => {
  99. const gapped: SessionEvent[] = [
  100. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  101. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  102. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  103. ]
  104. expect(() => scanRows(rows(gapped))).toThrow(/seq gap in committed region/)
  105. })
  106. it('throws on an unparsable row inside the committed region', () => {
  107. const withCorruptCommitted: EventRow[] = [
  108. { seq: 0, type: 'turn/start', time: 1, data: '{not json' }, // corrupt, sits before a turn/end
  109. { seq: 1, type: 'turn/end', time: 2, data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }) },
  110. ]
  111. expect(() => scanRows(withCorruptCommitted)).toThrow(/unparsable committed event/)
  112. })
  113. it('tolerates an unparsable torn-tail row after the last turn/end', () => {
  114. const withCorruptTail: EventRow[] = [
  115. ...rows(oneTurnLog()),
  116. { seq: 6, type: 'turn/start', time: 7, data: '{not json' }, // torn fragment, no committed turn/end after
  117. ]
  118. const { preserved, tornFrom } = scanRows(withCorruptTail)
  119. expect(preserved).toEqual(oneTurnLog())
  120. expect(tornFrom).toBe(6)
  121. })
  122. })
  123. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  124. it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
  125. const path = await freshDbPath()
  126. const m = meta('crash')
  127. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  128. const ctx1 = new Context()
  129. await ctx1.plugin(SessionStore)
  130. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  131. await ctx1.sessionPersistence.create(m)
  132. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  133. await ctx1.sessionPersistence.append(m.id, [
  134. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  135. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  136. ])
  137. await fiber1.dispose()
  138. // Run 2: load PRESERVES the interrupted turn's real events (a turn can be huge
  139. // — never truncated) and closes the orphaned turn with synthetic boundary
  140. // events: step/end (the step was open) then turn/end {interrupted}.
  141. const ctx2 = new Context()
  142. await ctx2.plugin(SessionStore)
  143. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  144. const loaded = await ctx2.sessionPersistence.load(m.id)
  145. expect(loaded.events.map(e => e.type)).toEqual([
  146. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  147. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  148. ])
  149. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  150. const last = loaded.events.at(-1)!
  151. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  152. // load durably closed the turn, so the next append continues at the balanced
  153. // length (seq 10) and a reload round-trips identically.
  154. await ctx2.sessionPersistence.append(m.id, [
  155. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  156. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  157. ])
  158. const reloaded = await ctx2.sessionPersistence.load(m.id)
  159. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  160. await fiber2.dispose()
  161. })
  162. it('load() durably closes the interrupted turn: the synthetic closers are on disk after load', async () => {
  163. const path = await freshDbPath()
  164. const m = meta('load-closes')
  165. const b1 = await backend(path)
  166. await b1.ctx.sessionPersistence.create(m)
  167. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  168. await b1.dispose()
  169. // Hand-write an interrupted turn (turn/start seq 6, no turn/end).
  170. const db = openDatabase(path)
  171. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  172. .run(m.id, 'turn/start', JSON.stringify({ turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } }))
  173. db.close()
  174. const b2 = await backend(path)
  175. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  176. // turn 2's real turn/start (seq 6) is preserved + a synthetic turn/end (seq 7).
  177. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  178. expect(loaded.events.at(-1)!.type).toBe('turn/end')
  179. // load() is mutating: the synthetic turn/end MUST be on disk so the stored log
  180. // is balanced and the cursor is truthful (contract: load closes, not defers).
  181. const probe = openDatabase(path)
  182. const stored = probe.prepare('SELECT seq, type FROM events WHERE session_id = ? ORDER BY seq').all(m.id) as { seq: number; type: string }[]
  183. probe.close()
  184. expect(stored.map(r => r.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  185. expect(stored.at(-1)!.type).toBe('turn/end')
  186. await b2.dispose()
  187. })
  188. it('all-tail load: a session whose only turn never closed is preserved and closed on load', async () => {
  189. const path = await freshDbPath()
  190. const m = meta('all-tail')
  191. const b1 = await backend(path)
  192. await b1.ctx.sessionPersistence.create(m)
  193. // A first turn that NEVER completed: turn/start + user/message, no turn/end.
  194. await b1.ctx.sessionPersistence.append(m.id, [
  195. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  196. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } } },
  197. ])
  198. await b1.dispose()
  199. // A fresh backend loads it: the interrupted (only) turn's real events are
  200. // preserved and closed with a synthetic turn/end {interrupted} — NOT
  201. // truncated. The session was materialized, so list() reports it present.
  202. const b2 = await backend(path)
  203. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  204. expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  205. expect(loaded.events.at(-1)!.type === 'turn/end' && loaded.events.at(-1)!.data).toMatchObject({ reason: { kind: 'interrupted' } })
  206. expect((await b2.ctx.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  207. await b2.dispose()
  208. })
  209. it('rejects opening a database whose schema version is not the current build (newer OR older)', async () => {
  210. const path = await freshDbPath()
  211. openDatabase(path).close() // stamp user_version = SCHEMA_VERSION
  212. // Bump user_version past what this build supports.
  213. const dbNewer = openDatabase(path)
  214. dbNewer.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`)
  215. dbNewer.close()
  216. expect(() => openDatabase(path)).toThrow(/incompatible with this build/)
  217. // A stale OLDER version (e.g. a pre-summary-drop v1 DB) is also rejected —
  218. // we do not migrate (unreleased software, no backward-compat).
  219. const olderPath = await freshDbPath()
  220. openDatabase(olderPath).close()
  221. const dbOlder = openDatabase(olderPath)
  222. dbOlder.exec('PRAGMA user_version = 1')
  223. dbOlder.close()
  224. expect(() => openDatabase(olderPath)).toThrow(/incompatible with this build/)
  225. })
  226. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  227. const path = await freshDbPath()
  228. const m = meta('corrupt-tail')
  229. const b1 = await backend(path)
  230. await b1.ctx.sessionPersistence.create(m)
  231. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  232. await b1.dispose()
  233. // Hand-insert a torn tail row (seq 6, no closing turn/end) whose `data` is
  234. // invalid JSON. The contract: only a parse error in the COMMITTED region is
  235. // unloadable; a torn tail must be discarded. scanRows finds the last
  236. // turn/end on the seq+type columns (never parsing tail `data`), so the
  237. // unparsable row after it bounds the preserved prefix and is deleted by load.
  238. const db = openDatabase(path)
  239. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  240. .run(m.id, 'turn/start', '{not valid json')
  241. db.close()
  242. const b2 = await backend(path)
  243. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  244. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  245. // load physically deleted the corrupt tail row, so a fresh append continues.
  246. await b2.ctx.sessionPersistence.append(m.id, [
  247. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  248. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  249. ])
  250. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  251. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  252. await b2.dispose()
  253. })
  254. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  255. const ctx = new Context()
  256. await ctx.plugin(SessionStore)
  257. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  258. const m = meta('rollback')
  259. await ctx.sessionPersistence.create(m)
  260. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  261. // A batch that re-states an already-stored seq must be rejected and leave
  262. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  263. // inside the transaction → ROLLBACK).
  264. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  265. const loaded = await ctx.sessionPersistence.load(m.id)
  266. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  267. await fiber.dispose()
  268. })
  269. it('persists across separate backend instances over the same file', async () => {
  270. const path = await freshDbPath()
  271. const m = meta('persist', '/proj')
  272. const ctx1 = new Context()
  273. await ctx1.plugin(SessionStore)
  274. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  275. await ctx1.sessionPersistence.create(m)
  276. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  277. await fiber1.dispose()
  278. const ctx2 = new Context()
  279. await ctx2.plugin(SessionStore)
  280. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  281. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  282. const loaded = await ctx2.sessionPersistence.load(m.id)
  283. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj' })
  284. expect(loaded.events).toEqual(oneTurnLog())
  285. await fiber2.dispose()
  286. })
  287. it('exposes the schema version constant', () => {
  288. expect(SCHEMA_VERSION).toBe(2)
  289. })
  290. })
  291. describe('SessionPersistenceSqlite: edge cases', () => {
  292. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  293. const path = await freshDbPath()
  294. const m = meta('rollback-insert')
  295. const b1 = await backend(path)
  296. await b1.ctx.sessionPersistence.create(m)
  297. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  298. // A SECOND backend over the same file loads the session first, so it adopts
  299. // cursor 6 (the committed length) into its OWN in-memory state.
  300. const b2 = await backend(path)
  301. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  302. const turn2: SessionEvent[] = [
  303. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  304. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  305. ]
  306. // b1 commits seq 6..7 first.
  307. await b1.ctx.sessionPersistence.append(m.id, turn2)
  308. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  309. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  310. // mid-transaction → ROLLBACK + rethrow.
  311. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  312. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  313. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  314. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  315. await b1.dispose()
  316. await b2.dispose()
  317. })
  318. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  319. const path = await freshDbPath()
  320. // Instance 1 materializes a session and disposes.
  321. const b1 = await backend(path)
  322. const s1 = b1.ctx.sessions.create(SessionId('hmr-collide'))
  323. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  324. await b1.ctx.parallel('session/flush', s1)
  325. await b1.dispose()
  326. // A fresh context with an UNRELATED live session reusing the id meets a
  327. // materialized row that is NOT a prefix of its events → reject.
  328. const ctx = new Context()
  329. await ctx.plugin(SessionStore)
  330. let session!: Session
  331. await ctx.plugin(Object.assign((inner: Context) => {
  332. session = inner.sessions.create(SessionId('hmr-collide'))
  333. }, { inject: ['sessions'] }))
  334. session.append('turn/start', { turn: 9, trigger: { kind: 'message', source: { kind: 'user' } } })
  335. await ctx.plugin(SessionPersistenceSqlite, { path })
  336. await expect(ctx.parallel('session/flush', session)).rejects.toThrow(/id collision/)
  337. await ctx.fiber.dispose()
  338. })
  339. })