sqlite.spec.ts 42 KB

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