sqlite.spec.ts 25 KB

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