sqlite.spec.ts 40 KB

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