sqlite.spec.ts 24 KB

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