sqlite.spec.ts 33 KB

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