sqlite.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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 { DatabaseSync } from 'node:sqlite'
  8. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  9. import type { Session, SessionEvent, SurfaceEvent, SurfaceEventType } from '@deepseek-ai/dsh-session'
  10. import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
  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 nonempty unversioned database before stamping or changing journal mode', async () => {
  280. const path = await freshDbPath()
  281. const legacy = new DatabaseSync(path)
  282. legacy.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY)')
  283. legacy.close()
  284. expect(() => openDatabase(path, 'wal')).toThrow(/nonempty unversioned schema/)
  285. const unchanged = new DatabaseSync(path)
  286. expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 })
  287. expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  288. expect(unchanged.prepare(
  289. "SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'sessions'",
  290. ).get()).toEqual({ name: 'sessions' })
  291. unchanged.close()
  292. })
  293. it('rejects a sibling v3 database (the merge-collided version) rather than opening it against missing columns', async () => {
  294. // Version 3 identified two incompatible sibling layouts, so it is always rejected.
  295. const path = await freshDbPath()
  296. openDatabase(path, 'wal').close() // creates + stamps user_version = SCHEMA_VERSION
  297. const db = openDatabase(path, 'wal')
  298. db.exec('PRAGMA user_version = 3')
  299. db.close()
  300. expect(() => openDatabase(path, 'wal')).toThrow(/schema version 3, incompatible with this build/)
  301. })
  302. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  303. const path = await freshDbPath()
  304. const m = meta('corrupt-tail')
  305. const b1 = await backend(path)
  306. await b1.ctx.sessionPersistence.create(m)
  307. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  308. await b1.dispose()
  309. // A torn row after the last committed turn has invalid JSON. `scanRows` locates the boundary
  310. // from seq/type columns without parsing the tail, preserves the committed prefix, and load
  311. // deletes the row; invalid JSON inside the committed region would remain fatal.
  312. const db = openDatabase(path, 'wal')
  313. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  314. .run(m.id, 'turn/start', '{not valid json')
  315. db.close()
  316. const b2 = await backend(path)
  317. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  318. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  319. // load physically deleted the corrupt tail row, so a fresh append continues.
  320. await b2.ctx.sessionPersistence.append(m.id, [
  321. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  322. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  323. ])
  324. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  325. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  326. await b2.dispose()
  327. })
  328. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  329. const ctx = new Context()
  330. await ctx.plugin(SessionStore)
  331. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  332. const m = meta('rollback')
  333. await ctx.sessionPersistence.create(m)
  334. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  335. // A batch that re-states an already-stored seq must be rejected and leave
  336. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  337. // inside the transaction → ROLLBACK).
  338. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  339. const loaded = await ctx.sessionPersistence.load(m.id)
  340. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  341. await fiber.dispose()
  342. })
  343. it('persists across separate backend instances over the same file', async () => {
  344. const path = await freshDbPath()
  345. const m = meta('persist', '/proj')
  346. const ctx1 = new Context()
  347. await ctx1.plugin(SessionStore)
  348. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  349. await ctx1.sessionPersistence.create(m)
  350. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  351. await fiber1.dispose()
  352. const ctx2 = new Context()
  353. await ctx2.plugin(SessionStore)
  354. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  355. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  356. const loaded = await ctx2.sessionPersistence.load(m.id)
  357. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj' })
  358. expect(loaded.events).toEqual(oneTurnLog())
  359. await fiber2.dispose()
  360. })
  361. it('source-qualifies revisions across stores while preserving same-file reopen identity', async () => {
  362. const pathA = await freshDbPath()
  363. const pathB = await freshDbPath()
  364. const m = meta('revision-source')
  365. const a = await backend(pathA)
  366. await a.ctx.sessionPersistence.create(m)
  367. await a.ctx.sessionPersistence.append(m.id, oneTurnLog())
  368. const revisionA = (await a.ctx.sessionPersistence.listSnapshots())[0]?.revision
  369. await a.dispose()
  370. const probeA = openDatabase(pathA, 'wal')
  371. const storeIdA = (probeA.prepare(
  372. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  373. ).get() as { store_id: string }).store_id
  374. probeA.close()
  375. const aliasA = `${pathA}.alias`
  376. await symlink(pathA, aliasA)
  377. const reopenedA = await backend(aliasA)
  378. expect((await reopenedA.ctx.sessionPersistence.listSnapshots())[0]?.revision).toBe(revisionA)
  379. await reopenedA.dispose()
  380. const b = await backend(pathB)
  381. await b.ctx.sessionPersistence.create(m)
  382. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  383. const revisionB = (await b.ctx.sessionPersistence.listSnapshots())[0]?.revision
  384. const probeB = openDatabase(pathB, 'wal')
  385. const storeIdB = (probeB.prepare(
  386. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  387. ).get() as { store_id: string }).store_id
  388. probeB.close()
  389. expect(storeIdB).not.toBe(storeIdA)
  390. expect(revisionB).not.toBe(revisionA)
  391. expect(String(revisionA)).toMatch(/:revision:1$/)
  392. expect(String(revisionB)).toMatch(/:revision:1$/)
  393. await b.dispose()
  394. })
  395. it('changes revisions when a deleted session id is materialized again in the same database', async () => {
  396. const path = await freshDbPath()
  397. const m = meta('recreated-revision')
  398. const first = await backend(path)
  399. await first.ctx.sessionPersistence.create(m)
  400. await first.ctx.sessionPersistence.append(m.id, oneTurnLog())
  401. const before = (await first.ctx.sessionPersistence.listSnapshots())[0]?.revision
  402. await first.dispose()
  403. const cleanup = openDatabase(path, 'wal')
  404. cleanup.prepare('DELETE FROM sessions WHERE id = ?').run(m.id)
  405. cleanup.close()
  406. const second = await backend(path)
  407. await second.ctx.sessionPersistence.create(m)
  408. await second.ctx.sessionPersistence.append(m.id, oneTurnLog())
  409. const after = (await second.ctx.sessionPersistence.listSnapshots())[0]?.revision
  410. expect(after).not.toBe(before)
  411. expect(String(before)).toMatch(/:revision:1$/)
  412. expect(String(after)).toMatch(/:revision:1$/)
  413. await second.dispose()
  414. })
  415. it('exposes the schema version constant', () => {
  416. expect(SCHEMA_VERSION).toBe(9)
  417. })
  418. it('keeps the revision stable for an empty repair hook', async () => {
  419. const b = await backend()
  420. const m = meta('empty-repair')
  421. await b.ctx.sessionPersistence.create(m)
  422. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  423. const before = await b.ctx.sessionPersistence.listSnapshots()
  424. await (b.ctx.sessionPersistence as SessionPersistenceSqlite).commitRepair(m, undefined, [])
  425. expect(await b.ctx.sessionPersistence.listSnapshots()).toEqual(before)
  426. await b.dispose()
  427. })
  428. })
  429. describe('SessionPersistenceSqlite: edge cases', () => {
  430. it('rejects and closes a current-schema database with an invalid store identity', async () => {
  431. const path = await freshDbPath()
  432. const db = openDatabase(path, 'wal')
  433. db.exec("UPDATE persistence_state SET store_id = '' WHERE singleton = 1")
  434. db.close()
  435. const b = await backend(path)
  436. await expect(b.ctx.sessionPersistence.listSnapshots()).rejects.toThrow(/no valid store identity/)
  437. await expect(b.dispose()).resolves.toBeUndefined()
  438. })
  439. it('creates a new database and WAL sidecars with owner-only modes without changing its parent mode', async () => {
  440. if (process.platform === 'win32') return
  441. const path = await freshDbPath()
  442. const dir = dirname(path)
  443. await chmod(dir, 0o755)
  444. const b = await backend(path)
  445. await b.ctx.sessionPersistence.list()
  446. expect((await stat(dir)).mode & 0o777).toBe(0o755)
  447. expect((await stat(path)).mode & 0o777).toBe(0o600)
  448. expect((await stat(`${path}-wal`)).mode & 0o777).toBe(0o600)
  449. expect((await stat(`${path}-shm`)).mode & 0o777).toBe(0o600)
  450. await b.dispose()
  451. })
  452. it('creates a persistent rollback journal with owner-only mode', async () => {
  453. if (process.platform === 'win32') return
  454. const path = await freshDbPath()
  455. const ctx = new Context()
  456. await ctx.plugin(SessionStore)
  457. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path, journalMode: 'persist' })
  458. const m = meta('persist-permissions')
  459. await ctx.sessionPersistence.create(m)
  460. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  461. expect((await stat(path)).mode & 0o777).toBe(0o600)
  462. expect((await stat(`${path}-journal`)).mode & 0o777).toBe(0o600)
  463. await fiber.dispose()
  464. })
  465. it('preserves the mode of an existing database file', async () => {
  466. if (process.platform === 'win32') return
  467. const path = await freshDbPath()
  468. await writeFile(path, '', { mode: 0o644 })
  469. await chmod(path, 0o644)
  470. const ctx = new Context()
  471. await ctx.plugin(SessionStore)
  472. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path, journalMode: 'delete' })
  473. await ctx.sessionPersistence.list()
  474. expect((await stat(path)).mode & 0o777).toBe(0o644)
  475. await fiber.dispose()
  476. })
  477. it('surfaces an invalid database path during pre-creation', async () => {
  478. const path = await freshDbPath()
  479. const b = await backend(`${path}\0`)
  480. await expect(b.ctx.sessionPersistence.list()).rejects.toMatchObject({ code: 'ERR_INVALID_ARG_VALUE' })
  481. await b.dispose()
  482. })
  483. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  484. const path = await freshDbPath()
  485. const m = meta('rollback-insert')
  486. const b1 = await backend(path)
  487. await b1.ctx.sessionPersistence.create(m)
  488. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  489. // A SECOND backend over the same file loads the session first, so it adopts
  490. // cursor 6 (the committed length) into its OWN in-memory state.
  491. const b2 = await backend(path)
  492. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  493. const turn2: SessionEvent[] = [
  494. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  495. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  496. ]
  497. // b1 commits seq 6..7 first.
  498. await b1.ctx.sessionPersistence.append(m.id, turn2)
  499. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  500. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  501. // mid-transaction → ROLLBACK + rethrow.
  502. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  503. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  504. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  505. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  506. await b1.dispose()
  507. await b2.dispose()
  508. })
  509. it('journalMode config reaches the database (default wal, rollback modes selectable)', async () => {
  510. // :memory: databases always report journal_mode=memory, so probe file DBs.
  511. const walPath = await freshDbPath()
  512. const bWal = await backend(walPath)
  513. await bWal.ctx.sessionPersistence.create(meta('jm-wal'))
  514. const probe = openDatabase(walPath, 'wal')
  515. expect((probe.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('wal')
  516. probe.close()
  517. await bWal.dispose()
  518. const deletePath = await freshDbPath()
  519. const ctx = new Context()
  520. await ctx.plugin(SessionStore)
  521. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: deletePath, journalMode: 'delete' })
  522. await ctx.sessionPersistence.create(meta('jm-delete'))
  523. // Probe through a second connection: journal_mode=delete is a per-database
  524. // property only insofar as no WAL files exist — assert the world, not the
  525. // backend's self-report (no -wal sidecar after writes in delete mode).
  526. const db = openDatabase(deletePath, 'delete')
  527. expect((db.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('delete')
  528. db.close()
  529. expect(existsSync(`${deletePath}-wal`)).toBe(false)
  530. await fiber.dispose()
  531. })
  532. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  533. const path = await freshDbPath()
  534. // Instance 1 materializes a session and disposes.
  535. const b1 = await backend(path)
  536. const s1 = b1.ctx.sessions.create(SessionId('hmr-collide'))
  537. appendLog(s1, oneTurnLog())
  538. await b1.ctx.sessions.flush(s1)
  539. await b1.dispose()
  540. // A fresh context with an UNRELATED live session reusing the id meets a
  541. // materialized row that is NOT a prefix of its events → reject.
  542. const ctx = new Context()
  543. await ctx.plugin(SessionStore)
  544. let session!: Session
  545. await ctx.plugin(Object.assign((inner: Context) => {
  546. session = inner.sessions.create(SessionId('hmr-collide'))
  547. }, { inject: ['sessions'] }))
  548. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  549. await ctx.plugin(SessionPersistenceSqlite, { path })
  550. await expectFlushError(ctx.sessions.flush(session), /id collision/)
  551. await ctx.fiber.dispose()
  552. })
  553. })
  554. describe('surface field round-trip', () => {
  555. it('rowToEvent parses surface fields from EventRow columns', () => {
  556. const row: EventRow = {
  557. seq: 0, type: 'assistant/message', time: 1,
  558. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  559. source_event_seqs: JSON.stringify([3, 5]),
  560. surface_op: JSON.stringify('append'),
  561. }
  562. const event = rowToEvent(row)
  563. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([3, 5])
  564. expect((event as SurfaceEvent).surfaceOp).toBe('append')
  565. })
  566. it('rowToEvent handles replace surfaceOp object', () => {
  567. const row: EventRow = {
  568. seq: 0, type: 'assistant/message', time: 1,
  569. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  570. source_event_seqs: JSON.stringify([0, 1]),
  571. surface_op: JSON.stringify({ op: 'replace', start: 0, end: 1 }),
  572. }
  573. const event = rowToEvent(row)
  574. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  575. expect((event as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 1 })
  576. })
  577. it('scanRows with surface columns reconstructs events with surface fields', () => {
  578. const rows: EventRow[] = [
  579. { seq: 0, type: 'user/message', time: 1,
  580. data: JSON.stringify({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }),
  581. source_event_seqs: null, surface_op: '{"op":"replace","start":0,"end":0}' },
  582. { seq: 1, type: 'turn/end', time: 2,
  583. data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }),
  584. source_event_seqs: null, surface_op: null },
  585. ]
  586. const { preserved } = scanRows(rows)
  587. expect(preserved).toHaveLength(2)
  588. expect((preserved[0]! as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  589. expect((preserved[0]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  590. expect((preserved[1] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  591. })
  592. it('append and load round-trips surface fields through SQLite', async () => {
  593. const ctx = new Context()
  594. await ctx.plugin(SessionStore)
  595. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  596. const session = ctx.sessions.create(SessionId('roundtrip-surface'))
  597. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  598. session.append('step/start', { turn: 1, step: 1 })
  599. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  600. session.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [] }, { surfaceOp: 'append', sourceEventSeqs: [2] })
  601. session.append('step/end', { turn: 1, step: 1 })
  602. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  603. await ctx.sessions.flush(session)
  604. const loaded = await ctx.sessionPersistence.load(SessionId('roundtrip-surface'))
  605. expect(loaded.events).toHaveLength(6)
  606. const um = loaded.events[2]!
  607. expect((um as SurfaceEvent).surfaceOp).toBe('append')
  608. expect((um as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  609. const am = loaded.events[3]!
  610. expect((am as SurfaceEvent).surfaceOp).toBe('append')
  611. expect((am as SurfaceEvent).sourceEventSeqs).toEqual([2])
  612. await fiber.dispose()
  613. })
  614. it('persists events with surfaceOp but no sourceEventSeqs (covers null branch in surfaceBindings)', async () => {
  615. const ctx = new Context()
  616. await ctx.plugin(SessionStore)
  617. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  618. const session = ctx.sessions.create(SessionId('surface-noseq'))
  619. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  620. session.append('steering/message', { turn: 1, content: [], source: { kind: 'user' } }, { surfaceOp: 'append' })
  621. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  622. await ctx.sessions.flush(session)
  623. const loaded = await ctx.sessionPersistence.load(SessionId('surface-noseq'))
  624. expect((loaded.events[1]! as SurfaceEvent).surfaceOp).toBe('append')
  625. expect((loaded.events[1]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  626. await fiber.dispose()
  627. })
  628. })