sqlite.spec.ts 42 KB

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