sqlite.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { existsSync } from 'node:fs'
  4. import { chmod, mkdtemp, rm, stat, symlink, writeFile } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { dirname, 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 { sessionLiveOwner } from '@deepseek-ai/dsh-session-persistence'
  11. import { openDatabase, rowToEvent, scanRows, type EventRow } from '../src/schema.ts'
  12. import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts'
  13. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  14. const dirs: string[] = []
  15. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  16. async function expectFlushError(promise: Promise<unknown>, message: RegExp): Promise<void> {
  17. try {
  18. await promise
  19. } catch (error) {
  20. expect(error).toBeInstanceOf(Error)
  21. expect((error as Error).message).toMatch(message)
  22. return
  23. }
  24. throw new Error('expected flush to reject')
  25. }
  26. async function freshDbPath(): Promise<string> {
  27. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-'))
  28. dirs.push(dir)
  29. return join(dir, 'sessions.db')
  30. }
  31. /** A context with the session store + SQLite backend, plus a teardown. */
  32. async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
  33. const ctx = new Context()
  34. await ctx.plugin(SessionStore)
  35. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  36. return { ctx, dispose: () => fiber.dispose() }
  37. }
  38. // Run the same backend-agnostic contract as JSONL to pin identical semantics.
  39. runPersistenceContract('sqlite', async () => {
  40. const ctx = new Context()
  41. await ctx.plugin(SessionStore)
  42. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  43. return {
  44. persistence: ctx.sessionPersistence,
  45. dispose: async () => { await fiber.dispose() },
  46. }
  47. })
  48. // A file-backed database lets two mounts share rows across reload. `corruptTail` inserts invalid
  49. // JSON past the committed seq, exercising coordinator repair against real database rows.
  50. runCoordinatorContract('sqlite', async (): Promise<CoordinatorFixture> => {
  51. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-coord-'))
  52. const path = join(dir, 'sessions.db')
  53. return {
  54. mount: async ctx => ctx.plugin(SessionPersistenceSqlite, { path }),
  55. corruptTail: async (id) => {
  56. // A row past the committed region whose `data` does not parse: scanRows
  57. // bounds the preserved prefix at it and returns its seq as tornFrom, which
  58. // the backend surfaces to the coordinator as the tornMarker to delete from.
  59. const db = openDatabase(path, 'wal')
  60. const next = (db.prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM events WHERE session_id = ?')
  61. .get(id) as { n: number }).n
  62. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  63. .run(id, next, 'assistant/chunk', 99, '{not valid json')
  64. db.close()
  65. },
  66. cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
  67. }
  68. })
  69. describe('scanRows', () => {
  70. // scanRows works off EventRows (data is a JSON string column); build them from SessionEvents
  71. // so the unit tests read in terms of the event vocabulary. Surface metadata is serialized to
  72. // its nullable columns so the conversion remains faithful.
  73. const rows = (events: SessionEvent[]): EventRow[] =>
  74. events.map((e) => {
  75. const se = e as SessionEvent<SurfaceEventType>
  76. return {
  77. seq: e.seq, type: e.type, time: e.time, data: JSON.stringify(e.data),
  78. source_event_seqs: se.sourceEventSeqs !== undefined ? JSON.stringify(se.sourceEventSeqs) : null,
  79. surface_op: se.surfaceOp !== undefined ? JSON.stringify(se.surfaceOp) : null,
  80. }
  81. })
  82. it('preserves the full log when it ends exactly on a turn/end (no torn tail)', () => {
  83. const { preserved, tornFrom } = scanRows(rows(oneTurnLog()))
  84. expect(preserved).toEqual(oneTurnLog())
  85. expect(tornFrom).toBeUndefined()
  86. })
  87. it('PRESERVES the real events of an interrupted turn after the last turn/end', () => {
  88. // turn 1 committed (0..5) + a crashed turn 2 (turn/start 6, step/start 7, no
  89. // close): all 8 rows are intact, so the whole prefix is preserved and there
  90. // is no torn fragment to delete. (load() then synthesizes the closers.)
  91. const withOpenTurn: SessionEvent[] = [
  92. ...oneTurnLog(),
  93. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  94. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  95. ]
  96. const { preserved, tornFrom } = scanRows(rows(withOpenTurn))
  97. expect(preserved.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  98. expect(tornFrom).toBeUndefined()
  99. })
  100. it('preserves the contiguous prefix and flags a torn tail at a seq gap', () => {
  101. // A gap after seq 0 (no committed turn/end): seq 0 is the preserved
  102. // interrupted-turn event; the gap bounds it and marks the torn fragment.
  103. const gapped: SessionEvent[] = [
  104. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  105. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  106. ]
  107. const { preserved, tornFrom } = scanRows(rows(gapped))
  108. expect(preserved.map(e => e.seq)).toEqual([0])
  109. expect(tornFrom).toBe(1)
  110. })
  111. it('an empty log preserves nothing and has no torn tail', () => {
  112. expect(scanRows([])).toEqual({ preserved: [] })
  113. })
  114. it('throws on a seq gap inside the committed region (before the last turn/end)', () => {
  115. const gapped: SessionEvent[] = [
  116. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  117. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  118. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  119. ]
  120. expect(() => scanRows(rows(gapped))).toThrow(/seq gap in committed region/)
  121. })
  122. it('throws on an unparsable row inside the committed region', () => {
  123. const withCorruptCommitted: EventRow[] = [
  124. { seq: 0, type: 'turn/start', time: 1, data: '{not json', source_event_seqs: null, surface_op: null }, // corrupt, sits before a turn/end
  125. { seq: 1, type: 'turn/end', time: 2, data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }), source_event_seqs: null, surface_op: null },
  126. ]
  127. expect(() => scanRows(withCorruptCommitted)).toThrow(/unparsable committed event/)
  128. })
  129. it('tolerates an unparsable torn-tail row after the last turn/end', () => {
  130. const withCorruptTail: EventRow[] = [
  131. ...rows(oneTurnLog()),
  132. { seq: 6, type: 'turn/start', time: 7, data: '{not json', source_event_seqs: null, surface_op: null }, // torn fragment, no committed turn/end after
  133. ]
  134. const { preserved, tornFrom } = scanRows(withCorruptTail)
  135. expect(preserved).toEqual(oneTurnLog())
  136. expect(tornFrom).toBe(6)
  137. })
  138. })
  139. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  140. it('rejects a stored v0 log containing a legacy request/header-delta event', async () => {
  141. const path = await freshDbPath()
  142. const m = meta('legacy-header-delta', '/legacy')
  143. const db = openDatabase(path, 'wal')
  144. db.prepare('INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length, delegation_depth, incarnation, revision) VALUES (?, ?, ?, ?, NULL, NULL, NULL, ?, 1)')
  145. .run(m.id, m.version, m.createdAt, m.cwd ?? null, 'legacy-header-delta')
  146. const insert = db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  147. insert.run(m.id, 0, 'turn/start', 1, JSON.stringify({ turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }))
  148. insert.run(m.id, 1, 'request/header-delta', 2, JSON.stringify({ config: { model: 'legacy' } }))
  149. insert.run(m.id, 2, 'turn/end', 3, JSON.stringify({ turn: 1, reason: { kind: 'completed' } }))
  150. db.close()
  151. const mounted = await backend(path)
  152. await expect(mounted.ctx.sessionPersistence.load(m.id)).rejects.toThrow(/unsupported legacy request\/header-delta event at seq 1/)
  153. await mounted.dispose()
  154. })
  155. it('rejects a stored v0 full header carrying the legacy fallback reason', async () => {
  156. const path = await freshDbPath()
  157. const m = meta('legacy-header-fallback', '/legacy')
  158. const db = openDatabase(path, 'wal')
  159. db.prepare('INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length, delegation_depth, incarnation, revision) VALUES (?, ?, ?, ?, NULL, NULL, NULL, ?, 1)')
  160. .run(m.id, m.version, m.createdAt, m.cwd ?? null, 'legacy-header-fallback')
  161. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  162. .run(m.id, 0, 'request/header', 1, JSON.stringify({
  163. header: { config: { model: 'legacy' } },
  164. reason: 'fallback',
  165. }))
  166. db.close()
  167. const mounted = await backend(path)
  168. await expect(mounted.ctx.sessionPersistence.load(m.id))
  169. .rejects.toThrow(/unsupported legacy request\/header reason "fallback" at seq 0/)
  170. await mounted.dispose()
  171. })
  172. it('has no independent per-session log location', async () => {
  173. const { ctx, dispose } = await backend()
  174. expect(ctx.sessionPersistence.locate(meta('sqlite-location'))).toBeUndefined()
  175. await dispose()
  176. })
  177. it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
  178. const path = await freshDbPath()
  179. const m = meta('crash')
  180. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  181. const ctx1 = new Context()
  182. await ctx1.plugin(SessionStore)
  183. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  184. await ctx1.sessionPersistence.create(m)
  185. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  186. await ctx1.sessionPersistence.append(m.id, [
  187. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  188. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  189. ])
  190. await fiber1.dispose()
  191. // Run 2: load PRESERVES the interrupted turn's real events (a turn can be huge
  192. // — never truncated) and closes the orphaned turn with synthetic boundary
  193. // events: step/end (the step was open) then turn/end {interrupted}.
  194. const ctx2 = new Context()
  195. await ctx2.plugin(SessionStore)
  196. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  197. const loaded = await ctx2.sessionPersistence.load(m.id)
  198. expect(loaded.events.map(e => e.type)).toEqual([
  199. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  200. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  201. ])
  202. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  203. const last = loaded.events.at(-1)!
  204. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  205. // load durably closed the turn, so the next append continues at the balanced
  206. // length (seq 10) and a reload round-trips identically.
  207. await ctx2.sessionPersistence.append(m.id, [
  208. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  209. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  210. ])
  211. const reloaded = await ctx2.sessionPersistence.load(m.id)
  212. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  213. await fiber2.dispose()
  214. })
  215. it('load() durably closes the interrupted turn: the synthetic closers are on disk after load', async () => {
  216. const path = await freshDbPath()
  217. const m = meta('load-closes')
  218. const b1 = await backend(path)
  219. await b1.ctx.sessionPersistence.create(m)
  220. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  221. await b1.dispose()
  222. // Hand-write an interrupted turn (turn/start seq 6, no turn/end).
  223. const db = openDatabase(path, 'wal')
  224. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  225. .run(m.id, 'turn/start', JSON.stringify({ turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } }))
  226. db.close()
  227. const b2 = await backend(path)
  228. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  229. // turn 2's real turn/start (seq 6) is preserved + a synthetic turn/end (seq 7).
  230. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  231. expect(loaded.events.at(-1)!.type).toBe('turn/end')
  232. // load() is mutating: the synthetic turn/end MUST be on disk so the stored log
  233. // is balanced and the cursor is truthful (contract: load closes, not defers).
  234. const probe = openDatabase(path, 'wal')
  235. const stored = probe.prepare('SELECT seq, type FROM events WHERE session_id = ? ORDER BY seq').all(m.id) as { seq: number; type: string }[]
  236. probe.close()
  237. expect(stored.map(r => r.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  238. expect(stored.at(-1)!.type).toBe('turn/end')
  239. await b2.dispose()
  240. })
  241. it('all-tail load: a session whose only turn never closed is preserved and closed on load', async () => {
  242. const path = await freshDbPath()
  243. const m = meta('all-tail')
  244. const b1 = await backend(path)
  245. await b1.ctx.sessionPersistence.create(m)
  246. // A first turn that NEVER completed: turn/start + user/message, no turn/end.
  247. await b1.ctx.sessionPersistence.append(m.id, [
  248. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  249. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } } },
  250. ])
  251. await b1.dispose()
  252. // A fresh backend loads it: the interrupted (only) turn's real events are
  253. // preserved and closed with a synthetic turn/end {interrupted} — NOT
  254. // truncated. The session was materialized, so list() reports it present.
  255. const b2 = await backend(path)
  256. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  257. expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  258. expect(loaded.events.at(-1)!.type === 'turn/end' && loaded.events.at(-1)!.data).toMatchObject({ reason: { kind: 'interrupted' } })
  259. expect((await b2.ctx.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  260. await b2.dispose()
  261. })
  262. it('rejects opening a database whose schema version is not the current build (newer OR older)', async () => {
  263. const path = await freshDbPath()
  264. openDatabase(path, 'wal').close() // stamp user_version = SCHEMA_VERSION
  265. // Bump user_version past what this build supports.
  266. const dbNewer = openDatabase(path, 'wal')
  267. dbNewer.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`)
  268. dbNewer.close()
  269. expect(() => openDatabase(path, 'wal')).toThrow(/incompatible with this build/)
  270. // The immediately preceding layout lacks the required store identity and is
  271. // rejected rather than migrated (unreleased software, no backward-compat).
  272. const olderPath = await freshDbPath()
  273. openDatabase(olderPath, 'wal').close()
  274. const dbOlder = openDatabase(olderPath, 'wal')
  275. dbOlder.exec(`PRAGMA user_version = ${SCHEMA_VERSION - 1}`)
  276. dbOlder.close()
  277. expect(() => openDatabase(olderPath, 'wal')).toThrow(/incompatible with this build/)
  278. })
  279. it('rejects a sibling v3 database (the merge-collided version) rather than opening it against missing columns', async () => {
  280. // Version 3 identified two incompatible sibling layouts, so it is always rejected.
  281. const path = await freshDbPath()
  282. openDatabase(path, 'wal').close() // creates + stamps user_version = SCHEMA_VERSION
  283. const db = openDatabase(path, 'wal')
  284. db.exec('PRAGMA user_version = 3')
  285. db.close()
  286. expect(() => openDatabase(path, 'wal')).toThrow(/schema version 3, incompatible with this build/)
  287. })
  288. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  289. const path = await freshDbPath()
  290. const m = meta('corrupt-tail')
  291. const b1 = await backend(path)
  292. await b1.ctx.sessionPersistence.create(m)
  293. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  294. await b1.dispose()
  295. // A torn row after the last committed turn has invalid JSON. `scanRows` locates the boundary
  296. // from seq/type columns without parsing the tail, preserves the committed prefix, and load
  297. // deletes the row; invalid JSON inside the committed region would remain fatal.
  298. const db = openDatabase(path, 'wal')
  299. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  300. .run(m.id, 'turn/start', '{not valid json')
  301. db.close()
  302. const b2 = await backend(path)
  303. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  304. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  305. // load physically deleted the corrupt tail row, so a fresh append continues.
  306. await b2.ctx.sessionPersistence.append(m.id, [
  307. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  308. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  309. ])
  310. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  311. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  312. await b2.dispose()
  313. })
  314. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  315. const ctx = new Context()
  316. await ctx.plugin(SessionStore)
  317. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  318. const m = meta('rollback')
  319. await ctx.sessionPersistence.create(m)
  320. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  321. // A batch that re-states an already-stored seq must be rejected and leave
  322. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  323. // inside the transaction → ROLLBACK).
  324. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  325. const loaded = await ctx.sessionPersistence.load(m.id)
  326. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  327. await fiber.dispose()
  328. })
  329. it('persists across separate backend instances over the same file', async () => {
  330. const path = await freshDbPath()
  331. const m = meta('persist', '/proj')
  332. const ctx1 = new Context()
  333. await ctx1.plugin(SessionStore)
  334. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  335. await ctx1.sessionPersistence.create(m)
  336. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  337. await fiber1.dispose()
  338. const ctx2 = new Context()
  339. await ctx2.plugin(SessionStore)
  340. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  341. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  342. const loaded = await ctx2.sessionPersistence.load(m.id)
  343. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj' })
  344. expect(loaded.events).toEqual(oneTurnLog())
  345. await fiber2.dispose()
  346. })
  347. it('source-qualifies revisions across stores while preserving same-file reopen identity', async () => {
  348. const pathA = await freshDbPath()
  349. const pathB = await freshDbPath()
  350. const m = meta('revision-source')
  351. const a = await backend(pathA)
  352. await a.ctx.sessionPersistence.create(m)
  353. await a.ctx.sessionPersistence.append(m.id, oneTurnLog())
  354. const revisionA = (await a.ctx.sessionPersistence.listSnapshots())[0]?.revision
  355. await a.dispose()
  356. const probeA = openDatabase(pathA, 'wal')
  357. const storeIdA = (probeA.prepare(
  358. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  359. ).get() as { store_id: string }).store_id
  360. probeA.close()
  361. const aliasA = `${pathA}.alias`
  362. await symlink(pathA, aliasA)
  363. const reopenedA = await backend(aliasA)
  364. expect((await reopenedA.ctx.sessionPersistence.listSnapshots())[0]?.revision).toBe(revisionA)
  365. await reopenedA.dispose()
  366. const b = await backend(pathB)
  367. await b.ctx.sessionPersistence.create(m)
  368. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  369. const revisionB = (await b.ctx.sessionPersistence.listSnapshots())[0]?.revision
  370. const probeB = openDatabase(pathB, 'wal')
  371. const storeIdB = (probeB.prepare(
  372. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  373. ).get() as { store_id: string }).store_id
  374. probeB.close()
  375. expect(storeIdB).not.toBe(storeIdA)
  376. expect(revisionB).not.toBe(revisionA)
  377. expect(String(revisionA)).toMatch(/:revision:1$/)
  378. expect(String(revisionB)).toMatch(/:revision:1$/)
  379. await b.dispose()
  380. })
  381. it('changes revisions when a deleted session id is materialized again in the same database', async () => {
  382. const path = await freshDbPath()
  383. const m = meta('recreated-revision')
  384. const first = await backend(path)
  385. await first.ctx.sessionPersistence.create(m)
  386. await first.ctx.sessionPersistence.append(m.id, oneTurnLog())
  387. const before = (await first.ctx.sessionPersistence.listSnapshots())[0]?.revision
  388. await first.dispose()
  389. const cleanup = openDatabase(path, 'wal')
  390. cleanup.prepare('DELETE FROM sessions WHERE id = ?').run(m.id)
  391. cleanup.close()
  392. const second = await backend(path)
  393. await second.ctx.sessionPersistence.create(m)
  394. await second.ctx.sessionPersistence.append(m.id, oneTurnLog())
  395. const after = (await second.ctx.sessionPersistence.listSnapshots())[0]?.revision
  396. expect(after).not.toBe(before)
  397. expect(String(before)).toMatch(/:revision:1$/)
  398. expect(String(after)).toMatch(/:revision:1$/)
  399. await second.dispose()
  400. })
  401. it('exposes the schema version constant', () => {
  402. expect(SCHEMA_VERSION).toBe(9)
  403. })
  404. it('keeps the revision stable for an empty repair hook', async () => {
  405. const b = await backend()
  406. const m = meta('empty-repair')
  407. await b.ctx.sessionPersistence.create(m)
  408. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  409. const before = await b.ctx.sessionPersistence.listSnapshots()
  410. await (b.ctx.sessionPersistence as SessionPersistenceSqlite).commitRepair(m, undefined, [])
  411. expect(await b.ctx.sessionPersistence.listSnapshots()).toEqual(before)
  412. await b.dispose()
  413. })
  414. })
  415. describe('SessionPersistenceSqlite: edge cases', () => {
  416. it('claims, rejects, reclaims, inspects, and releases SQLite live leases', async () => {
  417. const path = await freshDbPath()
  418. const b = await backend(path)
  419. await b.ctx.sessionPersistence.list()
  420. const concrete = b.ctx.sessionPersistence as SessionPersistenceSqlite
  421. const owner = sessionLiveOwner()
  422. const db = openDatabase(path, 'wal')
  423. const insert = db.prepare('INSERT INTO live_session_leases (session_id, pid, nonce) VALUES (?, ?, ?)')
  424. insert.run('occupied-lease', process.pid, 'another-owner')
  425. insert.run('stale-claim', 2_147_483_647, 'dead-owner')
  426. insert.run('stale-inspect', 2_147_483_647, 'dead-owner')
  427. insert.run('owned-inspect', owner.pid, owner.nonce)
  428. db.close()
  429. await expect(concrete.acquireLive(SessionId('occupied-lease'), owner))
  430. .rejects.toThrow('occupied by another live process')
  431. const claim = await concrete.acquireLive(SessionId('stale-claim'), owner)
  432. expect(await concrete.inspectLive(SessionId('owned-inspect'), owner)).toBe(true)
  433. expect(await concrete.inspectLive(SessionId('stale-inspect'), owner)).toBe(false)
  434. expect(await concrete.inspectLive(SessionId('missing-inspect'), owner)).toBe(false)
  435. await claim()
  436. await b.dispose()
  437. const memory = new Context()
  438. await memory.plugin(SessionStore)
  439. await memory.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  440. const memoryClaim = await memory.sessionPersistence.claimLive(SessionId('memory-live'))
  441. expect(await memory.sessionPersistence.isLive(SessionId('memory-live'))).toBe(true)
  442. await memoryClaim.release()
  443. await memory.fiber.dispose()
  444. })
  445. it('rejects and closes a current-schema database with an invalid store identity', async () => {
  446. const path = await freshDbPath()
  447. const db = openDatabase(path, 'wal')
  448. db.exec("UPDATE persistence_state SET store_id = '' WHERE singleton = 1")
  449. db.close()
  450. const b = await backend(path)
  451. await expect(b.ctx.sessionPersistence.listSnapshots()).rejects.toThrow(/no valid store identity/)
  452. await expect(b.dispose()).resolves.toBeUndefined()
  453. })
  454. it('creates a new database and WAL sidecars with owner-only modes without changing its parent mode', async () => {
  455. if (process.platform === 'win32') return
  456. const path = await freshDbPath()
  457. const dir = dirname(path)
  458. await chmod(dir, 0o755)
  459. const b = await backend(path)
  460. await b.ctx.sessionPersistence.list()
  461. expect((await stat(dir)).mode & 0o777).toBe(0o755)
  462. expect((await stat(path)).mode & 0o777).toBe(0o600)
  463. expect((await stat(`${path}-wal`)).mode & 0o777).toBe(0o600)
  464. expect((await stat(`${path}-shm`)).mode & 0o777).toBe(0o600)
  465. await b.dispose()
  466. })
  467. it('creates a persistent rollback journal with owner-only mode', async () => {
  468. if (process.platform === 'win32') return
  469. const path = await freshDbPath()
  470. const ctx = new Context()
  471. await ctx.plugin(SessionStore)
  472. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path, journalMode: 'persist' })
  473. const m = meta('persist-permissions')
  474. await ctx.sessionPersistence.create(m)
  475. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  476. expect((await stat(path)).mode & 0o777).toBe(0o600)
  477. expect((await stat(`${path}-journal`)).mode & 0o777).toBe(0o600)
  478. await fiber.dispose()
  479. })
  480. it('preserves the mode of an existing database file', async () => {
  481. if (process.platform === 'win32') return
  482. const path = await freshDbPath()
  483. await writeFile(path, '', { mode: 0o644 })
  484. await chmod(path, 0o644)
  485. const ctx = new Context()
  486. await ctx.plugin(SessionStore)
  487. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path, journalMode: 'delete' })
  488. await ctx.sessionPersistence.list()
  489. expect((await stat(path)).mode & 0o777).toBe(0o644)
  490. await fiber.dispose()
  491. })
  492. it('surfaces an invalid database path during pre-creation', async () => {
  493. const path = await freshDbPath()
  494. const b = await backend(`${path}\0`)
  495. await expect(b.ctx.sessionPersistence.list()).rejects.toMatchObject({ code: 'ERR_INVALID_ARG_VALUE' })
  496. await b.dispose()
  497. })
  498. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  499. const path = await freshDbPath()
  500. const m = meta('rollback-insert')
  501. const b1 = await backend(path)
  502. await b1.ctx.sessionPersistence.create(m)
  503. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  504. // A SECOND backend over the same file loads the session first, so it adopts
  505. // cursor 6 (the committed length) into its OWN in-memory state.
  506. const b2 = await backend(path)
  507. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  508. const turn2: SessionEvent[] = [
  509. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  510. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  511. ]
  512. // b1 commits seq 6..7 first.
  513. await b1.ctx.sessionPersistence.append(m.id, turn2)
  514. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  515. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  516. // mid-transaction → ROLLBACK + rethrow.
  517. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  518. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  519. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  520. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  521. await b1.dispose()
  522. await b2.dispose()
  523. })
  524. it('journalMode config reaches the database (default wal, rollback modes selectable)', async () => {
  525. // :memory: databases always report journal_mode=memory, so probe file DBs.
  526. const walPath = await freshDbPath()
  527. const bWal = await backend(walPath)
  528. await bWal.ctx.sessionPersistence.create(meta('jm-wal'))
  529. const probe = openDatabase(walPath, 'wal')
  530. expect((probe.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('wal')
  531. probe.close()
  532. await bWal.dispose()
  533. const deletePath = await freshDbPath()
  534. const ctx = new Context()
  535. await ctx.plugin(SessionStore)
  536. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: deletePath, journalMode: 'delete' })
  537. await ctx.sessionPersistence.create(meta('jm-delete'))
  538. // Probe through a second connection: journal_mode=delete is a per-database
  539. // property only insofar as no WAL files exist — assert the world, not the
  540. // backend's self-report (no -wal sidecar after writes in delete mode).
  541. const db = openDatabase(deletePath, 'delete')
  542. expect((db.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('delete')
  543. db.close()
  544. expect(existsSync(`${deletePath}-wal`)).toBe(false)
  545. await fiber.dispose()
  546. })
  547. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  548. const path = await freshDbPath()
  549. // Instance 1 materializes a session and disposes.
  550. const b1 = await backend(path)
  551. const s1 = b1.ctx.sessions.create(SessionId('hmr-collide'))
  552. appendLog(s1, oneTurnLog())
  553. await b1.ctx.sessions.flush(s1)
  554. await b1.dispose()
  555. // A fresh context with an UNRELATED live session reusing the id meets a
  556. // materialized row that is NOT a prefix of its events → reject.
  557. const ctx = new Context()
  558. await ctx.plugin(SessionStore)
  559. let session!: Session
  560. await ctx.plugin(Object.assign((inner: Context) => {
  561. session = inner.sessions.create(SessionId('hmr-collide'))
  562. }, { inject: ['sessions'] }))
  563. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  564. await ctx.plugin(SessionPersistenceSqlite, { path })
  565. await expectFlushError(ctx.sessions.flush(session), /id collision/)
  566. await ctx.fiber.dispose()
  567. })
  568. })
  569. describe('surface field round-trip', () => {
  570. it('rowToEvent parses surface fields from EventRow columns', () => {
  571. const row: EventRow = {
  572. seq: 0, type: 'assistant/message', time: 1,
  573. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  574. source_event_seqs: JSON.stringify([3, 5]),
  575. surface_op: JSON.stringify('append'),
  576. }
  577. const event = rowToEvent(row)
  578. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([3, 5])
  579. expect((event as SurfaceEvent).surfaceOp).toBe('append')
  580. })
  581. it('rowToEvent handles replace surfaceOp object', () => {
  582. const row: EventRow = {
  583. seq: 0, type: 'assistant/message', time: 1,
  584. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  585. source_event_seqs: JSON.stringify([0, 1]),
  586. surface_op: JSON.stringify({ op: 'replace', start: 0, end: 1 }),
  587. }
  588. const event = rowToEvent(row)
  589. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  590. expect((event as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 1 })
  591. })
  592. it('scanRows with surface columns reconstructs events with surface fields', () => {
  593. const rows: EventRow[] = [
  594. { seq: 0, type: 'user/message', time: 1,
  595. data: JSON.stringify({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }),
  596. source_event_seqs: null, surface_op: '{"op":"replace","start":0,"end":0}' },
  597. { seq: 1, type: 'turn/end', time: 2,
  598. data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }),
  599. source_event_seqs: null, surface_op: null },
  600. ]
  601. const { preserved } = scanRows(rows)
  602. expect(preserved).toHaveLength(2)
  603. expect((preserved[0]! as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  604. expect((preserved[0]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  605. expect((preserved[1] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  606. })
  607. it('append and load round-trips surface fields through SQLite', async () => {
  608. const ctx = new Context()
  609. await ctx.plugin(SessionStore)
  610. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  611. const session = ctx.sessions.create(SessionId('roundtrip-surface'))
  612. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  613. session.append('step/start', { turn: 1, step: 1 })
  614. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  615. session.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [] }, { surfaceOp: 'append', sourceEventSeqs: [2] })
  616. session.append('step/end', { turn: 1, step: 1 })
  617. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  618. await ctx.sessions.flush(session)
  619. const loaded = await ctx.sessionPersistence.load(SessionId('roundtrip-surface'))
  620. expect(loaded.events).toHaveLength(6)
  621. const um = loaded.events[2]!
  622. expect((um as SurfaceEvent).surfaceOp).toBe('append')
  623. expect((um as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  624. const am = loaded.events[3]!
  625. expect((am as SurfaceEvent).surfaceOp).toBe('append')
  626. expect((am as SurfaceEvent).sourceEventSeqs).toEqual([2])
  627. await fiber.dispose()
  628. })
  629. it('persists events with surfaceOp but no sourceEventSeqs (covers null branch in surfaceBindings)', async () => {
  630. const ctx = new Context()
  631. await ctx.plugin(SessionStore)
  632. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  633. const session = ctx.sessions.create(SessionId('surface-noseq'))
  634. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  635. session.append('steering/message', { turn: 1, content: [], source: { kind: 'user' } }, { surfaceOp: 'append' })
  636. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  637. await ctx.sessions.flush(session)
  638. const loaded = await ctx.sessionPersistence.load(SessionId('surface-noseq'))
  639. expect((loaded.events[1]! as SurfaceEvent).surfaceOp).toBe('append')
  640. expect((loaded.events[1]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  641. await fiber.dispose()
  642. })
  643. })