sqlite.spec.ts 38 KB

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