sqlite.spec.ts 40 KB

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