sqlite.spec.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { mkdtemp, rm } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  7. import type { Session, SessionEvent, SessionMeta } from '@deepseek-ai/dsh-session'
  8. import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
  9. import { openDatabase, scanRows, type EventRow } from '../src/schema.ts'
  10. import { runPersistenceContract, meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
  11. const dirs: string[] = []
  12. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  13. async function freshDbPath(): Promise<string> {
  14. const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-'))
  15. dirs.push(dir)
  16. return join(dir, 'sessions.db')
  17. }
  18. /** A context with the session store + SQLite backend, plus a teardown. */
  19. async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
  20. const ctx = new Context()
  21. await ctx.plugin(SessionStore)
  22. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  23. return { ctx, dispose: () => fiber.dispose() }
  24. }
  25. // The payoff: the SAME backend-agnostic contract the JSONL backend runs, now
  26. // proving the SQLite backend satisfies identical semantics.
  27. runPersistenceContract('sqlite', async () => {
  28. const ctx = new Context()
  29. await ctx.plugin(SessionStore)
  30. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  31. return {
  32. persistence: ctx.sessionPersistence,
  33. dispose: async () => { await fiber.dispose() },
  34. }
  35. })
  36. describe('scanRows', () => {
  37. // scanRows works off EventRows (data is a JSON string column); build them from
  38. // SessionEvents so the unit tests read in terms of the event vocabulary.
  39. const rows = (events: SessionEvent[]): EventRow[] =>
  40. events.map(e => ({ seq: e.seq, type: e.type, time: e.time, data: JSON.stringify(e.data) }))
  41. it('preserves the full log when it ends exactly on a turn/end (no torn tail)', () => {
  42. const { preserved, tornFrom } = scanRows(rows(oneTurnLog()))
  43. expect(preserved).toEqual(oneTurnLog())
  44. expect(tornFrom).toBeUndefined()
  45. })
  46. it('PRESERVES the real events of an interrupted turn after the last turn/end', () => {
  47. // turn 1 committed (0..5) + a crashed turn 2 (turn/start 6, step/start 7, no
  48. // close): all 8 rows are intact, so the whole prefix is preserved and there
  49. // is no torn fragment to delete. (load() then synthesizes the closers.)
  50. const withOpenTurn: SessionEvent[] = [
  51. ...oneTurnLog(),
  52. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  53. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  54. ]
  55. const { preserved, tornFrom } = scanRows(rows(withOpenTurn))
  56. expect(preserved.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  57. expect(tornFrom).toBeUndefined()
  58. })
  59. it('preserves the contiguous prefix and flags a torn tail at a seq gap', () => {
  60. // A gap after seq 0 (no committed turn/end): seq 0 is the preserved
  61. // interrupted-turn event; the gap bounds it and marks the torn fragment.
  62. const gapped: SessionEvent[] = [
  63. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  64. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  65. ]
  66. const { preserved, tornFrom } = scanRows(rows(gapped))
  67. expect(preserved.map(e => e.seq)).toEqual([0])
  68. expect(tornFrom).toBe(1)
  69. })
  70. it('an empty log preserves nothing and has no torn tail', () => {
  71. expect(scanRows([])).toEqual({ preserved: [] })
  72. })
  73. it('throws on a seq gap inside the committed region (before the last turn/end)', () => {
  74. const gapped: SessionEvent[] = [
  75. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  76. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  77. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  78. ]
  79. expect(() => scanRows(rows(gapped))).toThrow(/seq gap in committed region/)
  80. })
  81. it('throws on an unparsable row inside the committed region', () => {
  82. const withCorruptCommitted: EventRow[] = [
  83. { seq: 0, type: 'turn/start', time: 1, data: '{not json' }, // corrupt, sits before a turn/end
  84. { seq: 1, type: 'turn/end', time: 2, data: JSON.stringify({ turn: 1, reason: { kind: 'completed' } }) },
  85. ]
  86. expect(() => scanRows(withCorruptCommitted)).toThrow(/unparsable committed event/)
  87. })
  88. it('tolerates an unparsable torn-tail row after the last turn/end', () => {
  89. const withCorruptTail: EventRow[] = [
  90. ...rows(oneTurnLog()),
  91. { seq: 6, type: 'turn/start', time: 7, data: '{not json' }, // torn fragment, no committed turn/end after
  92. ]
  93. const { preserved, tornFrom } = scanRows(withCorruptTail)
  94. expect(preserved).toEqual(oneTurnLog())
  95. expect(tornFrom).toBe(6)
  96. })
  97. })
  98. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  99. it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
  100. const path = await freshDbPath()
  101. const m = meta('crash')
  102. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  103. const ctx1 = new Context()
  104. await ctx1.plugin(SessionStore)
  105. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  106. await ctx1.sessionPersistence.create(m)
  107. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  108. await ctx1.sessionPersistence.append(m.id, [
  109. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  110. { type: 'step/start', seq: 7, time: 8, data: { turn: 2, step: 1 } },
  111. ])
  112. await fiber1.dispose()
  113. // Run 2: load PRESERVES the interrupted turn's real events (a turn can be huge
  114. // — never truncated) and closes the orphaned turn with synthetic boundary
  115. // events: step/end (the step was open) then turn/end {interrupted}.
  116. const ctx2 = new Context()
  117. await ctx2.plugin(SessionStore)
  118. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  119. const loaded = await ctx2.sessionPersistence.load(m.id)
  120. expect(loaded.events.map(e => e.type)).toEqual([
  121. 'turn/start', 'user/message', 'step/start', 'assistant/message', 'step/end', 'turn/end', // turn 1
  122. 'turn/start', 'step/start', 'step/end', 'turn/end', // turn 2: real events + synthetic closers
  123. ])
  124. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  125. const last = loaded.events.at(-1)!
  126. expect(last.type === 'turn/end' && last.data.reason).toEqual({ kind: 'interrupted' })
  127. // load durably closed the turn, so the next append continues at the balanced
  128. // length (seq 10) and a reload round-trips identically.
  129. await ctx2.sessionPersistence.append(m.id, [
  130. { type: 'turn/start', seq: 10, time: 9, data: { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } } },
  131. { type: 'turn/end', seq: 11, time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
  132. ])
  133. const reloaded = await ctx2.sessionPersistence.load(m.id)
  134. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  135. await fiber2.dispose()
  136. })
  137. it('load() durably closes the interrupted turn: the synthetic closers are on disk after load', async () => {
  138. const path = await freshDbPath()
  139. const m = meta('load-closes')
  140. const b1 = await backend(path)
  141. await b1.ctx.sessionPersistence.create(m)
  142. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  143. await b1.dispose()
  144. // Hand-write an interrupted turn (turn/start seq 6, no turn/end).
  145. const db = openDatabase(path)
  146. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  147. .run(m.id, 'turn/start', JSON.stringify({ turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } }))
  148. db.close()
  149. const b2 = await backend(path)
  150. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  151. // turn 2's real turn/start (seq 6) is preserved + a synthetic turn/end (seq 7).
  152. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  153. expect(loaded.events.at(-1)!.type).toBe('turn/end')
  154. // load() is mutating: the synthetic turn/end MUST be on disk so the stored log
  155. // is balanced and the cursor is truthful (contract: load closes, not defers).
  156. const probe = openDatabase(path)
  157. const stored = probe.prepare('SELECT seq, type FROM events WHERE session_id = ? ORDER BY seq').all(m.id) as { seq: number; type: string }[]
  158. probe.close()
  159. expect(stored.map(r => r.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  160. expect(stored.at(-1)!.type).toBe('turn/end')
  161. await b2.dispose()
  162. })
  163. it('all-tail load: a session whose only turn never closed is preserved and closed on load', async () => {
  164. const path = await freshDbPath()
  165. const m = meta('all-tail')
  166. const b1 = await backend(path)
  167. await b1.ctx.sessionPersistence.create(m)
  168. // A first turn that NEVER completed: turn/start + user/message, no turn/end.
  169. await b1.ctx.sessionPersistence.append(m.id, [
  170. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  171. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } } },
  172. ])
  173. expect(await b1.ctx.sessionPersistence.has(m.id)).toBe(true) // materialized
  174. await b1.dispose()
  175. // A fresh backend loads it: the interrupted (only) turn's real events are
  176. // preserved and closed with a synthetic turn/end {interrupted} — NOT
  177. // truncated. The session was materialized, so has()/list() report it present.
  178. const b2 = await backend(path)
  179. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  180. expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  181. expect(loaded.events.at(-1)!.type === 'turn/end' && loaded.events.at(-1)!.data).toMatchObject({ reason: { kind: 'interrupted' } })
  182. expect(await b2.ctx.sessionPersistence.has(m.id)).toBe(true)
  183. expect((await b2.ctx.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  184. await b2.dispose()
  185. })
  186. it('rejects opening a database whose schema version is newer than this build', async () => {
  187. const path = await freshDbPath()
  188. openDatabase(path).close() // stamp user_version = SCHEMA_VERSION
  189. // Bump user_version past what this build supports.
  190. const db = openDatabase(path)
  191. db.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`)
  192. db.close()
  193. expect(() => openDatabase(path)).toThrow(/newer than this build/)
  194. })
  195. it('append snapshots the batch: mutating an event after the call does not corrupt the persisted copy', async () => {
  196. const ctx = new Context()
  197. await ctx.plugin(SessionStore)
  198. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  199. const m = meta('snapshot')
  200. await ctx.sessionPersistence.create(m)
  201. const batch: SessionEvent[] = [
  202. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  203. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } } },
  204. { type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  205. ]
  206. const p = ctx.sessionPersistence.append(m.id, batch)
  207. // Mutate the live array AND an event's data AFTER the call but before it
  208. // drains behind the per-session chain. The snapshot taken at call time must
  209. // shield the persisted copy.
  210. ;(batch[1]!.data as { content: { type: 'text'; text: string }[] }).content[0]!.text = 'HACKED'
  211. batch.push({ type: 'user/message', seq: 3, time: 4, data: { content: [{ type: 'text', text: 'injected' }], source: { kind: 'user' } } })
  212. await p
  213. const loaded = await ctx.sessionPersistence.load(m.id)
  214. expect(loaded.events).toHaveLength(3) // the pushed event was not persisted
  215. const um = loaded.events[1]
  216. expect(um?.type === 'user/message' && (um.data.content[0] as { text: string }).text).toBe('original')
  217. await fiber.dispose()
  218. })
  219. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  220. const path = await freshDbPath()
  221. const m = meta('corrupt-tail')
  222. const b1 = await backend(path)
  223. await b1.ctx.sessionPersistence.create(m)
  224. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  225. await b1.dispose()
  226. // Hand-insert a torn tail row (seq 6, no closing turn/end) whose `data` is
  227. // invalid JSON. The contract: only a parse error in the COMMITTED region is
  228. // unloadable; a torn tail must be discarded. scanRows finds the last
  229. // turn/end on the seq+type columns (never parsing tail `data`), so the
  230. // unparsable row after it bounds the preserved prefix and is deleted by load.
  231. const db = openDatabase(path)
  232. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  233. .run(m.id, 'turn/start', '{not valid json')
  234. db.close()
  235. const b2 = await backend(path)
  236. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  237. expect(loaded.events).toEqual(oneTurnLog()) // torn tail discarded, committed intact (turn 1 already balanced → no closers)
  238. // load physically deleted the corrupt tail row, so a fresh append continues.
  239. await b2.ctx.sessionPersistence.append(m.id, [
  240. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  241. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  242. ])
  243. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  244. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  245. await b2.dispose()
  246. })
  247. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  248. const ctx = new Context()
  249. await ctx.plugin(SessionStore)
  250. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  251. const m = meta('rollback')
  252. await ctx.sessionPersistence.create(m)
  253. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  254. // A batch that re-states an already-stored seq must be rejected and leave
  255. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  256. // inside the transaction → ROLLBACK).
  257. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  258. const loaded = await ctx.sessionPersistence.load(m.id)
  259. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  260. await fiber.dispose()
  261. })
  262. it('persists across separate backend instances over the same file', async () => {
  263. const path = await freshDbPath()
  264. const m = meta('persist', '/proj')
  265. const ctx1 = new Context()
  266. await ctx1.plugin(SessionStore)
  267. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  268. await ctx1.sessionPersistence.create(m)
  269. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  270. await ctx1.sessionPersistence.update(m.id, { title: 'T', firstPrompt: 'hi' })
  271. await fiber1.dispose()
  272. const ctx2 = new Context()
  273. await ctx2.plugin(SessionStore)
  274. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  275. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  276. const loaded = await ctx2.sessionPersistence.load(m.id)
  277. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj', title: 'T', firstPrompt: 'hi' })
  278. expect(loaded.events).toEqual(oneTurnLog())
  279. await fiber2.dispose()
  280. })
  281. it('rejects an unknown format version on load', async () => {
  282. const path = await freshDbPath()
  283. // Materialize a row with version 2 directly via the real schema.
  284. const db = openDatabase(path)
  285. db.prepare('INSERT INTO sessions (id, version, created_at, updated_at) VALUES (?, ?, ?, ?)')
  286. .run('v2', 2, 1, 1)
  287. db.close()
  288. const ctx = new Context()
  289. await ctx.plugin(SessionStore)
  290. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  291. await expect(ctx.sessionPersistence.load(SessionId('v2'))).rejects.toThrow(/version 2/)
  292. await fiber.dispose()
  293. })
  294. it('create rejects a duplicate id (in memory and on a persisted row)', async () => {
  295. const path = await freshDbPath()
  296. const m = meta('dup')
  297. const ctx = new Context()
  298. await ctx.plugin(SessionStore)
  299. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  300. await ctx.sessionPersistence.create(m)
  301. // Same in-memory state.
  302. await expect(ctx.sessionPersistence.create(m)).rejects.toThrow(/already exists/)
  303. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  304. await fiber.dispose()
  305. // A fresh instance over the same file sees the persisted row.
  306. const ctx2 = new Context()
  307. await ctx2.plugin(SessionStore)
  308. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  309. await expect(ctx2.sessionPersistence.create(m)).rejects.toThrow(/already has a persisted row/)
  310. await fiber2.dispose()
  311. })
  312. it('exposes the schema version constant', () => {
  313. expect(SCHEMA_VERSION).toBe(1)
  314. })
  315. })
  316. describe('SessionPersistenceSqlite: write path (session/event → flush)', () => {
  317. function send(session: Session, events: SessionEvent[]): void {
  318. for (const e of events) session.append(e.type, e.data)
  319. }
  320. it('persists a turn appended through the live session on flush', async () => {
  321. const ctx = new Context()
  322. await ctx.plugin(SessionStore)
  323. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  324. const session = ctx.sessions.create('w1')
  325. send(session, oneTurnLog())
  326. await ctx.parallel('session/flush', session)
  327. const loaded = await ctx.sessionPersistence.load(SessionId('w1'))
  328. expect(loaded.events.map(e => e.type)).toEqual(oneTurnLog().map(e => e.type))
  329. await fiber.dispose()
  330. })
  331. it('a resumed session does not re-append its seed', async () => {
  332. const path = await freshDbPath()
  333. // Run 1: persist a full turn through the live session.
  334. const ctx1 = new Context()
  335. await ctx1.plugin(SessionStore)
  336. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  337. const s1 = ctx1.sessions.create('resume')
  338. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  339. await ctx1.parallel('session/flush', s1)
  340. await fiber1.dispose()
  341. // Run 2: reconstruct the live session from the loaded log (seed), then add a
  342. // second turn. The seed must NOT be re-appended (no UNIQUE collision), and
  343. // the second turn continues the seq.
  344. const ctx2 = new Context()
  345. await ctx2.plugin(SessionStore)
  346. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  347. const { events } = await ctx2.sessionPersistence.load(SessionId('resume'))
  348. const s2 = ctx2.sessions.create('resume', { seed: events })
  349. s2.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  350. s2.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  351. await ctx2.parallel('session/flush', s2)
  352. const reloaded = await ctx2.sessionPersistence.load(SessionId('resume'))
  353. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  354. await fiber2.dispose()
  355. })
  356. it('HMR: applying the plugin seeds existing live sessions', async () => {
  357. const ctx = new Context()
  358. await ctx.plugin(SessionStore)
  359. const session = ctx.sessions.create('hmr')
  360. for (const e of oneTurnLog()) session.append(e.type, e.data)
  361. // Plugin applied AFTER the session already has events.
  362. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  363. await ctx.parallel('session/flush', session)
  364. expect(await ctx.sessionPersistence.has(SessionId('hmr'))).toBe(true)
  365. await fiber.dispose()
  366. })
  367. it('dispose drains a pending buffer before closing the database', async () => {
  368. const path = await freshDbPath()
  369. const ctx = new Context()
  370. await ctx.plugin(SessionStore)
  371. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  372. const session = ctx.sessions.create('drain')
  373. for (const e of oneTurnLog()) session.append(e.type, e.data)
  374. // No explicit flush — dispose must drain the buffer.
  375. await fiber.dispose()
  376. const ctx2 = new Context()
  377. await ctx2.plugin(SessionStore)
  378. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  379. expect(await ctx2.sessionPersistence.has(SessionId('drain'))).toBe(true)
  380. await fiber2.dispose()
  381. })
  382. it('rejects a different live session colliding on a persisted id', async () => {
  383. const path = await freshDbPath()
  384. const ctx1 = new Context()
  385. await ctx1.plugin(SessionStore)
  386. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  387. const s1 = ctx1.sessions.create('collide')
  388. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  389. await ctx1.parallel('session/flush', s1)
  390. await fiber1.dispose()
  391. // A fresh, unrelated session reusing the id (no seed) must be rejected.
  392. const ctx2 = new Context()
  393. await ctx2.plugin(SessionStore)
  394. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  395. const s2 = ctx2.sessions.create('collide')
  396. s2.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  397. await expect(ctx2.parallel('session/flush', s2)).rejects.toThrow(/id collision/)
  398. await fiber2.dispose()
  399. })
  400. it('update before the first append keeps the summary in memory and the session lazy', async () => {
  401. const ctx = new Context()
  402. await ctx.plugin(SessionStore)
  403. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  404. const m = meta('lazy-update')
  405. await ctx.sessionPersistence.create(m)
  406. await ctx.sessionPersistence.update(m.id, { title: 'pending' })
  407. // Still lazy: no materialized row yet.
  408. expect(await ctx.sessionPersistence.has(m.id)).toBe(false)
  409. // The first append materializes and carries the pending title.
  410. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  411. const loaded = await ctx.sessionPersistence.load(m.id)
  412. expect(loaded.meta.title).toBe('pending')
  413. await fiber.dispose()
  414. })
  415. })
  416. describe('SessionPersistenceSqlite: edge cases', () => {
  417. it('append of an empty batch is a no-op', async () => {
  418. const { ctx, dispose } = await backend()
  419. const m = meta('empty-batch')
  420. await ctx.sessionPersistence.create(m)
  421. await ctx.sessionPersistence.append(m.id, [])
  422. expect(await ctx.sessionPersistence.has(m.id)).toBe(false) // still lazy
  423. await dispose()
  424. })
  425. it('load rejects a missing session', async () => {
  426. const { ctx, dispose } = await backend()
  427. await expect(ctx.sessionPersistence.load(SessionId('nope'))).rejects.toThrow(/not found/)
  428. await dispose()
  429. })
  430. it('delete of a non-existent session is a no-op', async () => {
  431. const { ctx, dispose } = await backend()
  432. await ctx.sessionPersistence.delete(SessionId('ghost'))
  433. expect(await ctx.sessionPersistence.has(SessionId('ghost'))).toBe(false)
  434. await dispose()
  435. })
  436. it('append adopts a session that exists only in the DB (fresh instance)', async () => {
  437. const path = await freshDbPath()
  438. const m = meta('adopt-append')
  439. const b1 = await backend(path)
  440. await b1.ctx.sessionPersistence.create(m)
  441. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  442. await b1.dispose()
  443. // A fresh instance appends a second turn WITHOUT a prior create/load: append
  444. // must adopt the on-disk row (cursor = stored length) and continue the seq.
  445. const b2 = await backend(path)
  446. await b2.ctx.sessionPersistence.append(m.id, [
  447. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  448. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  449. ])
  450. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  451. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  452. await b2.dispose()
  453. })
  454. it('update adopts a session that exists only in the DB (fresh instance)', async () => {
  455. const path = await freshDbPath()
  456. const m = meta('adopt-update')
  457. const b1 = await backend(path)
  458. await b1.ctx.sessionPersistence.create(m)
  459. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  460. await b1.dispose()
  461. const b2 = await backend(path)
  462. await b2.ctx.sessionPersistence.update(m.id, { title: 'after restart' })
  463. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  464. expect(loaded.meta.title).toBe('after restart')
  465. await b2.dispose()
  466. })
  467. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  468. const path = await freshDbPath()
  469. const m = meta('rollback-insert')
  470. const b1 = await backend(path)
  471. await b1.ctx.sessionPersistence.create(m)
  472. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  473. // A SECOND backend over the same file loads the session first, so it adopts
  474. // cursor 6 (the committed length) into its OWN in-memory state.
  475. const b2 = await backend(path)
  476. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  477. const turn2: SessionEvent[] = [
  478. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  479. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  480. ]
  481. // b1 commits seq 6..7 first.
  482. await b1.ctx.sessionPersistence.append(m.id, turn2)
  483. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  484. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  485. // mid-transaction → ROLLBACK + rethrow.
  486. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  487. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  488. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  489. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  490. await b1.dispose()
  491. await b2.dispose()
  492. })
  493. it('round-trips a header with parentSession (fork lineage)', async () => {
  494. const { ctx, dispose } = await backend()
  495. const m: SessionMeta = { ...meta('child'), parentSession: SessionId('parent') }
  496. await ctx.sessionPersistence.create(m)
  497. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  498. const loaded = await ctx.sessionPersistence.load(m.id)
  499. expect(loaded.meta.parentSession).toBe(SessionId('parent'))
  500. await dispose()
  501. })
  502. it('a fresh live session reusing a previously-loaded id is rejected (ownerless guard)', async () => {
  503. const path = await freshDbPath()
  504. const m = meta('ownerless')
  505. const b1 = await backend(path)
  506. await b1.ctx.sessionPersistence.create(m)
  507. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  508. await b1.dispose()
  509. const b2 = await backend(path)
  510. // load() leaves ownerless state with cursor 6.
  511. await b2.ctx.sessionPersistence.load(m.id)
  512. // A fresh, unrelated live session reusing the id has a shorter/non-matching
  513. // seed → its onCreated must reject rather than graft onto the loaded prefix.
  514. const s = b2.ctx.sessions.create('ownerless')
  515. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  516. await expect(b2.ctx.parallel('session/flush', s)).rejects.toThrow(/id collision/)
  517. await b2.dispose()
  518. })
  519. it('a live session whose seed matches the loaded prefix claims ownerless state and persists the suffix', async () => {
  520. const path = await freshDbPath()
  521. const m = meta('claim')
  522. const b1 = await backend(path)
  523. await b1.ctx.sessionPersistence.create(m)
  524. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  525. await b1.dispose()
  526. const b2 = await backend(path)
  527. const { events } = await b2.ctx.sessionPersistence.load(m.id) // ownerless, cursor 6
  528. // A live session seeded with the loaded log PLUS a new turn claims the state
  529. // and persists only the suffix.
  530. const s = b2.ctx.sessions.create('claim', { seed: [
  531. ...events,
  532. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  533. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  534. ] })
  535. await b2.ctx.parallel('session/flush', s)
  536. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  537. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  538. await b2.dispose()
  539. })
  540. it('an abandoned lazy session (never materialized) releases its id for reuse', async () => {
  541. const { ctx, dispose } = await backend()
  542. const inits = (ctx.sessionPersistence as unknown as { inits: Map<Session, Promise<void>> }).inits
  543. let first!: Session
  544. const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
  545. first = inner.sessions.create('reuse')
  546. }, { inject: ['sessions'] }))
  547. await inits.get(first) // let the lazy create register the state
  548. await firstFiber.dispose() // disposed before any append → never materialized
  549. let reuse!: Session
  550. await ctx.plugin(Object.assign((inner: Context) => {
  551. reuse = inner.sessions.create('reuse')
  552. }, { inject: ['sessions'] }))
  553. await expect(inits.get(reuse)).resolves.toBeUndefined()
  554. reuse.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  555. reuse.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  556. await ctx.parallel('session/flush', reuse)
  557. expect(await ctx.sessionPersistence.has(SessionId('reuse'))).toBe(true)
  558. await dispose()
  559. })
  560. it('does NOT reclaim an id whose abandoned owner still has buffered (unflushed) events', async () => {
  561. const { ctx, dispose } = await backend()
  562. const inits = (ctx.sessionPersistence as unknown as { inits: Map<Session, Promise<void>> }).inits
  563. let first!: Session
  564. const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
  565. first = inner.sessions.create('buffered')
  566. }, { inject: ['sessions'] }))
  567. await inits.get(first)
  568. // Append a turn but do NOT flush — events sit in the write-behind buffer.
  569. first.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  570. first.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  571. await firstFiber.dispose() // disposed before flush; not materialized, buffer pending
  572. let reuse!: Session
  573. await ctx.plugin(Object.assign((inner: Context) => {
  574. reuse = inner.sessions.create('buffered')
  575. }, { inject: ['sessions'] }))
  576. await expect(inits.get(reuse)).rejects.toThrow(/already bound to a different live session/)
  577. await dispose()
  578. })
  579. it('initFor is idempotent: re-emitting session/created does not re-initialize', async () => {
  580. const { ctx, dispose } = await backend()
  581. const session = ctx.sessions.create('idem')
  582. ctx.emit('session/created', session) // second create event for the same object
  583. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  584. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  585. await ctx.parallel('session/flush', session)
  586. expect(await ctx.sessionPersistence.has(SessionId('idem'))).toBe(true)
  587. await dispose()
  588. })
  589. it('a live session claims cursor-0 ownerless state created via the public API and persists its seed', async () => {
  590. const { ctx, dispose } = await backend()
  591. // create() registers ownerless state with cursor 0 (no events yet).
  592. await ctx.sessionPersistence.create(meta('cursor0'))
  593. // A live session reusing that id, seeded with a turn, claims the ownerless
  594. // state (cursor 0 trivially matches any seed) and persists the whole seed.
  595. const s = ctx.sessions.create('cursor0', { seed: [
  596. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  597. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  598. ] })
  599. await ctx.parallel('session/flush', s)
  600. const loaded = await ctx.sessionPersistence.load(SessionId('cursor0'))
  601. expect(loaded.events.map(e => e.seq)).toEqual([0, 1])
  602. await dispose()
  603. })
  604. it('HMR: reloading the backend adopts a still-live, already-materialized session', async () => {
  605. const path = await freshDbPath()
  606. const ctx = new Context()
  607. await ctx.plugin(SessionStore)
  608. // The session lives in its OWN fiber so it survives the backend reload.
  609. let session!: Session
  610. await ctx.plugin(Object.assign((inner: Context) => {
  611. session = inner.sessions.create('hmr-adopt')
  612. }, { inject: ['sessions'] }))
  613. // Backend instance 1 materializes the session on disk.
  614. const backend1 = await ctx.plugin(SessionPersistenceSqlite, { path })
  615. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  616. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })
  617. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  618. await ctx.parallel('session/flush', session)
  619. // Hot-reload: dispose instance 1, plug in instance 2 over the SAME file
  620. // while the session stays live. Instance 2 has an empty states map but the
  621. // row is materialized on disk and is a prefix of the live events — it must
  622. // ADOPT (not reject), and a second turn then persists.
  623. await backend1.dispose()
  624. await ctx.plugin(SessionPersistenceSqlite, { path })
  625. session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  626. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  627. await expect(ctx.parallel('session/flush', session)).resolves.not.toThrow()
  628. const loaded = await ctx.sessionPersistence.load(SessionId('hmr-adopt'))
  629. expect(loaded.events.filter(e => e.type === 'turn/start')).toHaveLength(2)
  630. await ctx.fiber.dispose()
  631. })
  632. it('HMR: adoption persists the live SUFFIX that was ahead of the on-disk prefix', async () => {
  633. const path = await freshDbPath()
  634. const ctx = new Context()
  635. await ctx.plugin(SessionStore)
  636. let session!: Session
  637. await ctx.plugin(Object.assign((inner: Context) => {
  638. session = inner.sessions.create('hmr-suffix')
  639. }, { inject: ['sessions'] }))
  640. const backend1 = await ctx.plugin(SessionPersistenceSqlite, { path })
  641. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  642. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  643. await ctx.parallel('session/flush', session)
  644. // Append turn 2 to the LIVE session, then dispose instance 1 WITHOUT
  645. // flushing turn 2: it is now ONLY in the live session's events.
  646. await backend1.dispose()
  647. session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  648. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  649. // Instance 2 adopts the on-disk prefix (turn 1) and MUST persist the live
  650. // suffix (turn 2) carried in the session's events.
  651. await ctx.plugin(SessionPersistenceSqlite, { path })
  652. await ctx.parallel('session/flush', session)
  653. const loaded = await ctx.sessionPersistence.load(SessionId('hmr-suffix'))
  654. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3])
  655. expect(loaded.events.filter(e => e.type === 'turn/start')).toHaveLength(2)
  656. await ctx.fiber.dispose()
  657. })
  658. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  659. const path = await freshDbPath()
  660. // Instance 1 materializes a session and disposes.
  661. const b1 = await backend(path)
  662. const s1 = b1.ctx.sessions.create('hmr-collide')
  663. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  664. await b1.ctx.parallel('session/flush', s1)
  665. await b1.dispose()
  666. // A fresh context with an UNRELATED live session reusing the id meets a
  667. // materialized row that is NOT a prefix of its events → reject.
  668. const ctx = new Context()
  669. await ctx.plugin(SessionStore)
  670. let session!: Session
  671. await ctx.plugin(Object.assign((inner: Context) => {
  672. session = inner.sessions.create('hmr-collide')
  673. }, { inject: ['sessions'] }))
  674. session.append('turn/start', { turn: 9, trigger: { kind: 'message', source: { kind: 'user' } } })
  675. await ctx.plugin(SessionPersistenceSqlite, { path })
  676. await expect(ctx.parallel('session/flush', session)).rejects.toThrow(/id collision/)
  677. await ctx.fiber.dispose()
  678. })
  679. })