sqlite.spec.ts 40 KB

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