sqlite.spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { existsSync } from 'node:fs'
  4. import { mkdtemp, rm, symlink } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { Session, SessionEvent, SurfaceEvent, SurfaceEventType } from '@deepseek-ai/dsh-session'
  9. import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
  10. import { openDatabase, rowToEvent, scanRows, type EventRow } from '../src/schema.ts'
  11. import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts'
  12. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  13. const dirs: string[] = []
  14. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  15. async function freshDbPath(): Promise<string> {
  16. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-'))
  17. dirs.push(dir)
  18. return join(dir, 'sessions.db')
  19. }
  20. /** A context with the session store + SQLite backend, plus a teardown. */
  21. async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
  22. const ctx = new Context()
  23. await ctx.plugin(SessionStore)
  24. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  25. return { ctx, dispose: () => fiber.dispose() }
  26. }
  27. // The payoff: the SAME backend-agnostic contract the JSONL backend runs, now
  28. // proving the SQLite backend satisfies identical semantics.
  29. runPersistenceContract('sqlite', async () => {
  30. const ctx = new Context()
  31. await ctx.plugin(SessionStore)
  32. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  33. return {
  34. persistence: ctx.sessionPersistence,
  35. dispose: async () => { await fiber.dispose() },
  36. }
  37. })
  38. // Run the shared coordinator orchestration suite against the real SQLite backend.
  39. // A FILE-backed db (not :memory:) is the shared storage scope so two mounted
  40. // instances see the same rows (HMR/reload). `corruptTail` INSERTs a row past the
  41. // committed seq whose `data` is invalid JSON — a never-committed torn tail that
  42. // drives the coordinator's commitRepair-with-tornMarker branch over real db rows.
  43. runCoordinatorContract('sqlite', async (): Promise<CoordinatorFixture> => {
  44. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-coord-'))
  45. const path = join(dir, 'sessions.db')
  46. return {
  47. mount: async ctx => ctx.plugin(SessionPersistenceSqlite, { path }),
  48. corruptTail: async (id) => {
  49. // A row past the committed region whose `data` does not parse: scanRows
  50. // bounds the preserved prefix at it and returns its seq as tornFrom, which
  51. // the backend surfaces to the coordinator as the tornMarker to delete from.
  52. const db = openDatabase(path, 'wal')
  53. const next = (db.prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM events WHERE session_id = ?')
  54. .get(id) as { n: number }).n
  55. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  56. .run(id, next, 'assistant/chunk', 99, '{not valid json')
  57. db.close()
  58. },
  59. cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
  60. }
  61. })
  62. describe('scanRows', () => {
  63. // scanRows works off EventRows (data is a JSON string column); build them from
  64. // SessionEvents so the unit tests read in terms of the event vocabulary. Surface
  65. // fields are serialized to their nullable columns so a round trip is faithful.
  66. const rows = (events: SessionEvent[]): EventRow[] =>
  67. events.map((e) => {
  68. const se = e as SessionEvent<SurfaceEventType>
  69. return {
  70. seq: e.seq, type: e.type, time: e.time, data: JSON.stringify(e.data),
  71. source_event_seqs: se.sourceEventSeqs !== undefined ? JSON.stringify(se.sourceEventSeqs) : null,
  72. surface_op: se.surfaceOp !== undefined ? JSON.stringify(se.surfaceOp) : null,
  73. }
  74. })
  75. it('preserves the full log when it ends exactly on a turn/end (no torn tail)', () => {
  76. const { preserved, tornFrom } = scanRows(rows(oneTurnLog()))
  77. expect(preserved).toEqual(oneTurnLog())
  78. expect(tornFrom).toBeUndefined()
  79. })
  80. it('PRESERVES the real events of an interrupted turn after the last turn/end', () => {
  81. // turn 1 committed (0..5) + a crashed turn 2 (turn/start 6, step/start 7, no
  82. // close): all 8 rows are intact, so the whole prefix is preserved and there
  83. // is no torn fragment to delete. (load() then synthesizes the closers.)
  84. const withOpenTurn: SessionEvent[] = [
  85. ...oneTurnLog(),
  86. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  87. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  88. ]
  89. const { preserved, tornFrom } = scanRows(rows(withOpenTurn))
  90. expect(preserved.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  91. expect(tornFrom).toBeUndefined()
  92. })
  93. it('preserves the contiguous prefix and flags a torn tail at a seq gap', () => {
  94. // A gap after seq 0 (no committed turn/end): seq 0 is the preserved
  95. // interrupted-turn event; the gap bounds it and marks the torn fragment.
  96. const gapped: SessionEvent[] = [
  97. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  98. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  99. ]
  100. const { preserved, tornFrom } = scanRows(rows(gapped))
  101. expect(preserved.map(e => e.seq)).toEqual([0])
  102. expect(tornFrom).toBe(1)
  103. })
  104. it('an empty log preserves nothing and has no torn tail', () => {
  105. expect(scanRows([])).toEqual({ preserved: [] })
  106. })
  107. it('throws on a seq gap inside the committed region (before the last turn/end)', () => {
  108. const gapped: SessionEvent[] = [
  109. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  110. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  111. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  112. ]
  113. expect(() => scanRows(rows(gapped))).toThrow(/seq gap in committed region/)
  114. })
  115. it('throws on an unparsable row inside the committed region', () => {
  116. const withCorruptCommitted: EventRow[] = [
  117. { seq: 0, type: 'turn/start', time: 1, data: '{not json', source_event_seqs: null, surface_op: null }, // corrupt, sits before a turn/end
  118. { seq: 1, type: 'turn/end', time: 2, data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }), source_event_seqs: null, surface_op: null },
  119. ]
  120. expect(() => scanRows(withCorruptCommitted)).toThrow(/unparsable committed event/)
  121. })
  122. it('tolerates an unparsable torn-tail row after the last turn/end', () => {
  123. const withCorruptTail: EventRow[] = [
  124. ...rows(oneTurnLog()),
  125. { seq: 6, type: 'turn/start', time: 7, data: '{not json', source_event_seqs: null, surface_op: null }, // torn fragment, no committed turn/end after
  126. ]
  127. const { preserved, tornFrom } = scanRows(withCorruptTail)
  128. expect(preserved).toEqual(oneTurnLog())
  129. expect(tornFrom).toBe(6)
  130. })
  131. })
  132. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  133. it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
  134. const path = await freshDbPath()
  135. const m = meta('crash')
  136. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  137. const ctx1 = new Context()
  138. await ctx1.plugin(SessionStore)
  139. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  140. await ctx1.sessionPersistence.create(m)
  141. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  142. await ctx1.sessionPersistence.append(m.id, [
  143. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  144. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  145. ])
  146. await fiber1.dispose()
  147. // Run 2: load PRESERVES the interrupted turn's real events (a turn can be huge
  148. // — never truncated) and closes the orphaned turn with synthetic boundary
  149. // events: step/end (the step was open) then turn/end {interrupted}.
  150. const ctx2 = new Context()
  151. await ctx2.plugin(SessionStore)
  152. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  153. const loaded = await ctx2.sessionPersistence.load(m.id)
  154. expect(loaded.events.map(e => e.type)).toEqual([
  155. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  156. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  157. ])
  158. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  159. const last = loaded.events.at(-1)!
  160. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  161. // load durably closed the turn, so the next append continues at the balanced
  162. // length (seq 10) and a reload round-trips identically.
  163. await ctx2.sessionPersistence.append(m.id, [
  164. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  165. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  166. ])
  167. const reloaded = await ctx2.sessionPersistence.load(m.id)
  168. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  169. await fiber2.dispose()
  170. })
  171. it('load() durably closes the interrupted turn: the synthetic closers are on disk after load', async () => {
  172. const path = await freshDbPath()
  173. const m = meta('load-closes')
  174. const b1 = await backend(path)
  175. await b1.ctx.sessionPersistence.create(m)
  176. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  177. await b1.dispose()
  178. // Hand-write an interrupted turn (turn/start seq 6, no turn/end).
  179. const db = openDatabase(path, 'wal')
  180. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  181. .run(m.id, 'turn/start', JSON.stringify({ turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } }))
  182. db.close()
  183. const b2 = await backend(path)
  184. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  185. // turn 2's real turn/start (seq 6) is preserved + a synthetic turn/end (seq 7).
  186. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  187. expect(loaded.events.at(-1)!.type).toBe('turn/end')
  188. // load() is mutating: the synthetic turn/end MUST be on disk so the stored log
  189. // is balanced and the cursor is truthful (contract: load closes, not defers).
  190. const probe = openDatabase(path, 'wal')
  191. const stored = probe.prepare('SELECT seq, type FROM events WHERE session_id = ? ORDER BY seq').all(m.id) as { seq: number; type: string }[]
  192. probe.close()
  193. expect(stored.map(r => r.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  194. expect(stored.at(-1)!.type).toBe('turn/end')
  195. await b2.dispose()
  196. })
  197. it('all-tail load: a session whose only turn never closed is preserved and closed on load', async () => {
  198. const path = await freshDbPath()
  199. const m = meta('all-tail')
  200. const b1 = await backend(path)
  201. await b1.ctx.sessionPersistence.create(m)
  202. // A first turn that NEVER completed: turn/start + user/message, no turn/end.
  203. await b1.ctx.sessionPersistence.append(m.id, [
  204. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  205. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } } },
  206. ])
  207. await b1.dispose()
  208. // A fresh backend loads it: the interrupted (only) turn's real events are
  209. // preserved and closed with a synthetic turn/end {interrupted} — NOT
  210. // truncated. The session was materialized, so list() reports it present.
  211. const b2 = await backend(path)
  212. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  213. expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  214. expect(loaded.events.at(-1)!.type === 'turn/end' && loaded.events.at(-1)!.data).toMatchObject({ reason: { kind: 'interrupted' } })
  215. expect((await b2.ctx.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  216. await b2.dispose()
  217. })
  218. it('rejects opening a database whose schema version is not the current build (newer OR older)', async () => {
  219. const path = await freshDbPath()
  220. openDatabase(path, 'wal').close() // stamp user_version = SCHEMA_VERSION
  221. // Bump user_version past what this build supports.
  222. const dbNewer = openDatabase(path, 'wal')
  223. dbNewer.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`)
  224. dbNewer.close()
  225. expect(() => openDatabase(path, 'wal')).toThrow(/incompatible with this build/)
  226. // The immediately preceding layout lacks the required store identity and is
  227. // rejected rather than migrated (unreleased software, no backward-compat).
  228. const olderPath = await freshDbPath()
  229. openDatabase(olderPath, 'wal').close()
  230. const dbOlder = openDatabase(olderPath, 'wal')
  231. dbOlder.exec(`PRAGMA user_version = ${SCHEMA_VERSION - 1}`)
  232. dbOlder.close()
  233. expect(() => openDatabase(olderPath, 'wal')).toThrow(/incompatible with this build/)
  234. })
  235. it('rejects a sibling v3 database (the merge-collided version) rather than opening it against missing columns', async () => {
  236. // Two unmerged branches each shipped a DISTINCT layout under user_version 3
  237. // (one added only `seed_length`, the other only the surface columns). The
  238. // the current build rejects every older layout; an on-disk v3 is ambiguous and is missing at least one
  239. // of this build's columns, so it MUST be rejected, not opened. Stamp a v3
  240. // database and confirm the version check refuses it.
  241. const path = await freshDbPath()
  242. openDatabase(path, 'wal').close() // creates + stamps user_version = SCHEMA_VERSION
  243. const db = openDatabase(path, 'wal')
  244. db.exec('PRAGMA user_version = 3')
  245. db.close()
  246. expect(() => openDatabase(path, 'wal')).toThrow(/schema version 3, incompatible with this build/)
  247. })
  248. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  249. const path = await freshDbPath()
  250. const m = meta('corrupt-tail')
  251. const b1 = await backend(path)
  252. await b1.ctx.sessionPersistence.create(m)
  253. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  254. await b1.dispose()
  255. // Hand-insert a torn tail row (seq 6, no closing turn/end) whose `data` is
  256. // invalid JSON. The contract: only a parse error in the COMMITTED region is
  257. // unloadable; a torn tail must be discarded. scanRows finds the last
  258. // turn/end on the seq+type columns (never parsing tail `data`), so the
  259. // unparsable row after it bounds the preserved prefix and is deleted by load.
  260. const db = openDatabase(path, 'wal')
  261. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  262. .run(m.id, 'turn/start', '{not valid json')
  263. db.close()
  264. const b2 = await backend(path)
  265. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  266. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  267. // load physically deleted the corrupt tail row, so a fresh append continues.
  268. await b2.ctx.sessionPersistence.append(m.id, [
  269. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  270. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  271. ])
  272. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  273. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  274. await b2.dispose()
  275. })
  276. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  277. const ctx = new Context()
  278. await ctx.plugin(SessionStore)
  279. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  280. const m = meta('rollback')
  281. await ctx.sessionPersistence.create(m)
  282. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  283. // A batch that re-states an already-stored seq must be rejected and leave
  284. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  285. // inside the transaction → ROLLBACK).
  286. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  287. const loaded = await ctx.sessionPersistence.load(m.id)
  288. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  289. await fiber.dispose()
  290. })
  291. it('persists across separate backend instances over the same file', async () => {
  292. const path = await freshDbPath()
  293. const m = meta('persist', '/proj')
  294. const ctx1 = new Context()
  295. await ctx1.plugin(SessionStore)
  296. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  297. await ctx1.sessionPersistence.create(m)
  298. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  299. await fiber1.dispose()
  300. const ctx2 = new Context()
  301. await ctx2.plugin(SessionStore)
  302. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  303. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  304. const loaded = await ctx2.sessionPersistence.load(m.id)
  305. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj' })
  306. expect(loaded.events).toEqual(oneTurnLog())
  307. await fiber2.dispose()
  308. })
  309. it('source-qualifies revisions across stores while preserving same-file reopen identity', async () => {
  310. const pathA = await freshDbPath()
  311. const pathB = await freshDbPath()
  312. const m = meta('revision-source')
  313. const a = await backend(pathA)
  314. await a.ctx.sessionPersistence.create(m)
  315. await a.ctx.sessionPersistence.append(m.id, oneTurnLog())
  316. const revisionA = (await a.ctx.sessionPersistence.listSnapshots())[0]?.revision
  317. await a.dispose()
  318. const probeA = openDatabase(pathA, 'wal')
  319. const storeIdA = (probeA.prepare(
  320. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  321. ).get() as { store_id: string }).store_id
  322. probeA.close()
  323. const aliasA = `${pathA}.alias`
  324. await symlink(pathA, aliasA)
  325. const reopenedA = await backend(aliasA)
  326. expect((await reopenedA.ctx.sessionPersistence.listSnapshots())[0]?.revision).toBe(revisionA)
  327. await reopenedA.dispose()
  328. const b = await backend(pathB)
  329. await b.ctx.sessionPersistence.create(m)
  330. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  331. const revisionB = (await b.ctx.sessionPersistence.listSnapshots())[0]?.revision
  332. const probeB = openDatabase(pathB, 'wal')
  333. const storeIdB = (probeB.prepare(
  334. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  335. ).get() as { store_id: string }).store_id
  336. probeB.close()
  337. expect(storeIdB).not.toBe(storeIdA)
  338. expect(revisionB).not.toBe(revisionA)
  339. expect(String(revisionA)).toMatch(/:revision:1$/)
  340. expect(String(revisionB)).toMatch(/:revision:1$/)
  341. await b.dispose()
  342. })
  343. it('exposes the schema version constant', () => {
  344. expect(SCHEMA_VERSION).toBe(6)
  345. })
  346. it('keeps the revision stable for an empty repair hook', async () => {
  347. const b = await backend()
  348. const m = meta('empty-repair')
  349. await b.ctx.sessionPersistence.create(m)
  350. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  351. const before = await b.ctx.sessionPersistence.listSnapshots()
  352. await (b.ctx.sessionPersistence as SessionPersistenceSqlite).commitRepair(m, undefined, [])
  353. expect(await b.ctx.sessionPersistence.listSnapshots()).toEqual(before)
  354. await b.dispose()
  355. })
  356. })
  357. describe('SessionPersistenceSqlite: edge cases', () => {
  358. it('rejects and closes a current-schema database with an invalid store identity', async () => {
  359. const path = await freshDbPath()
  360. const db = openDatabase(path, 'wal')
  361. db.exec("UPDATE persistence_state SET store_id = '' WHERE singleton = 1")
  362. db.close()
  363. const b = await backend(path)
  364. await expect(b.ctx.sessionPersistence.listSnapshots()).rejects.toThrow(/no valid store identity/)
  365. await expect(b.dispose()).resolves.toBeUndefined()
  366. })
  367. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  368. const path = await freshDbPath()
  369. const m = meta('rollback-insert')
  370. const b1 = await backend(path)
  371. await b1.ctx.sessionPersistence.create(m)
  372. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  373. // A SECOND backend over the same file loads the session first, so it adopts
  374. // cursor 6 (the committed length) into its OWN in-memory state.
  375. const b2 = await backend(path)
  376. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  377. const turn2: SessionEvent[] = [
  378. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  379. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  380. ]
  381. // b1 commits seq 6..7 first.
  382. await b1.ctx.sessionPersistence.append(m.id, turn2)
  383. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  384. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  385. // mid-transaction → ROLLBACK + rethrow.
  386. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  387. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  388. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  389. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  390. await b1.dispose()
  391. await b2.dispose()
  392. })
  393. it('journalMode config reaches the database (default wal, rollback modes selectable)', async () => {
  394. // :memory: databases always report journal_mode=memory, so probe file DBs.
  395. const walPath = await freshDbPath()
  396. const bWal = await backend(walPath)
  397. await bWal.ctx.sessionPersistence.create(meta('jm-wal'))
  398. expect((openDatabase(walPath, 'wal').prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('wal')
  399. await bWal.dispose()
  400. const deletePath = await freshDbPath()
  401. const ctx = new Context()
  402. await ctx.plugin(SessionStore)
  403. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: deletePath, journalMode: 'delete' })
  404. await ctx.sessionPersistence.create(meta('jm-delete'))
  405. // Probe through a second connection: journal_mode=delete is a per-database
  406. // property only insofar as no WAL files exist — assert the world, not the
  407. // backend's self-report (no -wal sidecar after writes in delete mode).
  408. const db = openDatabase(deletePath, 'delete')
  409. expect((db.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('delete')
  410. db.close()
  411. expect(existsSync(`${deletePath}-wal`)).toBe(false)
  412. await fiber.dispose()
  413. })
  414. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  415. const path = await freshDbPath()
  416. // Instance 1 materializes a session and disposes.
  417. const b1 = await backend(path)
  418. const s1 = b1.ctx.sessions.create(SessionId('hmr-collide'))
  419. appendLog(s1, oneTurnLog())
  420. await b1.ctx.parallel('session/flush', s1)
  421. await b1.dispose()
  422. // A fresh context with an UNRELATED live session reusing the id meets a
  423. // materialized row that is NOT a prefix of its events → reject.
  424. const ctx = new Context()
  425. await ctx.plugin(SessionStore)
  426. let session!: Session
  427. await ctx.plugin(Object.assign((inner: Context) => {
  428. session = inner.sessions.create(SessionId('hmr-collide'))
  429. }, { inject: ['sessions'] }))
  430. session.append('turn/start', { turn: 9, trigger: { kind: 'message', source: { kind: 'user' } } })
  431. await ctx.plugin(SessionPersistenceSqlite, { path })
  432. await expect(ctx.parallel('session/flush', session)).rejects.toThrow(/id collision/)
  433. await ctx.fiber.dispose()
  434. })
  435. })
  436. describe('surface field round-trip', () => {
  437. it('rowToEvent parses surface fields from EventRow columns', () => {
  438. const row: EventRow = {
  439. seq: 0, type: 'assistant/message', time: 1,
  440. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  441. source_event_seqs: JSON.stringify([3, 5]),
  442. surface_op: JSON.stringify('append'),
  443. }
  444. const event = rowToEvent(row)
  445. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([3, 5])
  446. expect((event as SurfaceEvent).surfaceOp).toBe('append')
  447. })
  448. it('rowToEvent handles replace surfaceOp object', () => {
  449. const row: EventRow = {
  450. seq: 0, type: 'assistant/message', time: 1,
  451. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  452. source_event_seqs: JSON.stringify([0, 1]),
  453. surface_op: JSON.stringify({ op: 'replace', start: 0, end: 1 }),
  454. }
  455. const event = rowToEvent(row)
  456. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  457. expect((event as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 1 })
  458. })
  459. it('scanRows with surface columns reconstructs events with surface fields', () => {
  460. const rows: EventRow[] = [
  461. { seq: 0, type: 'user/message', time: 1,
  462. data: JSON.stringify({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }),
  463. source_event_seqs: null, surface_op: '{"op":"replace","start":0,"end":0}' },
  464. { seq: 1, type: 'turn/end', time: 2,
  465. data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }),
  466. source_event_seqs: null, surface_op: null },
  467. ]
  468. const { preserved } = scanRows(rows)
  469. expect(preserved).toHaveLength(2)
  470. expect((preserved[0]! as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  471. expect((preserved[0]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  472. expect((preserved[1] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  473. })
  474. it('append and load round-trips surface fields through SQLite', async () => {
  475. const ctx = new Context()
  476. await ctx.plugin(SessionStore)
  477. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  478. const session = ctx.sessions.create(SessionId('roundtrip-surface'))
  479. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  480. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  481. session.append('assistant/message', { turn: 1, step: 1, content: [] }, { surfaceOp: 'append', sourceEventSeqs: [0] })
  482. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  483. await ctx.parallel('session/flush', session)
  484. const loaded = await ctx.sessionPersistence.load(SessionId('roundtrip-surface'))
  485. expect(loaded.events).toHaveLength(4)
  486. const um = loaded.events[1]!
  487. expect((um as SurfaceEvent).surfaceOp).toBe('append')
  488. expect((um as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  489. const am = loaded.events[2]!
  490. expect((am as SurfaceEvent).surfaceOp).toBe('append')
  491. expect((am as SurfaceEvent).sourceEventSeqs).toEqual([0])
  492. await fiber.dispose()
  493. })
  494. it('persists events with surfaceOp but no sourceEventSeqs (covers null branch in surfaceBindings)', async () => {
  495. const ctx = new Context()
  496. await ctx.plugin(SessionStore)
  497. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  498. const session = ctx.sessions.create(SessionId('surface-noseq'))
  499. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  500. session.append('steering/message', { turn: 1, content: [], source: { kind: 'user' } }, { surfaceOp: 'append' })
  501. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  502. await ctx.parallel('session/flush', session)
  503. const loaded = await ctx.sessionPersistence.load(SessionId('surface-noseq'))
  504. expect((loaded.events[1]! as SurfaceEvent).surfaceOp).toBe('append')
  505. expect((loaded.events[1]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  506. await fiber.dispose()
  507. })
  508. })