sqlite.spec.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { existsSync } from 'node:fs'
  4. import { mkdtemp, rm } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { Session, SessionEvent, SurfaceEvent, SurfaceEventType } from '@deepseek-ai/dsh-session'
  9. import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
  10. import { openDatabase, rowToEvent, scanRows, type EventRow } from '../src/schema.ts'
  11. import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts'
  12. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  13. const dirs: string[] = []
  14. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  15. async function expectParallelFlushError(promise: Promise<unknown>, message: RegExp): Promise<void> {
  16. try {
  17. await promise
  18. } catch (error) {
  19. expect(error).toBeInstanceOf(AggregateError)
  20. const [cause] = (error as AggregateError).errors as unknown[]
  21. expect(cause).toBeInstanceOf(Error)
  22. expect((cause as Error).message).toMatch(message)
  23. return
  24. }
  25. throw new Error('expected parallel flush to reject')
  26. }
  27. async function freshDbPath(): Promise<string> {
  28. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-'))
  29. dirs.push(dir)
  30. return join(dir, 'sessions.db')
  31. }
  32. /** A context with the session store + SQLite backend, plus a teardown. */
  33. async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
  34. const ctx = new Context()
  35. await ctx.plugin(SessionStore)
  36. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  37. return { ctx, dispose: () => fiber.dispose() }
  38. }
  39. // Run the same backend-agnostic contract as JSONL to pin identical semantics.
  40. runPersistenceContract('sqlite', async () => {
  41. const ctx = new Context()
  42. await ctx.plugin(SessionStore)
  43. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  44. return {
  45. persistence: ctx.sessionPersistence,
  46. dispose: async () => { await fiber.dispose() },
  47. }
  48. })
  49. // A file-backed database lets two mounts share rows across reload. `corruptTail` inserts invalid
  50. // JSON past the committed seq, exercising coordinator repair against real database rows.
  51. runCoordinatorContract('sqlite', async (): Promise<CoordinatorFixture> => {
  52. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-coord-'))
  53. const path = join(dir, 'sessions.db')
  54. return {
  55. mount: async ctx => ctx.plugin(SessionPersistenceSqlite, { path }),
  56. corruptTail: async (id) => {
  57. // A row past the committed region whose `data` does not parse: scanRows
  58. // bounds the preserved prefix at it and returns its seq as tornFrom, which
  59. // the backend surfaces to the coordinator as the tornMarker to delete from.
  60. const db = openDatabase(path, 'wal')
  61. const next = (db.prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM events WHERE session_id = ?')
  62. .get(id) as { n: number }).n
  63. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  64. .run(id, next, 'assistant/chunk', 99, '{not valid json')
  65. db.close()
  66. },
  67. cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
  68. }
  69. })
  70. describe('scanRows', () => {
  71. // scanRows works off EventRows (data is a JSON string column); build them from SessionEvents
  72. // so the unit tests read in terms of the event vocabulary. Surface metadata is serialized to
  73. // its nullable columns so the conversion remains faithful.
  74. const rows = (events: SessionEvent[]): EventRow[] =>
  75. events.map((e) => {
  76. const se = e as SessionEvent<SurfaceEventType>
  77. return {
  78. seq: e.seq, type: e.type, time: e.time, data: JSON.stringify(e.data),
  79. source_event_seqs: se.sourceEventSeqs !== undefined ? JSON.stringify(se.sourceEventSeqs) : null,
  80. surface_op: se.surfaceOp !== undefined ? JSON.stringify(se.surfaceOp) : null,
  81. }
  82. })
  83. it('preserves the full log when it ends exactly on a turn/end (no torn tail)', () => {
  84. const { preserved, tornFrom } = scanRows(rows(oneTurnLog()))
  85. expect(preserved).toEqual(oneTurnLog())
  86. expect(tornFrom).toBeUndefined()
  87. })
  88. it('PRESERVES the real events of an interrupted turn after the last turn/end', () => {
  89. // turn 1 committed (0..5) + a crashed turn 2 (turn/start 6, step/start 7, no
  90. // close): all 8 rows are intact, so the whole prefix is preserved and there
  91. // is no torn fragment to delete. (load() then synthesizes the closers.)
  92. const withOpenTurn: SessionEvent[] = [
  93. ...oneTurnLog(),
  94. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  95. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  96. ]
  97. const { preserved, tornFrom } = scanRows(rows(withOpenTurn))
  98. expect(preserved.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  99. expect(tornFrom).toBeUndefined()
  100. })
  101. it('preserves the contiguous prefix and flags a torn tail at a seq gap', () => {
  102. // A gap after seq 0 (no committed turn/end): seq 0 is the preserved
  103. // interrupted-turn event; the gap bounds it and marks the torn fragment.
  104. const gapped: SessionEvent[] = [
  105. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  106. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  107. ]
  108. const { preserved, tornFrom } = scanRows(rows(gapped))
  109. expect(preserved.map(e => e.seq)).toEqual([0])
  110. expect(tornFrom).toBe(1)
  111. })
  112. it('an empty log preserves nothing and has no torn tail', () => {
  113. expect(scanRows([])).toEqual({ preserved: [] })
  114. })
  115. it('throws on a seq gap inside the committed region (before the last turn/end)', () => {
  116. const gapped: SessionEvent[] = [
  117. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  118. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  119. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  120. ]
  121. expect(() => scanRows(rows(gapped))).toThrow(/seq gap in committed region/)
  122. })
  123. it('throws on an unparsable row inside the committed region', () => {
  124. const withCorruptCommitted: EventRow[] = [
  125. { seq: 0, type: 'turn/start', time: 1, data: '{not json', source_event_seqs: null, surface_op: null }, // corrupt, sits before a turn/end
  126. { seq: 1, type: 'turn/end', time: 2, data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }), source_event_seqs: null, surface_op: null },
  127. ]
  128. expect(() => scanRows(withCorruptCommitted)).toThrow(/unparsable committed event/)
  129. })
  130. it('tolerates an unparsable torn-tail row after the last turn/end', () => {
  131. const withCorruptTail: EventRow[] = [
  132. ...rows(oneTurnLog()),
  133. { seq: 6, type: 'turn/start', time: 7, data: '{not json', source_event_seqs: null, surface_op: null }, // torn fragment, no committed turn/end after
  134. ]
  135. const { preserved, tornFrom } = scanRows(withCorruptTail)
  136. expect(preserved).toEqual(oneTurnLog())
  137. expect(tornFrom).toBe(6)
  138. })
  139. })
  140. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  141. it('rejects a stored v0 log containing a legacy request/header-delta event', async () => {
  142. const path = await freshDbPath()
  143. const m = meta('legacy-header-delta', '/legacy')
  144. const db = openDatabase(path, 'wal')
  145. db.prepare('INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length) VALUES (?, ?, ?, ?, NULL, NULL)')
  146. .run(m.id, m.version, m.createdAt, m.cwd ?? null)
  147. const insert = db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  148. insert.run(m.id, 0, 'turn/start', 1, JSON.stringify({ turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }))
  149. insert.run(m.id, 1, 'request/header-delta', 2, JSON.stringify({ config: { model: 'legacy' } }))
  150. insert.run(m.id, 2, 'turn/end', 3, JSON.stringify({ turn: 1, reason: { kind: 'completed' } }))
  151. db.close()
  152. const mounted = await backend(path)
  153. await expect(mounted.ctx.sessionPersistence.load(m.id)).rejects.toThrow(/unsupported legacy request\/header-delta event at seq 1/)
  154. await mounted.dispose()
  155. })
  156. it('rejects a stored v0 full header carrying the legacy fallback reason', async () => {
  157. const path = await freshDbPath()
  158. const m = meta('legacy-header-fallback', '/legacy')
  159. const db = openDatabase(path, 'wal')
  160. db.prepare('INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length) VALUES (?, ?, ?, ?, NULL, NULL)')
  161. .run(m.id, m.version, m.createdAt, m.cwd ?? null)
  162. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  163. .run(m.id, 0, 'request/header', 1, JSON.stringify({
  164. header: { config: { model: 'legacy' } },
  165. reason: 'fallback',
  166. }))
  167. db.close()
  168. const mounted = await backend(path)
  169. await expect(mounted.ctx.sessionPersistence.load(m.id))
  170. .rejects.toThrow(/unsupported legacy request\/header reason "fallback" at seq 0/)
  171. await mounted.dispose()
  172. })
  173. it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
  174. const path = await freshDbPath()
  175. const m = meta('crash')
  176. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  177. const ctx1 = new Context()
  178. await ctx1.plugin(SessionStore)
  179. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  180. await ctx1.sessionPersistence.create(m)
  181. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  182. await ctx1.sessionPersistence.append(m.id, [
  183. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  184. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  185. ])
  186. await fiber1.dispose()
  187. // Run 2: load PRESERVES the interrupted turn's real events (a turn can be huge
  188. // — never truncated) and closes the orphaned turn with synthetic boundary
  189. // events: step/end (the step was open) then turn/end {interrupted}.
  190. const ctx2 = new Context()
  191. await ctx2.plugin(SessionStore)
  192. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  193. const loaded = await ctx2.sessionPersistence.load(m.id)
  194. expect(loaded.events.map(e => e.type)).toEqual([
  195. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  196. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  197. ])
  198. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  199. const last = loaded.events.at(-1)!
  200. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  201. // load durably closed the turn, so the next append continues at the balanced
  202. // length (seq 10) and a reload round-trips identically.
  203. await ctx2.sessionPersistence.append(m.id, [
  204. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  205. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  206. ])
  207. const reloaded = await ctx2.sessionPersistence.load(m.id)
  208. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  209. await fiber2.dispose()
  210. })
  211. it('load() durably closes the interrupted turn: the synthetic closers are on disk after load', async () => {
  212. const path = await freshDbPath()
  213. const m = meta('load-closes')
  214. const b1 = await backend(path)
  215. await b1.ctx.sessionPersistence.create(m)
  216. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  217. await b1.dispose()
  218. // Hand-write an interrupted turn (turn/start seq 6, no turn/end).
  219. const db = openDatabase(path, 'wal')
  220. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  221. .run(m.id, 'turn/start', JSON.stringify({ turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } }))
  222. db.close()
  223. const b2 = await backend(path)
  224. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  225. // turn 2's real turn/start (seq 6) is preserved + a synthetic turn/end (seq 7).
  226. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  227. expect(loaded.events.at(-1)!.type).toBe('turn/end')
  228. // load() is mutating: the synthetic turn/end MUST be on disk so the stored log
  229. // is balanced and the cursor is truthful (contract: load closes, not defers).
  230. const probe = openDatabase(path, 'wal')
  231. const stored = probe.prepare('SELECT seq, type FROM events WHERE session_id = ? ORDER BY seq').all(m.id) as { seq: number; type: string }[]
  232. probe.close()
  233. expect(stored.map(r => r.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  234. expect(stored.at(-1)!.type).toBe('turn/end')
  235. await b2.dispose()
  236. })
  237. it('all-tail load: a session whose only turn never closed is preserved and closed on load', async () => {
  238. const path = await freshDbPath()
  239. const m = meta('all-tail')
  240. const b1 = await backend(path)
  241. await b1.ctx.sessionPersistence.create(m)
  242. // A first turn that NEVER completed: turn/start + user/message, no turn/end.
  243. await b1.ctx.sessionPersistence.append(m.id, [
  244. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  245. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } } },
  246. ])
  247. await b1.dispose()
  248. // A fresh backend loads it: the interrupted (only) turn's real events are
  249. // preserved and closed with a synthetic turn/end {interrupted} — NOT
  250. // truncated. The session was materialized, so list() reports it present.
  251. const b2 = await backend(path)
  252. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  253. expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  254. expect(loaded.events.at(-1)!.type === 'turn/end' && loaded.events.at(-1)!.data).toMatchObject({ reason: { kind: 'interrupted' } })
  255. expect((await b2.ctx.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  256. await b2.dispose()
  257. })
  258. it('rejects opening a database whose schema version is not the current build (newer OR older)', async () => {
  259. const path = await freshDbPath()
  260. openDatabase(path, 'wal').close() // stamp user_version = SCHEMA_VERSION
  261. // Bump user_version past what this build supports.
  262. const dbNewer = openDatabase(path, 'wal')
  263. dbNewer.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`)
  264. dbNewer.close()
  265. expect(() => openDatabase(path, 'wal')).toThrow(/incompatible with this build/)
  266. // A stale OLDER version (e.g. a pre-summary-drop v1 DB) is also rejected —
  267. // we do not migrate (unreleased software, no backward-compat).
  268. const olderPath = await freshDbPath()
  269. openDatabase(olderPath, 'wal').close()
  270. const dbOlder = openDatabase(olderPath, 'wal')
  271. dbOlder.exec('PRAGMA user_version = 1')
  272. dbOlder.close()
  273. expect(() => openDatabase(olderPath, 'wal')).toThrow(/incompatible with this build/)
  274. })
  275. it('rejects a sibling v3 database (the merge-collided version) rather than opening it against missing columns', async () => {
  276. // Two unmerged branches each shipped a DISTINCT layout under user_version 3 (one added only
  277. // `seed_length`, the other only the surface columns). The merged v4 cannot interpret that
  278. // ambiguous, incomplete layout and must reject it.
  279. const path = await freshDbPath()
  280. openDatabase(path, 'wal').close() // creates + stamps user_version = SCHEMA_VERSION (4)
  281. const db = openDatabase(path, 'wal')
  282. db.exec('PRAGMA user_version = 3')
  283. db.close()
  284. expect(() => openDatabase(path, 'wal')).toThrow(/schema version 3, incompatible with this build/)
  285. })
  286. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  287. const path = await freshDbPath()
  288. const m = meta('corrupt-tail')
  289. const b1 = await backend(path)
  290. await b1.ctx.sessionPersistence.create(m)
  291. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  292. await b1.dispose()
  293. // A torn row after the last committed turn has invalid JSON. `scanRows` locates the boundary
  294. // from seq/type columns without parsing the tail, preserves the committed prefix, and load
  295. // deletes the row; invalid JSON inside the committed region would remain fatal.
  296. const db = openDatabase(path, 'wal')
  297. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  298. .run(m.id, 'turn/start', '{not valid json')
  299. db.close()
  300. const b2 = await backend(path)
  301. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  302. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  303. // load physically deleted the corrupt tail row, so a fresh append continues.
  304. await b2.ctx.sessionPersistence.append(m.id, [
  305. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  306. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  307. ])
  308. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  309. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  310. await b2.dispose()
  311. })
  312. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  313. const ctx = new Context()
  314. await ctx.plugin(SessionStore)
  315. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  316. const m = meta('rollback')
  317. await ctx.sessionPersistence.create(m)
  318. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  319. // A batch that re-states an already-stored seq must be rejected and leave
  320. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  321. // inside the transaction → ROLLBACK).
  322. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  323. const loaded = await ctx.sessionPersistence.load(m.id)
  324. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  325. await fiber.dispose()
  326. })
  327. it('persists across separate backend instances over the same file', async () => {
  328. const path = await freshDbPath()
  329. const m = meta('persist', '/proj')
  330. const ctx1 = new Context()
  331. await ctx1.plugin(SessionStore)
  332. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  333. await ctx1.sessionPersistence.create(m)
  334. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  335. await fiber1.dispose()
  336. const ctx2 = new Context()
  337. await ctx2.plugin(SessionStore)
  338. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  339. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  340. const loaded = await ctx2.sessionPersistence.load(m.id)
  341. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj' })
  342. expect(loaded.events).toEqual(oneTurnLog())
  343. await fiber2.dispose()
  344. })
  345. it('exposes the schema version constant', () => {
  346. expect(SCHEMA_VERSION).toBe(4)
  347. })
  348. })
  349. describe('SessionPersistenceSqlite: edge cases', () => {
  350. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  351. const path = await freshDbPath()
  352. const m = meta('rollback-insert')
  353. const b1 = await backend(path)
  354. await b1.ctx.sessionPersistence.create(m)
  355. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  356. // A SECOND backend over the same file loads the session first, so it adopts
  357. // cursor 6 (the committed length) into its OWN in-memory state.
  358. const b2 = await backend(path)
  359. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  360. const turn2: SessionEvent[] = [
  361. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  362. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  363. ]
  364. // b1 commits seq 6..7 first.
  365. await b1.ctx.sessionPersistence.append(m.id, turn2)
  366. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  367. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  368. // mid-transaction → ROLLBACK + rethrow.
  369. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  370. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  371. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  372. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  373. await b1.dispose()
  374. await b2.dispose()
  375. })
  376. it('journalMode config reaches the database (default wal, rollback modes selectable)', async () => {
  377. // :memory: databases always report journal_mode=memory, so probe file DBs.
  378. const walPath = await freshDbPath()
  379. const bWal = await backend(walPath)
  380. await bWal.ctx.sessionPersistence.create(meta('jm-wal'))
  381. expect((openDatabase(walPath, 'wal').prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('wal')
  382. await bWal.dispose()
  383. const deletePath = await freshDbPath()
  384. const ctx = new Context()
  385. await ctx.plugin(SessionStore)
  386. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: deletePath, journalMode: 'delete' })
  387. await ctx.sessionPersistence.create(meta('jm-delete'))
  388. // Probe through a second connection: journal_mode=delete is a per-database
  389. // property only insofar as no WAL files exist — assert the world, not the
  390. // backend's self-report (no -wal sidecar after writes in delete mode).
  391. const db = openDatabase(deletePath, 'delete')
  392. expect((db.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('delete')
  393. db.close()
  394. expect(existsSync(`${deletePath}-wal`)).toBe(false)
  395. await fiber.dispose()
  396. })
  397. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  398. const path = await freshDbPath()
  399. // Instance 1 materializes a session and disposes.
  400. const b1 = await backend(path)
  401. const s1 = b1.ctx.sessions.create(SessionId('hmr-collide'))
  402. appendLog(s1, oneTurnLog())
  403. await b1.ctx.parallel('session/flush', s1)
  404. await b1.dispose()
  405. // A fresh context with an UNRELATED live session reusing the id meets a
  406. // materialized row that is NOT a prefix of its events → reject.
  407. const ctx = new Context()
  408. await ctx.plugin(SessionStore)
  409. let session!: Session
  410. await ctx.plugin(Object.assign((inner: Context) => {
  411. session = inner.sessions.create(SessionId('hmr-collide'))
  412. }, { inject: ['sessions'] }))
  413. session.append('turn/start', { turn: 9, trigger: { kind: 'message', source: { kind: 'user' } } })
  414. await ctx.plugin(SessionPersistenceSqlite, { path })
  415. await expectParallelFlushError(ctx.parallel('session/flush', session), /id collision/)
  416. await ctx.fiber.dispose()
  417. })
  418. })
  419. describe('surface field round-trip', () => {
  420. it('rowToEvent parses surface fields from EventRow columns', () => {
  421. const row: EventRow = {
  422. seq: 0, type: 'assistant/message', time: 1,
  423. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  424. source_event_seqs: JSON.stringify([3, 5]),
  425. surface_op: JSON.stringify('append'),
  426. }
  427. const event = rowToEvent(row)
  428. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([3, 5])
  429. expect((event as SurfaceEvent).surfaceOp).toBe('append')
  430. })
  431. it('rowToEvent handles replace surfaceOp object', () => {
  432. const row: EventRow = {
  433. seq: 0, type: 'assistant/message', time: 1,
  434. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  435. source_event_seqs: JSON.stringify([0, 1]),
  436. surface_op: JSON.stringify({ op: 'replace', start: 0, end: 1 }),
  437. }
  438. const event = rowToEvent(row)
  439. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  440. expect((event as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 1 })
  441. })
  442. it('scanRows with surface columns reconstructs events with surface fields', () => {
  443. const rows: EventRow[] = [
  444. { seq: 0, type: 'user/message', time: 1,
  445. data: JSON.stringify({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }),
  446. source_event_seqs: null, surface_op: '{"op":"replace","start":0,"end":0}' },
  447. { seq: 1, type: 'turn/end', time: 2,
  448. data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }),
  449. source_event_seqs: null, surface_op: null },
  450. ]
  451. const { preserved } = scanRows(rows)
  452. expect(preserved).toHaveLength(2)
  453. expect((preserved[0]! as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  454. expect((preserved[0]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  455. expect((preserved[1] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  456. })
  457. it('append and load round-trips surface fields through SQLite', async () => {
  458. const ctx = new Context()
  459. await ctx.plugin(SessionStore)
  460. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  461. const session = ctx.sessions.create(SessionId('roundtrip-surface'))
  462. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  463. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  464. session.append('assistant/message', { turn: 1, step: 1, content: [] }, { surfaceOp: 'append', sourceEventSeqs: [0] })
  465. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  466. await ctx.parallel('session/flush', session)
  467. const loaded = await ctx.sessionPersistence.load(SessionId('roundtrip-surface'))
  468. expect(loaded.events).toHaveLength(4)
  469. const um = loaded.events[1]!
  470. expect((um as SurfaceEvent).surfaceOp).toBe('append')
  471. expect((um as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  472. const am = loaded.events[2]!
  473. expect((am as SurfaceEvent).surfaceOp).toBe('append')
  474. expect((am as SurfaceEvent).sourceEventSeqs).toEqual([0])
  475. await fiber.dispose()
  476. })
  477. it('persists events with surfaceOp but no sourceEventSeqs (covers null branch in surfaceBindings)', async () => {
  478. const ctx = new Context()
  479. await ctx.plugin(SessionStore)
  480. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  481. const session = ctx.sessions.create(SessionId('surface-noseq'))
  482. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  483. session.append('steering/message', { turn: 1, content: [], source: { kind: 'user' } }, { surfaceOp: 'append' })
  484. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  485. await ctx.parallel('session/flush', session)
  486. const loaded = await ctx.sessionPersistence.load(SessionId('surface-noseq'))
  487. expect((loaded.events[1]! as SurfaceEvent).surfaceOp).toBe('append')
  488. expect((loaded.events[1]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  489. await fiber.dispose()
  490. })
  491. })