sqlite.spec.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. import { createUserMessage, createMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it } from 'vitest'
  3. import { Context } from 'cordis'
  4. import { existsSync } from 'node:fs'
  5. import { chmod, mkdtemp, rm, stat, symlink, writeFile } from 'node:fs/promises'
  6. import { tmpdir } from 'node:os'
  7. import { dirname, join } from 'node:path'
  8. import { DatabaseSync } from 'node:sqlite'
  9. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  10. import type { Session, SessionEvent, SurfaceEvent, SurfaceEventType } from '@deepseek-ai/dsh-session'
  11. import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
  12. import {
  13. openDatabase,
  14. rowToEvent,
  15. rowToMeta,
  16. scanRows,
  17. SESSION_PERSISTENCE_SQLITE_APPLICATION_ID,
  18. type EventRow,
  19. } from '../src/schema.ts'
  20. import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts'
  21. import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
  22. const dirs: string[] = []
  23. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  24. async function expectFlushError(promise: Promise<unknown>, message: RegExp): Promise<void> {
  25. try {
  26. await promise
  27. } catch (error) {
  28. expect(error).toBeInstanceOf(Error)
  29. expect((error as Error).message).toMatch(message)
  30. return
  31. }
  32. throw new Error('expected flush to reject')
  33. }
  34. async function freshDbPath(): Promise<string> {
  35. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-'))
  36. dirs.push(dir)
  37. return join(dir, 'sessions.db')
  38. }
  39. /** A context with the session store + SQLite backend, plus a teardown. */
  40. async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
  41. const ctx = new Context()
  42. await ctx.plugin(SessionStore)
  43. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  44. return { ctx, dispose: () => fiber.dispose() }
  45. }
  46. // Run the same backend-agnostic contract as JSONL to pin identical semantics.
  47. runPersistenceContract('sqlite', async () => {
  48. const ctx = new Context()
  49. await ctx.plugin(SessionStore)
  50. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  51. return {
  52. persistence: ctx.sessionPersistence,
  53. dispose: async () => { await fiber.dispose() },
  54. }
  55. })
  56. // A file-backed database lets two mounts share rows across reload. `corruptTail` inserts invalid
  57. // JSON past the committed seq, exercising coordinator repair against real database rows.
  58. runCoordinatorContract('sqlite', async (): Promise<CoordinatorFixture> => {
  59. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-coord-'))
  60. const path = join(dir, 'sessions.db')
  61. return {
  62. mount: async ctx => ctx.plugin(SessionPersistenceSqlite, { path }),
  63. corruptTail: async (id) => {
  64. // A row past the committed region whose `data` does not parse: scanRows
  65. // bounds the preserved prefix at it and returns its seq as tornFrom, which
  66. // the backend surfaces to the coordinator as the tornMarker to delete from.
  67. const db = openDatabase(path, 'wal')
  68. const next = (db.prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM events WHERE session_id = ?')
  69. .get(id) as { n: number }).n
  70. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  71. .run(id, next, 'assistant/chunk', 99, '{not valid json')
  72. db.close()
  73. },
  74. cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
  75. }
  76. })
  77. describe('scanRows', () => {
  78. // scanRows works off EventRows (data is a JSON string column); build them from SessionEvents
  79. // so the unit tests read in terms of the event vocabulary. Surface metadata is serialized to
  80. // its nullable columns so the conversion remains faithful.
  81. const rows = (events: SessionEvent[]): EventRow[] =>
  82. events.map((e) => {
  83. const se = e as SessionEvent<SurfaceEventType>
  84. return {
  85. seq: e.seq, type: e.type, time: e.time, data: JSON.stringify(e.data),
  86. source_event_seqs: se.sourceEventSeqs !== undefined ? JSON.stringify(se.sourceEventSeqs) : null,
  87. surface_op: se.surfaceOp !== undefined ? JSON.stringify(se.surfaceOp) : null,
  88. }
  89. })
  90. it('preserves the full log when it ends exactly on a turn/end (no torn tail)', () => {
  91. const { preserved, tornFrom } = scanRows(rows(oneTurnLog()))
  92. expect(preserved).toEqual(oneTurnLog())
  93. expect(tornFrom).toBeUndefined()
  94. })
  95. it('PRESERVES the real events of an interrupted turn after the last turn/end', () => {
  96. // turn 1 committed (0..5) + a crashed turn 2 (turn/start 6, step/start 7, no
  97. // close): all 8 rows are intact, so the whole prefix is preserved and there
  98. // is no torn fragment to delete. (load() then synthesizes the closers.)
  99. const withOpenTurn: SessionEvent[] = [
  100. ...oneTurnLog(),
  101. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  102. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  103. ]
  104. const { preserved, tornFrom } = scanRows(rows(withOpenTurn))
  105. expect(preserved.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  106. expect(tornFrom).toBeUndefined()
  107. })
  108. it('preserves the contiguous prefix and flags a torn tail at a seq gap', () => {
  109. // A gap after seq 0 (no committed turn/end): seq 0 is the preserved
  110. // interrupted-turn event; the gap bounds it and marks the torn fragment.
  111. const gapped: SessionEvent[] = [
  112. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  113. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  114. ]
  115. const { preserved, tornFrom } = scanRows(rows(gapped))
  116. expect(preserved.map(e => e.seq)).toEqual([0])
  117. expect(tornFrom).toBe(1)
  118. })
  119. it('an empty log preserves nothing and has no torn tail', () => {
  120. expect(scanRows([])).toEqual({ preserved: [] })
  121. })
  122. it('throws on a seq gap inside the committed region (before the last turn/end)', () => {
  123. const gapped: SessionEvent[] = [
  124. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  125. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  126. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  127. ]
  128. expect(() => scanRows(rows(gapped))).toThrow(/seq gap in committed region/)
  129. })
  130. it('throws on an unparsable row inside the committed region', () => {
  131. const withCorruptCommitted: EventRow[] = [
  132. { seq: 0, type: 'turn/start', time: 1, data: '{not json', source_event_seqs: null, surface_op: null }, // corrupt, sits before a turn/end
  133. { seq: 1, type: 'turn/end', time: 2, data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }), source_event_seqs: null, surface_op: null },
  134. ]
  135. expect(() => scanRows(withCorruptCommitted)).toThrow(/unparsable committed event/)
  136. })
  137. it('tolerates an unparsable torn-tail row after the last turn/end', () => {
  138. const withCorruptTail: EventRow[] = [
  139. ...rows(oneTurnLog()),
  140. { seq: 6, type: 'turn/start', time: 7, data: '{not json', source_event_seqs: null, surface_op: null }, // torn fragment, no committed turn/end after
  141. ]
  142. const { preserved, tornFrom } = scanRows(withCorruptTail)
  143. expect(preserved).toEqual(oneTurnLog())
  144. expect(tornFrom).toBe(6)
  145. })
  146. })
  147. describe('rowToMeta', () => {
  148. it('restores optional origin metadata', () => {
  149. expect(rowToMeta({
  150. id: 'with-origin',
  151. version: 0,
  152. created_at: 1,
  153. cwd: null,
  154. parent_session: null,
  155. seed_length: null,
  156. origin: 'subagent',
  157. incarnation: 'with-origin',
  158. revision: 1,
  159. delegation_depth: null,
  160. })).toMatchObject({ id: 'with-origin', origin: 'subagent' })
  161. })
  162. it('rejects fractional stored creation metadata', () => {
  163. expect(() => rowToMeta({
  164. id: 'fractional',
  165. version: 0,
  166. created_at: 1.5,
  167. cwd: null,
  168. parent_session: null,
  169. seed_length: null,
  170. origin: null,
  171. incarnation: 'fractional',
  172. revision: 1,
  173. delegation_depth: null,
  174. })).toThrow('stored session createdAt must be a non-negative safe integer')
  175. })
  176. })
  177. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  178. it('rejects a stored v0 log containing a legacy request/header-delta event', async () => {
  179. const path = await freshDbPath()
  180. const m = meta('legacy-header-delta', '/legacy')
  181. const db = openDatabase(path, 'wal')
  182. db.prepare('INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length, delegation_depth, incarnation, revision) VALUES (?, ?, ?, ?, NULL, NULL, NULL, ?, 1)')
  183. .run(m.id, m.version, m.createdAt, m.cwd ?? null, 'legacy-header-delta')
  184. const insert = db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  185. insert.run(m.id, 0, 'turn/start', 1, JSON.stringify({ turn: 1 }))
  186. insert.run(m.id, 1, 'request/header-delta', 2, JSON.stringify({ config: { model: 'legacy' } }))
  187. insert.run(m.id, 2, 'turn/end', 3, JSON.stringify({ turn: 1, reason: { kind: 'completed' } }))
  188. db.close()
  189. const mounted = await backend(path)
  190. await expect(mounted.ctx.sessionPersistence.load(m.id)).rejects.toThrow(/unsupported legacy request\/header-delta event at seq 1/)
  191. await mounted.dispose()
  192. })
  193. it('rejects a stored v0 full header carrying the legacy fallback reason', async () => {
  194. const path = await freshDbPath()
  195. const m = meta('legacy-header-fallback', '/legacy')
  196. const db = openDatabase(path, 'wal')
  197. db.prepare('INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length, delegation_depth, incarnation, revision) VALUES (?, ?, ?, ?, NULL, NULL, NULL, ?, 1)')
  198. .run(m.id, m.version, m.createdAt, m.cwd ?? null, 'legacy-header-fallback')
  199. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
  200. .run(m.id, 0, 'request/header', 1, JSON.stringify({
  201. header: { config: { model: 'legacy' } },
  202. reason: 'fallback',
  203. }))
  204. db.close()
  205. const mounted = await backend(path)
  206. await expect(mounted.ctx.sessionPersistence.load(m.id))
  207. .rejects.toThrow(/unsupported legacy request\/header reason "fallback" at seq 0/)
  208. await mounted.dispose()
  209. })
  210. it('has no independent per-session log location', async () => {
  211. const { ctx, dispose } = await backend()
  212. expect(ctx.sessionPersistence.locate(meta('sqlite-location'))).toBeUndefined()
  213. await dispose()
  214. })
  215. it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
  216. const path = await freshDbPath()
  217. const m = meta('crash')
  218. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  219. const ctx1 = new Context()
  220. await ctx1.plugin(SessionStore)
  221. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  222. await ctx1.sessionPersistence.create(m)
  223. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  224. await ctx1.sessionPersistence.append(m.id, [
  225. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  226. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  227. ])
  228. await fiber1.dispose()
  229. // Run 2: load PRESERVES the interrupted turn's real events (a turn can be huge
  230. // — never truncated) and closes the orphaned turn with synthetic boundary
  231. // events: step/end (the step was open) then turn/end {interrupted}.
  232. const ctx2 = new Context()
  233. await ctx2.plugin(SessionStore)
  234. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  235. const loaded = await ctx2.sessionPersistence.load(m.id)
  236. expect(loaded.events.map(e => e.type)).toEqual([
  237. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  238. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  239. ])
  240. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  241. const last = loaded.events.at(-1)!
  242. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  243. // load durably closed the turn, so the next append continues at the balanced
  244. // length (seq 10) and a reload round-trips identically.
  245. await ctx2.sessionPersistence.append(m.id, [
  246. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3 } },
  247. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  248. ])
  249. const reloaded = await ctx2.sessionPersistence.load(m.id)
  250. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  251. await fiber2.dispose()
  252. })
  253. it('load() durably closes the interrupted turn: the synthetic closers are on disk after load', async () => {
  254. const path = await freshDbPath()
  255. const m = meta('load-closes')
  256. const b1 = await backend(path)
  257. await b1.ctx.sessionPersistence.create(m)
  258. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  259. await b1.dispose()
  260. // Hand-write an interrupted turn (turn/start seq 6, no turn/end).
  261. const db = openDatabase(path, 'wal')
  262. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  263. .run(m.id, 'turn/start', JSON.stringify({ turn: 2 }))
  264. db.close()
  265. const b2 = await backend(path)
  266. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  267. // turn 2's real turn/start (seq 6) is preserved + a synthetic turn/end (seq 7).
  268. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  269. expect(loaded.events.at(-1)!.type).toBe('turn/end')
  270. // load() is mutating: the synthetic turn/end MUST be on disk so the stored log
  271. // is balanced and the cursor is truthful (contract: load closes, not defers).
  272. const probe = openDatabase(path, 'wal')
  273. const stored = probe.prepare('SELECT seq, type FROM events WHERE session_id = ? ORDER BY seq').all(m.id) as { seq: number; type: string }[]
  274. probe.close()
  275. expect(stored.map(r => r.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  276. expect(stored.at(-1)!.type).toBe('turn/end')
  277. await b2.dispose()
  278. })
  279. it('all-tail load: a session whose only turn never closed is preserved and closed on load', async () => {
  280. const path = await freshDbPath()
  281. const m = meta('all-tail')
  282. const b1 = await backend(path)
  283. await b1.ctx.sessionPersistence.create(m)
  284. // A first turn that NEVER completed: turn/start + user/message, no turn/end.
  285. await b1.ctx.sessionPersistence.append(m.id, [
  286. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  287. { type: 'user/message', seq: 1, time: 2, data: createUserMessage({
  288. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  289. }), surfaceOp: 'append' },
  290. ])
  291. await b1.dispose()
  292. // A fresh backend loads it: the interrupted (only) turn's real events are
  293. // preserved and closed with a synthetic turn/end {interrupted} — NOT
  294. // truncated. The session was materialized, so list() reports it present.
  295. const b2 = await backend(path)
  296. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  297. expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  298. expect(loaded.events.at(-1)!.type === 'turn/end' && loaded.events.at(-1)!.data).toMatchObject({ reason: { kind: 'interrupted' } })
  299. expect((await b2.ctx.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  300. await b2.dispose()
  301. })
  302. it('rejects opening a database whose schema version is not the current build (newer OR older)', async () => {
  303. const path = await freshDbPath()
  304. openDatabase(path, 'wal').close() // stamp user_version = SCHEMA_VERSION
  305. // Bump user_version past what this build supports.
  306. const dbNewer = openDatabase(path, 'wal')
  307. dbNewer.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`)
  308. dbNewer.close()
  309. expect(() => openDatabase(path, 'wal')).toThrow(/incompatible with this build/)
  310. // The immediately preceding layout lacks the required store identity and is
  311. // rejected rather than migrated (unreleased software, no backward-compat).
  312. const olderPath = await freshDbPath()
  313. openDatabase(olderPath, 'wal').close()
  314. const dbOlder = openDatabase(olderPath, 'wal')
  315. dbOlder.exec(`PRAGMA user_version = ${SCHEMA_VERSION - 1}`)
  316. dbOlder.close()
  317. expect(() => openDatabase(olderPath, 'wal')).toThrow(/incompatible with this build/)
  318. })
  319. it('rejects a table-backed unversioned database before stamping or changing journal mode', async () => {
  320. const path = await freshDbPath()
  321. const legacy = new DatabaseSync(path)
  322. legacy.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY)')
  323. legacy.close()
  324. expect(() => openDatabase(path, 'wal')).toThrow(/unversioned schema or application identity/)
  325. const unchanged = new DatabaseSync(path)
  326. expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 })
  327. expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  328. expect(unchanged.prepare(
  329. "SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'sessions'",
  330. ).get()).toEqual({ name: 'sessions' })
  331. unchanged.close()
  332. })
  333. it('counts a sqliteX table as user-owned instead of mistaking it for SQLite metadata', async () => {
  334. const path = await freshDbPath()
  335. const unrelated = new DatabaseSync(path)
  336. unrelated.exec('CREATE TABLE sqliteX (value TEXT)')
  337. unrelated.exec("INSERT INTO sqliteX VALUES ('safe')")
  338. unrelated.close()
  339. expect(() => openDatabase(path, 'wal')).toThrow(/unversioned schema or application identity/)
  340. const unchanged = new DatabaseSync(path)
  341. expect(unchanged.prepare('SELECT value FROM sqliteX').get()).toEqual({ value: 'safe' })
  342. expect(unchanged.prepare('PRAGMA application_id').get()).toEqual({ application_id: 0 })
  343. expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 })
  344. expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  345. unchanged.close()
  346. })
  347. it('rejects view-only and foreign-application unversioned databases without mutation', async () => {
  348. const viewPath = await freshDbPath()
  349. const viewOnly = new DatabaseSync(viewPath)
  350. viewOnly.exec('CREATE VIEW foreign_view AS SELECT 1 AS value')
  351. viewOnly.close()
  352. expect(() => openDatabase(viewPath, 'wal')).toThrow(/unversioned schema or application identity/)
  353. const unchangedView = new DatabaseSync(viewPath)
  354. expect(unchangedView.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  355. expect(unchangedView.prepare(
  356. "SELECT type FROM sqlite_schema WHERE name = 'foreign_view'",
  357. ).get()).toEqual({ type: 'view' })
  358. unchangedView.close()
  359. const applicationPath = await freshDbPath()
  360. const foreignApplication = new DatabaseSync(applicationPath)
  361. foreignApplication.exec('PRAGMA application_id = 12345')
  362. foreignApplication.close()
  363. expect(() => openDatabase(applicationPath, 'wal')).toThrow(/unversioned schema or application identity/)
  364. const unchangedApplication = new DatabaseSync(applicationPath)
  365. expect(unchangedApplication.prepare('PRAGMA application_id').get()).toEqual({ application_id: 12345 })
  366. expect(unchangedApplication.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 })
  367. expect(unchangedApplication.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  368. unchangedApplication.close()
  369. })
  370. it('rejects a current-version database with a foreign application identity', async () => {
  371. const path = await freshDbPath()
  372. const foreign = new DatabaseSync(path)
  373. foreign.exec('PRAGMA application_id = 12345')
  374. foreign.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`)
  375. foreign.close()
  376. expect(() => openDatabase(path, 'wal')).toThrow(/has application id 12345/)
  377. const unchanged = new DatabaseSync(path)
  378. expect(unchanged.prepare('PRAGMA application_id').get()).toEqual({ application_id: 12345 })
  379. expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION })
  380. expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  381. unchanged.close()
  382. })
  383. it('rolls back schema objects and identity stamps when initialization fails', async () => {
  384. const path = await freshDbPath()
  385. const conflicting = new DatabaseSync(path)
  386. conflicting.exec(`PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`)
  387. conflicting.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`)
  388. conflicting.exec("CREATE VIEW persistence_state AS SELECT 1 AS singleton, 'foreign' AS store_id")
  389. conflicting.close()
  390. expect(() => openDatabase(path, 'wal')).toThrow()
  391. const unchanged = new DatabaseSync(path)
  392. expect(unchanged.prepare(
  393. "SELECT type FROM sqlite_schema WHERE name = 'persistence_state'",
  394. ).get()).toEqual({ type: 'view' })
  395. expect(unchanged.prepare(
  396. "SELECT type FROM sqlite_schema WHERE name = 'sessions'",
  397. ).get()).toBeUndefined()
  398. expect(unchanged.prepare(
  399. "SELECT type FROM sqlite_schema WHERE name = 'events'",
  400. ).get()).toBeUndefined()
  401. expect(unchanged.prepare('PRAGMA application_id').get())
  402. .toEqual({ application_id: SESSION_PERSISTENCE_SQLITE_APPLICATION_ID })
  403. expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION })
  404. expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
  405. unchanged.close()
  406. })
  407. it('stamps the persistence application identity with the schema version', async () => {
  408. const path = await freshDbPath()
  409. openDatabase(path, 'wal').close()
  410. const db = new DatabaseSync(path)
  411. expect(db.prepare('PRAGMA application_id').get())
  412. .toEqual({ application_id: SESSION_PERSISTENCE_SQLITE_APPLICATION_ID })
  413. expect(db.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION })
  414. db.close()
  415. })
  416. it('rejects a sibling v3 database (the merge-collided version) rather than opening it against missing columns', async () => {
  417. // Version 3 identified two incompatible sibling layouts, so it is always rejected.
  418. const path = await freshDbPath()
  419. openDatabase(path, 'wal').close() // creates + stamps user_version = SCHEMA_VERSION
  420. const db = openDatabase(path, 'wal')
  421. db.exec('PRAGMA user_version = 3')
  422. db.close()
  423. expect(() => openDatabase(path, 'wal')).toThrow(/schema version 3, incompatible with this build/)
  424. })
  425. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  426. const path = await freshDbPath()
  427. const m = meta('corrupt-tail')
  428. const b1 = await backend(path)
  429. await b1.ctx.sessionPersistence.create(m)
  430. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  431. await b1.dispose()
  432. // A torn row after the last committed turn has invalid JSON. `scanRows` locates the boundary
  433. // from seq/type columns without parsing the tail, preserves the committed prefix, and load
  434. // deletes the row; invalid JSON inside the committed region would remain fatal.
  435. const db = openDatabase(path, 'wal')
  436. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  437. .run(m.id, 'turn/start', '{not valid json')
  438. db.close()
  439. const b2 = await backend(path)
  440. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  441. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  442. // load physically deleted the corrupt tail row, so a fresh append continues.
  443. await b2.ctx.sessionPersistence.append(m.id, [
  444. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2 } },
  445. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  446. ])
  447. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  448. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  449. await b2.dispose()
  450. })
  451. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  452. const ctx = new Context()
  453. await ctx.plugin(SessionStore)
  454. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  455. const m = meta('rollback')
  456. await ctx.sessionPersistence.create(m)
  457. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  458. // A batch that re-states an already-stored seq must be rejected and leave
  459. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  460. // inside the transaction → ROLLBACK).
  461. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  462. const loaded = await ctx.sessionPersistence.load(m.id)
  463. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  464. await fiber.dispose()
  465. })
  466. it('persists across separate backend instances over the same file', async () => {
  467. const path = await freshDbPath()
  468. const m = meta('persist', '/proj')
  469. const ctx1 = new Context()
  470. await ctx1.plugin(SessionStore)
  471. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  472. await ctx1.sessionPersistence.create(m)
  473. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  474. await fiber1.dispose()
  475. const ctx2 = new Context()
  476. await ctx2.plugin(SessionStore)
  477. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  478. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  479. const loaded = await ctx2.sessionPersistence.load(m.id)
  480. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj' })
  481. expect(loaded.events).toEqual(oneTurnLog())
  482. await fiber2.dispose()
  483. })
  484. it('source-qualifies revisions across stores while preserving same-file reopen identity', async () => {
  485. const pathA = await freshDbPath()
  486. const pathB = await freshDbPath()
  487. const m = meta('revision-source')
  488. const a = await backend(pathA)
  489. await a.ctx.sessionPersistence.create(m)
  490. await a.ctx.sessionPersistence.append(m.id, oneTurnLog())
  491. const revisionA = (await a.ctx.sessionPersistence.listSnapshots())[0]?.revision
  492. await a.dispose()
  493. const probeA = openDatabase(pathA, 'wal')
  494. const storeIdA = (probeA.prepare(
  495. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  496. ).get() as { store_id: string }).store_id
  497. probeA.close()
  498. const aliasA = `${pathA}.alias`
  499. await symlink(pathA, aliasA)
  500. const reopenedA = await backend(aliasA)
  501. expect((await reopenedA.ctx.sessionPersistence.listSnapshots())[0]?.revision).toBe(revisionA)
  502. await reopenedA.dispose()
  503. const b = await backend(pathB)
  504. await b.ctx.sessionPersistence.create(m)
  505. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  506. const revisionB = (await b.ctx.sessionPersistence.listSnapshots())[0]?.revision
  507. const probeB = openDatabase(pathB, 'wal')
  508. const storeIdB = (probeB.prepare(
  509. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  510. ).get() as { store_id: string }).store_id
  511. probeB.close()
  512. expect(storeIdB).not.toBe(storeIdA)
  513. expect(revisionB).not.toBe(revisionA)
  514. expect(String(revisionA)).toMatch(/:revision:1$/)
  515. expect(String(revisionB)).toMatch(/:revision:1$/)
  516. await b.dispose()
  517. })
  518. it('binds a full stored prefix to the same revision as a lightweight read', async () => {
  519. const b = await backend()
  520. const m = meta('stored-prefix-revision')
  521. await b.ctx.sessionPersistence.create(m)
  522. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  523. const persistence = b.ctx.sessionPersistence as SessionPersistenceSqlite
  524. const stored = await persistence.loadStored(m.id)
  525. expect(stored?.revision).toBe(await persistence.readStoredRevision(m.id))
  526. expect(await persistence.readStoredRevision(SessionId('missing-revision'))).toBeUndefined()
  527. await b.dispose()
  528. })
  529. it('changes revisions when a deleted session id is materialized again in the same database', async () => {
  530. const path = await freshDbPath()
  531. const m = meta('recreated-revision')
  532. const first = await backend(path)
  533. await first.ctx.sessionPersistence.create(m)
  534. await first.ctx.sessionPersistence.append(m.id, oneTurnLog())
  535. const before = (await first.ctx.sessionPersistence.listSnapshots())[0]?.revision
  536. await first.dispose()
  537. const cleanup = openDatabase(path, 'wal')
  538. cleanup.prepare('DELETE FROM sessions WHERE id = ?').run(m.id)
  539. cleanup.close()
  540. const second = await backend(path)
  541. await second.ctx.sessionPersistence.create(m)
  542. await second.ctx.sessionPersistence.append(m.id, oneTurnLog())
  543. const after = (await second.ctx.sessionPersistence.listSnapshots())[0]?.revision
  544. expect(after).not.toBe(before)
  545. expect(String(before)).toMatch(/:revision:1$/)
  546. expect(String(after)).toMatch(/:revision:1$/)
  547. await second.dispose()
  548. })
  549. it('awaits in-flight readiness before surfacing snapshot-list cancellation', async () => {
  550. const b = await backend()
  551. const internals = b.ctx.sessionPersistence as unknown as { ready: Promise<void> }
  552. const originalReady = internals.ready
  553. const readiness = Promise.withResolvers<undefined>()
  554. internals.ready = readiness.promise
  555. const reason = new Error('SQLite snapshot readiness cancelled')
  556. const controller = new AbortController()
  557. const pending = b.ctx.sessionPersistence.listSnapshots(controller.signal)
  558. let settled = false
  559. void pending.then(
  560. () => { settled = true },
  561. () => { settled = true },
  562. )
  563. controller.abort(reason)
  564. await Promise.resolve()
  565. expect(settled).toBe(false)
  566. readiness.resolve(undefined)
  567. await expect(pending).rejects.toBe(reason)
  568. internals.ready = originalReady
  569. await b.dispose()
  570. })
  571. it('exposes the schema version constant', () => {
  572. expect(SCHEMA_VERSION).toBe(13)
  573. })
  574. it('keeps the revision stable for an empty repair hook', async () => {
  575. const b = await backend()
  576. const m = meta('empty-repair')
  577. await b.ctx.sessionPersistence.create(m)
  578. await b.ctx.sessionPersistence.append(m.id, oneTurnLog())
  579. const before = await b.ctx.sessionPersistence.listSnapshots()
  580. await (b.ctx.sessionPersistence as SessionPersistenceSqlite).commitRepair(m, undefined, [])
  581. expect(await b.ctx.sessionPersistence.listSnapshots()).toEqual(before)
  582. await b.dispose()
  583. })
  584. })
  585. describe('SessionPersistenceSqlite: edge cases', () => {
  586. it('resolves the preparation-cache default without schema normalization', async () => {
  587. const ctx = new Context()
  588. await ctx.plugin(SessionStore)
  589. let persistence!: SessionPersistenceSqlite
  590. await ctx.plugin(Object.assign((inner: Context) => {
  591. persistence = new SessionPersistenceSqlite(inner, {
  592. path: ':memory:',
  593. journalMode: 'wal',
  594. })
  595. }, { inject: ['sessions'] }))
  596. expect(await persistence.list()).toEqual([])
  597. await ctx.fiber.dispose()
  598. })
  599. it('uses the configured preparation cache through the public service', async () => {
  600. const ctx = new Context()
  601. await ctx.plugin(SessionStore)
  602. const fiber = await ctx.plugin(SessionPersistenceSqlite, {
  603. path: ':memory:',
  604. preparedSessionCacheSize: 1,
  605. writeBatchMaxDelayMs: 1,
  606. })
  607. const m = meta('sqlite-preparation-cache')
  608. await ctx.sessionPersistence.create(m)
  609. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  610. const preparation = await ctx.sessionPersistence.prepare(m.id)
  611. expect(preparation.session.header).toEqual(m)
  612. preparation[Symbol.dispose]()
  613. await fiber.dispose()
  614. })
  615. it('rejects and closes a current-schema database with an invalid store identity', async () => {
  616. const path = await freshDbPath()
  617. const db = openDatabase(path, 'wal')
  618. db.exec("UPDATE persistence_state SET store_id = '' WHERE singleton = 1")
  619. db.close()
  620. const b = await backend(path)
  621. await expect(b.ctx.sessionPersistence.listSnapshots()).rejects.toThrow(/no valid store identity/)
  622. await expect(b.dispose()).resolves.toBeUndefined()
  623. })
  624. it('creates a new database and WAL sidecars with owner-only modes without changing its parent mode', async () => {
  625. if (process.platform === 'win32') return
  626. const path = await freshDbPath()
  627. const dir = dirname(path)
  628. await chmod(dir, 0o755)
  629. const b = await backend(path)
  630. await b.ctx.sessionPersistence.list()
  631. expect((await stat(dir)).mode & 0o777).toBe(0o755)
  632. expect((await stat(path)).mode & 0o777).toBe(0o600)
  633. expect((await stat(`${path}-wal`)).mode & 0o777).toBe(0o600)
  634. expect((await stat(`${path}-shm`)).mode & 0o777).toBe(0o600)
  635. await b.dispose()
  636. })
  637. it('creates a persistent rollback journal with owner-only mode', async () => {
  638. if (process.platform === 'win32') return
  639. const path = await freshDbPath()
  640. const ctx = new Context()
  641. await ctx.plugin(SessionStore)
  642. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path, journalMode: 'persist' })
  643. const m = meta('persist-permissions')
  644. await ctx.sessionPersistence.create(m)
  645. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  646. expect((await stat(path)).mode & 0o777).toBe(0o600)
  647. expect((await stat(`${path}-journal`)).mode & 0o777).toBe(0o600)
  648. await fiber.dispose()
  649. })
  650. it('preserves the mode of an existing database file', async () => {
  651. if (process.platform === 'win32') return
  652. const path = await freshDbPath()
  653. await writeFile(path, '', { mode: 0o644 })
  654. await chmod(path, 0o644)
  655. const ctx = new Context()
  656. await ctx.plugin(SessionStore)
  657. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path, journalMode: 'delete' })
  658. await ctx.sessionPersistence.list()
  659. expect((await stat(path)).mode & 0o777).toBe(0o644)
  660. await fiber.dispose()
  661. })
  662. it('surfaces an invalid database path during pre-creation', async () => {
  663. const path = await freshDbPath()
  664. const b = await backend(`${path}\0`)
  665. await expect(b.ctx.sessionPersistence.list()).rejects.toMatchObject({ code: 'ERR_INVALID_ARG_VALUE' })
  666. await b.dispose()
  667. })
  668. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  669. const path = await freshDbPath()
  670. const m = meta('rollback-insert')
  671. const b1 = await backend(path)
  672. await b1.ctx.sessionPersistence.create(m)
  673. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  674. // A SECOND backend over the same file loads the session first, so it adopts
  675. // cursor 6 (the committed length) into its OWN in-memory state.
  676. const b2 = await backend(path)
  677. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  678. const turn2: SessionEvent[] = [
  679. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } },
  680. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  681. ]
  682. // b1 commits seq 6..7 first.
  683. await b1.ctx.sessionPersistence.append(m.id, turn2)
  684. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  685. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  686. // mid-transaction → ROLLBACK + rethrow.
  687. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  688. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  689. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  690. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  691. await b1.dispose()
  692. await b2.dispose()
  693. })
  694. it('journalMode config reaches the database (default wal, rollback modes selectable)', async () => {
  695. // :memory: databases always report journal_mode=memory, so probe file DBs.
  696. const walPath = await freshDbPath()
  697. const bWal = await backend(walPath)
  698. await bWal.ctx.sessionPersistence.create(meta('jm-wal'))
  699. const probe = openDatabase(walPath, 'wal')
  700. expect((probe.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('wal')
  701. probe.close()
  702. await bWal.dispose()
  703. const deletePath = await freshDbPath()
  704. const ctx = new Context()
  705. await ctx.plugin(SessionStore)
  706. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: deletePath, journalMode: 'delete' })
  707. await ctx.sessionPersistence.create(meta('jm-delete'))
  708. // Probe through a second connection: journal_mode=delete is a per-database
  709. // property only insofar as no WAL files exist — assert the world, not the
  710. // backend's self-report (no -wal sidecar after writes in delete mode).
  711. const db = openDatabase(deletePath, 'delete')
  712. expect((db.prepare('PRAGMA journal_mode').get() as { journal_mode: string }).journal_mode).toBe('delete')
  713. db.close()
  714. expect(existsSync(`${deletePath}-wal`)).toBe(false)
  715. await fiber.dispose()
  716. })
  717. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  718. const path = await freshDbPath()
  719. // Instance 1 materializes a session and disposes.
  720. const b1 = await backend(path)
  721. const s1 = b1.ctx.sessions.create(SessionId('hmr-collide'))
  722. appendLog(s1, oneTurnLog())
  723. await b1.ctx.sessions.flush(s1)
  724. await b1.dispose()
  725. // A fresh context with an UNRELATED live session reusing the id meets a
  726. // materialized row that is NOT a prefix of its events → reject.
  727. const ctx = new Context()
  728. await ctx.plugin(SessionStore)
  729. let session!: Session
  730. await ctx.plugin(Object.assign((inner: Context) => {
  731. session = inner.sessions.create(SessionId('hmr-collide'))
  732. }, { inject: ['sessions'] }))
  733. session.append('turn/start', { turn: 1 })
  734. await ctx.plugin(SessionPersistenceSqlite, { path })
  735. await expectFlushError(ctx.sessions.flush(session), /id collision/)
  736. await ctx.fiber.dispose()
  737. })
  738. })
  739. describe('surface field round-trip', () => {
  740. it('rowToEvent parses surface fields from EventRow columns', () => {
  741. const row: EventRow = {
  742. seq: 0, type: 'assistant/message', time: 1,
  743. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  744. source_event_seqs: JSON.stringify([3, 5]),
  745. surface_op: JSON.stringify('append'),
  746. }
  747. const event = rowToEvent(row)
  748. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([3, 5])
  749. expect((event as SurfaceEvent).surfaceOp).toBe('append')
  750. })
  751. it('rowToEvent handles replace surfaceOp object', () => {
  752. const row: EventRow = {
  753. seq: 0, type: 'assistant/message', time: 1,
  754. data: JSON.stringify({ turn: 1, step: 1, content: [] }),
  755. source_event_seqs: JSON.stringify([0, 1]),
  756. surface_op: JSON.stringify({ op: 'replace', start: 0, end: 1 }),
  757. }
  758. const event = rowToEvent(row)
  759. expect((event as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  760. expect((event as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 1 })
  761. })
  762. it('scanRows with surface columns reconstructs events with surface fields', () => {
  763. const rows: EventRow[] = [
  764. { seq: 0, type: 'user/message', time: 1,
  765. data: JSON.stringify({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }),
  766. source_event_seqs: null, surface_op: '{"op":"replace","start":0,"end":0}' },
  767. { seq: 1, type: 'turn/end', time: 2,
  768. data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }),
  769. source_event_seqs: null, surface_op: null },
  770. ]
  771. const { preserved } = scanRows(rows)
  772. expect(preserved).toHaveLength(2)
  773. expect((preserved[0]! as SurfaceEvent).surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  774. expect((preserved[0]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  775. expect((preserved[1] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  776. })
  777. it('append and load round-trips surface fields through SQLite', async () => {
  778. const ctx = new Context()
  779. await ctx.plugin(SessionStore)
  780. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  781. const session = ctx.sessions.create(SessionId('roundtrip-surface'))
  782. session.append('turn/start', { turn: 1 })
  783. session.append('step/start', { turn: 1, step: 1 })
  784. session.append('user/message', createUserMessage({
  785. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  786. }), { surfaceOp: 'append' })
  787. session.append('assistant/message', {
  788. turn: 1, step: 1,
  789. message: createMessage({
  790. role: 'assistant',
  791. content: [],
  792. source: {
  793. kind: 'model',
  794. ...{ provider: 'mock', model: 'mock' },
  795. },
  796. }),
  797. }, { surfaceOp: 'append', sourceEventSeqs: [2] })
  798. session.append('step/end', { turn: 1, step: 1 })
  799. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  800. await ctx.sessions.flush(session)
  801. const loaded = await ctx.sessionPersistence.load(SessionId('roundtrip-surface'))
  802. expect(loaded.events).toHaveLength(6)
  803. const um = loaded.events[2]!
  804. expect((um as SurfaceEvent).surfaceOp).toBe('append')
  805. expect((um as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  806. const am = loaded.events[3]!
  807. expect((am as SurfaceEvent).surfaceOp).toBe('append')
  808. expect((am as SurfaceEvent).sourceEventSeqs).toEqual([2])
  809. await fiber.dispose()
  810. })
  811. it('persists events with surfaceOp but no sourceEventSeqs (covers null branch in surfaceBindings)', async () => {
  812. const ctx = new Context()
  813. await ctx.plugin(SessionStore)
  814. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  815. const session = ctx.sessions.create(SessionId('surface-noseq'))
  816. session.append('turn/start', { turn: 1 })
  817. session.append('user/message', createUserMessage({
  818. content: [],
  819. source: { kind: 'user' },
  820. }), { surfaceOp: 'append' })
  821. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  822. await ctx.sessions.flush(session)
  823. const loaded = await ctx.sessionPersistence.load(SessionId('surface-noseq'))
  824. expect((loaded.events[1]! as SurfaceEvent).surfaceOp).toBe('append')
  825. expect((loaded.events[1]! as SurfaceEvent).sourceEventSeqs).toBeUndefined()
  826. await fiber.dispose()
  827. })
  828. })