sqlite.spec.ts 37 KB

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