sqlite.spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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 { cutAtLastTurnEnd, openDatabase } 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('cutAtLastTurnEnd', () => {
  37. it('returns the prefix through the last complete turn/end and flags a cut tail', () => {
  38. const log = oneTurnLog()
  39. const withTail: SessionEvent[] = [
  40. ...log,
  41. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  42. { type: 'user/message', seq: 7, time: 8, data: { content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } } },
  43. ]
  44. const { committed, cutTail } = cutAtLastTurnEnd(withTail)
  45. expect(committed).toEqual(log)
  46. expect(cutTail).toBe(true)
  47. })
  48. it('treats a log with no turn/end as fully uncommitted', () => {
  49. const partial: SessionEvent[] = [
  50. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  51. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } } },
  52. ]
  53. expect(cutAtLastTurnEnd(partial)).toEqual({ committed: [], cutTail: true })
  54. })
  55. it('reports no cut when the log ends exactly on a turn/end', () => {
  56. const { committed, cutTail } = cutAtLastTurnEnd(oneTurnLog())
  57. expect(committed).toEqual(oneTurnLog())
  58. expect(cutTail).toBe(false)
  59. })
  60. it('an empty log is committed-empty with no tail', () => {
  61. expect(cutAtLastTurnEnd([])).toEqual({ committed: [], cutTail: false })
  62. })
  63. it('throws on a seq gap inside the committed region', () => {
  64. const gapped: SessionEvent[] = [
  65. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  66. { type: 'step/start', seq: 2, time: 2, data: { turn: 1, step: 1 } }, // seq 1 missing
  67. { type: 'turn/end', seq: 3, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  68. ]
  69. expect(() => cutAtLastTurnEnd(gapped)).toThrow(/seq gap in committed region/)
  70. })
  71. })
  72. describe('SessionPersistenceSqlite: durability and crash semantics', () => {
  73. it('a crash tail (rows after the last turn/end) is excluded and deleted on load', async () => {
  74. const path = await freshDbPath()
  75. const m = meta('crash')
  76. // Run 1: persist a complete turn, then a half-written second turn (no turn/end).
  77. const ctx1 = new Context()
  78. await ctx1.plugin(SessionStore)
  79. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  80. await ctx1.sessionPersistence.create(m)
  81. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  82. await ctx1.sessionPersistence.append(m.id, [
  83. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  84. { type: 'user/message', seq: 7, time: 8, data: { content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } } },
  85. ])
  86. await fiber1.dispose()
  87. // Run 2: load returns only the committed first turn; the tail is gone.
  88. const ctx2 = new Context()
  89. await ctx2.plugin(SessionStore)
  90. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  91. const loaded = await ctx2.sessionPersistence.load(m.id)
  92. expect(loaded.events).toEqual(oneTurnLog())
  93. // The next append continues at seq 6 (the committed length) and the cut
  94. // tail was physically deleted, so there is no UNIQUE collision.
  95. await ctx2.sessionPersistence.append(m.id, [
  96. { type: 'turn/start', seq: 6, time: 9, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  97. { type: 'turn/end', seq: 7, time: 10, data: { turn: 2, reason: { kind: 'completed' } } },
  98. ])
  99. const reloaded = await ctx2.sessionPersistence.load(m.id)
  100. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  101. await fiber2.dispose()
  102. })
  103. it('append snapshots the batch: mutating an event after the call does not corrupt the persisted copy', async () => {
  104. const ctx = new Context()
  105. await ctx.plugin(SessionStore)
  106. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  107. const m = meta('snapshot')
  108. await ctx.sessionPersistence.create(m)
  109. const batch: SessionEvent[] = [
  110. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  111. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } } },
  112. { type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  113. ]
  114. const p = ctx.sessionPersistence.append(m.id, batch)
  115. // Mutate the live array AND an event's data AFTER the call but before it
  116. // drains behind the per-session chain. The snapshot taken at call time must
  117. // shield the persisted copy.
  118. ;(batch[1]!.data as { content: { type: 'text'; text: string }[] }).content[0]!.text = 'HACKED'
  119. batch.push({ type: 'user/message', seq: 3, time: 4, data: { content: [{ type: 'text', text: 'injected' }], source: { kind: 'user' } } })
  120. await p
  121. const loaded = await ctx.sessionPersistence.load(m.id)
  122. expect(loaded.events).toHaveLength(3) // the pushed event was not persisted
  123. const um = loaded.events[1]
  124. expect(um?.type === 'user/message' && (um.data.content[0] as { text: string }).text).toBe('original')
  125. await fiber.dispose()
  126. })
  127. it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
  128. const path = await freshDbPath()
  129. const m = meta('corrupt-tail')
  130. const b1 = await backend(path)
  131. await b1.ctx.sessionPersistence.create(m)
  132. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog()) // committed: seqs 0..5
  133. await b1.dispose()
  134. // Hand-insert an uncommitted tail row (seq 6, no closing turn/end) whose
  135. // `data` is invalid JSON. The contract: only a parse error in the COMMITTED
  136. // region is unloadable; a corrupt tail must be discarded (load cuts at the
  137. // last turn/end using seq+type columns, never parsing tail `data`).
  138. const db = openDatabase(path)
  139. db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, 6, ?, 7, ?)')
  140. .run(m.id, 'turn/start', '{not valid json')
  141. db.close()
  142. const b2 = await backend(path)
  143. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  144. expect(loaded.events).toEqual(oneTurnLog()) // tail discarded, committed intact
  145. // The corrupt tail row was physically deleted, so a fresh append continues.
  146. await b2.ctx.sessionPersistence.append(m.id, [
  147. { type: 'turn/start', seq: 6, time: 8, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  148. { type: 'turn/end', seq: 7, time: 9, data: { turn: 2, reason: { kind: 'completed' } } },
  149. ])
  150. const reloaded = await b2.ctx.sessionPersistence.load(m.id)
  151. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  152. await b2.dispose()
  153. })
  154. it('append rolls back the whole batch on a mid-batch seq collision (transaction)', async () => {
  155. const ctx = new Context()
  156. await ctx.plugin(SessionStore)
  157. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  158. const m = meta('rollback')
  159. await ctx.sessionPersistence.create(m)
  160. await ctx.sessionPersistence.append(m.id, oneTurnLog()) // seqs 0..5
  161. // A batch that re-states an already-stored seq must be rejected and leave
  162. // the stored log unchanged (the UNIQUE (session_id, seq) constraint fires
  163. // inside the transaction → ROLLBACK).
  164. await expect(ctx.sessionPersistence.append(m.id, oneTurnLog())).rejects.toThrow()
  165. const loaded = await ctx.sessionPersistence.load(m.id)
  166. expect(loaded.events).toEqual(oneTurnLog()) // unchanged
  167. await fiber.dispose()
  168. })
  169. it('persists across separate backend instances over the same file', async () => {
  170. const path = await freshDbPath()
  171. const m = meta('persist', '/proj')
  172. const ctx1 = new Context()
  173. await ctx1.plugin(SessionStore)
  174. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  175. await ctx1.sessionPersistence.create(m)
  176. await ctx1.sessionPersistence.append(m.id, oneTurnLog())
  177. await ctx1.sessionPersistence.update(m.id, { title: 'T', firstPrompt: 'hi' })
  178. await fiber1.dispose()
  179. const ctx2 = new Context()
  180. await ctx2.plugin(SessionStore)
  181. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  182. expect((await ctx2.sessionPersistence.list()).map(x => x.id)).toContain(m.id)
  183. const loaded = await ctx2.sessionPersistence.load(m.id)
  184. expect(loaded.meta).toMatchObject({ id: m.id, cwd: '/proj', title: 'T', firstPrompt: 'hi' })
  185. expect(loaded.events).toEqual(oneTurnLog())
  186. await fiber2.dispose()
  187. })
  188. it('rejects an unknown format version on load', async () => {
  189. const path = await freshDbPath()
  190. // Materialize a row with version 2 directly via the real schema.
  191. const db = openDatabase(path)
  192. db.prepare('INSERT INTO sessions (id, version, created_at, updated_at, materialized) VALUES (?, ?, ?, ?, 1)')
  193. .run('v2', 2, 1, 1)
  194. db.close()
  195. const ctx = new Context()
  196. await ctx.plugin(SessionStore)
  197. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  198. await expect(ctx.sessionPersistence.load(SessionId('v2'))).rejects.toThrow(/version 2/)
  199. await fiber.dispose()
  200. })
  201. it('create rejects a duplicate id (in memory and on a persisted row)', async () => {
  202. const path = await freshDbPath()
  203. const m = meta('dup')
  204. const ctx = new Context()
  205. await ctx.plugin(SessionStore)
  206. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  207. await ctx.sessionPersistence.create(m)
  208. // Same in-memory state.
  209. await expect(ctx.sessionPersistence.create(m)).rejects.toThrow(/already exists/)
  210. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  211. await fiber.dispose()
  212. // A fresh instance over the same file sees the persisted row.
  213. const ctx2 = new Context()
  214. await ctx2.plugin(SessionStore)
  215. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  216. await expect(ctx2.sessionPersistence.create(m)).rejects.toThrow(/already has a persisted row/)
  217. await fiber2.dispose()
  218. })
  219. it('exposes the schema version constant', () => {
  220. expect(SCHEMA_VERSION).toBe(1)
  221. })
  222. })
  223. describe('SessionPersistenceSqlite: write path (session/event → flush)', () => {
  224. function send(session: Session, events: SessionEvent[]): void {
  225. for (const e of events) session.append(e.type, e.data)
  226. }
  227. it('persists a turn appended through the live session on flush', async () => {
  228. const ctx = new Context()
  229. await ctx.plugin(SessionStore)
  230. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  231. const session = ctx.sessions.create('w1')
  232. send(session, oneTurnLog())
  233. await ctx.parallel('session/flush', session)
  234. const loaded = await ctx.sessionPersistence.load(SessionId('w1'))
  235. expect(loaded.events.map(e => e.type)).toEqual(oneTurnLog().map(e => e.type))
  236. await fiber.dispose()
  237. })
  238. it('a resumed session does not re-append its seed', async () => {
  239. const path = await freshDbPath()
  240. // Run 1: persist a full turn through the live session.
  241. const ctx1 = new Context()
  242. await ctx1.plugin(SessionStore)
  243. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  244. const s1 = ctx1.sessions.create('resume')
  245. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  246. await ctx1.parallel('session/flush', s1)
  247. await fiber1.dispose()
  248. // Run 2: reconstruct the live session from the loaded log (seed), then add a
  249. // second turn. The seed must NOT be re-appended (no UNIQUE collision), and
  250. // the second turn continues the seq.
  251. const ctx2 = new Context()
  252. await ctx2.plugin(SessionStore)
  253. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  254. const { events } = await ctx2.sessionPersistence.load(SessionId('resume'))
  255. const s2 = ctx2.sessions.create('resume', { seed: events })
  256. s2.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  257. s2.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  258. await ctx2.parallel('session/flush', s2)
  259. const reloaded = await ctx2.sessionPersistence.load(SessionId('resume'))
  260. expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  261. await fiber2.dispose()
  262. })
  263. it('HMR: applying the plugin seeds existing live sessions', async () => {
  264. const ctx = new Context()
  265. await ctx.plugin(SessionStore)
  266. const session = ctx.sessions.create('hmr')
  267. for (const e of oneTurnLog()) session.append(e.type, e.data)
  268. // Plugin applied AFTER the session already has events.
  269. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  270. await ctx.parallel('session/flush', session)
  271. expect(await ctx.sessionPersistence.has(SessionId('hmr'))).toBe(true)
  272. await fiber.dispose()
  273. })
  274. it('dispose drains a pending buffer before closing the database', async () => {
  275. const path = await freshDbPath()
  276. const ctx = new Context()
  277. await ctx.plugin(SessionStore)
  278. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
  279. const session = ctx.sessions.create('drain')
  280. for (const e of oneTurnLog()) session.append(e.type, e.data)
  281. // No explicit flush — dispose must drain the buffer.
  282. await fiber.dispose()
  283. const ctx2 = new Context()
  284. await ctx2.plugin(SessionStore)
  285. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  286. expect(await ctx2.sessionPersistence.has(SessionId('drain'))).toBe(true)
  287. await fiber2.dispose()
  288. })
  289. it('rejects a different live session colliding on a persisted id', async () => {
  290. const path = await freshDbPath()
  291. const ctx1 = new Context()
  292. await ctx1.plugin(SessionStore)
  293. const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
  294. const s1 = ctx1.sessions.create('collide')
  295. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  296. await ctx1.parallel('session/flush', s1)
  297. await fiber1.dispose()
  298. // A fresh, unrelated session reusing the id (no seed) must be rejected.
  299. const ctx2 = new Context()
  300. await ctx2.plugin(SessionStore)
  301. const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
  302. const s2 = ctx2.sessions.create('collide')
  303. s2.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  304. await expect(ctx2.parallel('session/flush', s2)).rejects.toThrow(/id collision/)
  305. await fiber2.dispose()
  306. })
  307. it('update before the first append keeps the summary in memory and the session lazy', async () => {
  308. const ctx = new Context()
  309. await ctx.plugin(SessionStore)
  310. const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
  311. const m = meta('lazy-update')
  312. await ctx.sessionPersistence.create(m)
  313. await ctx.sessionPersistence.update(m.id, { title: 'pending' })
  314. // Still lazy: no materialized row yet.
  315. expect(await ctx.sessionPersistence.has(m.id)).toBe(false)
  316. // The first append materializes and carries the pending title.
  317. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  318. const loaded = await ctx.sessionPersistence.load(m.id)
  319. expect(loaded.meta.title).toBe('pending')
  320. await fiber.dispose()
  321. })
  322. })
  323. describe('SessionPersistenceSqlite: edge cases', () => {
  324. it('append of an empty batch is a no-op', async () => {
  325. const { ctx, dispose } = await backend()
  326. const m = meta('empty-batch')
  327. await ctx.sessionPersistence.create(m)
  328. await ctx.sessionPersistence.append(m.id, [])
  329. expect(await ctx.sessionPersistence.has(m.id)).toBe(false) // still lazy
  330. await dispose()
  331. })
  332. it('load rejects a missing session', async () => {
  333. const { ctx, dispose } = await backend()
  334. await expect(ctx.sessionPersistence.load(SessionId('nope'))).rejects.toThrow(/not found/)
  335. await dispose()
  336. })
  337. it('delete of a non-existent session is a no-op', async () => {
  338. const { ctx, dispose } = await backend()
  339. await ctx.sessionPersistence.delete(SessionId('ghost'))
  340. expect(await ctx.sessionPersistence.has(SessionId('ghost'))).toBe(false)
  341. await dispose()
  342. })
  343. it('append adopts a session that exists only in the DB (fresh instance)', async () => {
  344. const path = await freshDbPath()
  345. const m = meta('adopt-append')
  346. const b1 = await backend(path)
  347. await b1.ctx.sessionPersistence.create(m)
  348. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  349. await b1.dispose()
  350. // A fresh instance appends a second turn WITHOUT a prior create/load: append
  351. // must adopt the on-disk row (cursor = stored length) and continue the seq.
  352. const b2 = await backend(path)
  353. await b2.ctx.sessionPersistence.append(m.id, [
  354. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  355. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  356. ])
  357. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  358. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  359. await b2.dispose()
  360. })
  361. it('update adopts a session that exists only in the DB (fresh instance)', async () => {
  362. const path = await freshDbPath()
  363. const m = meta('adopt-update')
  364. const b1 = await backend(path)
  365. await b1.ctx.sessionPersistence.create(m)
  366. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  367. await b1.dispose()
  368. const b2 = await backend(path)
  369. await b2.ctx.sessionPersistence.update(m.id, { title: 'after restart' })
  370. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  371. expect(loaded.meta.title).toBe('after restart')
  372. await b2.dispose()
  373. })
  374. it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
  375. const path = await freshDbPath()
  376. const m = meta('rollback-insert')
  377. const b1 = await backend(path)
  378. await b1.ctx.sessionPersistence.create(m)
  379. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  380. // A SECOND backend over the same file loads the session first, so it adopts
  381. // cursor 6 (the committed length) into its OWN in-memory state.
  382. const b2 = await backend(path)
  383. await b2.ctx.sessionPersistence.load(m.id) // cursor 6 in b2
  384. const turn2: SessionEvent[] = [
  385. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  386. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  387. ]
  388. // b1 commits seq 6..7 first.
  389. await b1.ctx.sessionPersistence.append(m.id, turn2)
  390. // b2 still thinks its cursor is 6, so this batch passes the contiguity check
  391. // but its INSERT of seq 6 hits the UNIQUE (session_id, seq) constraint
  392. // mid-transaction → ROLLBACK + rethrow.
  393. await expect(b2.ctx.sessionPersistence.append(m.id, turn2)).rejects.toThrow(/UNIQUE/)
  394. // b1's turn is intact; b2's rolled-back attempt left nothing extra.
  395. const loaded = await b1.ctx.sessionPersistence.load(m.id)
  396. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  397. await b1.dispose()
  398. await b2.dispose()
  399. })
  400. it('round-trips a header with parentSession (fork lineage)', async () => {
  401. const { ctx, dispose } = await backend()
  402. const m: SessionMeta = { ...meta('child'), parentSession: SessionId('parent') }
  403. await ctx.sessionPersistence.create(m)
  404. await ctx.sessionPersistence.append(m.id, oneTurnLog())
  405. const loaded = await ctx.sessionPersistence.load(m.id)
  406. expect(loaded.meta.parentSession).toBe(SessionId('parent'))
  407. await dispose()
  408. })
  409. it('a fresh live session reusing a previously-loaded id is rejected (ownerless guard)', async () => {
  410. const path = await freshDbPath()
  411. const m = meta('ownerless')
  412. const b1 = await backend(path)
  413. await b1.ctx.sessionPersistence.create(m)
  414. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  415. await b1.dispose()
  416. const b2 = await backend(path)
  417. // load() leaves ownerless state with cursor 6.
  418. await b2.ctx.sessionPersistence.load(m.id)
  419. // A fresh, unrelated live session reusing the id has a shorter/non-matching
  420. // seed → its onCreated must reject rather than graft onto the loaded prefix.
  421. const s = b2.ctx.sessions.create('ownerless')
  422. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  423. await expect(b2.ctx.parallel('session/flush', s)).rejects.toThrow(/id collision/)
  424. await b2.dispose()
  425. })
  426. it('a live session whose seed matches the loaded prefix claims ownerless state and persists the suffix', async () => {
  427. const path = await freshDbPath()
  428. const m = meta('claim')
  429. const b1 = await backend(path)
  430. await b1.ctx.sessionPersistence.create(m)
  431. await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
  432. await b1.dispose()
  433. const b2 = await backend(path)
  434. const { events } = await b2.ctx.sessionPersistence.load(m.id) // ownerless, cursor 6
  435. // A live session seeded with the loaded log PLUS a new turn claims the state
  436. // and persists only the suffix.
  437. const s = b2.ctx.sessions.create('claim', { seed: [
  438. ...events,
  439. { type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
  440. { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
  441. ] })
  442. await b2.ctx.parallel('session/flush', s)
  443. const loaded = await b2.ctx.sessionPersistence.load(m.id)
  444. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
  445. await b2.dispose()
  446. })
  447. it('an abandoned lazy session (never materialized) releases its id for reuse', async () => {
  448. const { ctx, dispose } = await backend()
  449. const inits = (ctx.sessionPersistence as unknown as { inits: Map<Session, Promise<void>> }).inits
  450. let first!: Session
  451. const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
  452. first = inner.sessions.create('reuse')
  453. }, { inject: ['sessions'] }))
  454. await inits.get(first) // let the lazy create register the state
  455. await firstFiber.dispose() // disposed before any append → never materialized
  456. let reuse!: Session
  457. await ctx.plugin(Object.assign((inner: Context) => {
  458. reuse = inner.sessions.create('reuse')
  459. }, { inject: ['sessions'] }))
  460. await expect(inits.get(reuse)).resolves.toBeUndefined()
  461. reuse.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  462. reuse.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  463. await ctx.parallel('session/flush', reuse)
  464. expect(await ctx.sessionPersistence.has(SessionId('reuse'))).toBe(true)
  465. await dispose()
  466. })
  467. it('does NOT reclaim an id whose abandoned owner still has buffered (unflushed) events', async () => {
  468. const { ctx, dispose } = await backend()
  469. const inits = (ctx.sessionPersistence as unknown as { inits: Map<Session, Promise<void>> }).inits
  470. let first!: Session
  471. const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
  472. first = inner.sessions.create('buffered')
  473. }, { inject: ['sessions'] }))
  474. await inits.get(first)
  475. // Append a turn but do NOT flush — events sit in the write-behind buffer.
  476. first.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  477. first.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  478. await firstFiber.dispose() // disposed before flush; not materialized, buffer pending
  479. let reuse!: Session
  480. await ctx.plugin(Object.assign((inner: Context) => {
  481. reuse = inner.sessions.create('buffered')
  482. }, { inject: ['sessions'] }))
  483. await expect(inits.get(reuse)).rejects.toThrow(/already bound to a different live session/)
  484. await dispose()
  485. })
  486. it('initFor is idempotent: re-emitting session/created does not re-initialize', async () => {
  487. const { ctx, dispose } = await backend()
  488. const session = ctx.sessions.create('idem')
  489. ctx.emit('session/created', session) // second create event for the same object
  490. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  491. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  492. await ctx.parallel('session/flush', session)
  493. expect(await ctx.sessionPersistence.has(SessionId('idem'))).toBe(true)
  494. await dispose()
  495. })
  496. it('a live session claims cursor-0 ownerless state created via the public API and persists its seed', async () => {
  497. const { ctx, dispose } = await backend()
  498. // create() registers ownerless state with cursor 0 (no events yet).
  499. await ctx.sessionPersistence.create(meta('cursor0'))
  500. // A live session reusing that id, seeded with a turn, claims the ownerless
  501. // state (cursor 0 trivially matches any seed) and persists the whole seed.
  502. const s = ctx.sessions.create('cursor0', { seed: [
  503. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  504. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  505. ] })
  506. await ctx.parallel('session/flush', s)
  507. const loaded = await ctx.sessionPersistence.load(SessionId('cursor0'))
  508. expect(loaded.events.map(e => e.seq)).toEqual([0, 1])
  509. await dispose()
  510. })
  511. it('HMR: reloading the backend adopts a still-live, already-materialized session', async () => {
  512. const path = await freshDbPath()
  513. const ctx = new Context()
  514. await ctx.plugin(SessionStore)
  515. // The session lives in its OWN fiber so it survives the backend reload.
  516. let session!: Session
  517. await ctx.plugin(Object.assign((inner: Context) => {
  518. session = inner.sessions.create('hmr-adopt')
  519. }, { inject: ['sessions'] }))
  520. // Backend instance 1 materializes the session on disk.
  521. const backend1 = await ctx.plugin(SessionPersistenceSqlite, { path })
  522. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  523. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })
  524. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  525. await ctx.parallel('session/flush', session)
  526. // Hot-reload: dispose instance 1, plug in instance 2 over the SAME file
  527. // while the session stays live. Instance 2 has an empty states map but the
  528. // row is materialized on disk and is a prefix of the live events — it must
  529. // ADOPT (not reject), and a second turn then persists.
  530. await backend1.dispose()
  531. await ctx.plugin(SessionPersistenceSqlite, { path })
  532. session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  533. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  534. await expect(ctx.parallel('session/flush', session)).resolves.not.toThrow()
  535. const loaded = await ctx.sessionPersistence.load(SessionId('hmr-adopt'))
  536. expect(loaded.events.filter(e => e.type === 'turn/start')).toHaveLength(2)
  537. await ctx.fiber.dispose()
  538. })
  539. it('HMR: adoption persists the live SUFFIX that was ahead of the on-disk prefix', async () => {
  540. const path = await freshDbPath()
  541. const ctx = new Context()
  542. await ctx.plugin(SessionStore)
  543. let session!: Session
  544. await ctx.plugin(Object.assign((inner: Context) => {
  545. session = inner.sessions.create('hmr-suffix')
  546. }, { inject: ['sessions'] }))
  547. const backend1 = await ctx.plugin(SessionPersistenceSqlite, { path })
  548. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  549. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  550. await ctx.parallel('session/flush', session)
  551. // Append turn 2 to the LIVE session, then dispose instance 1 WITHOUT
  552. // flushing turn 2: it is now ONLY in the live session's events.
  553. await backend1.dispose()
  554. session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  555. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  556. // Instance 2 adopts the on-disk prefix (turn 1) and MUST persist the live
  557. // suffix (turn 2) carried in the session's events.
  558. await ctx.plugin(SessionPersistenceSqlite, { path })
  559. await ctx.parallel('session/flush', session)
  560. const loaded = await ctx.sessionPersistence.load(SessionId('hmr-suffix'))
  561. expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3])
  562. expect(loaded.events.filter(e => e.type === 'turn/start')).toHaveLength(2)
  563. await ctx.fiber.dispose()
  564. })
  565. it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
  566. const path = await freshDbPath()
  567. // Instance 1 materializes a session and disposes.
  568. const b1 = await backend(path)
  569. const s1 = b1.ctx.sessions.create('hmr-collide')
  570. for (const e of oneTurnLog()) s1.append(e.type, e.data)
  571. await b1.ctx.parallel('session/flush', s1)
  572. await b1.dispose()
  573. // A fresh context with an UNRELATED live session reusing the id meets a
  574. // materialized row that is NOT a prefix of its events → reject.
  575. const ctx = new Context()
  576. await ctx.plugin(SessionStore)
  577. let session!: Session
  578. await ctx.plugin(Object.assign((inner: Context) => {
  579. session = inner.sessions.create('hmr-collide')
  580. }, { inject: ['sessions'] }))
  581. session.append('turn/start', { turn: 9, trigger: { kind: 'message', source: { kind: 'user' } } })
  582. await ctx.plugin(SessionPersistenceSqlite, { path })
  583. await expect(ctx.parallel('session/flush', session)).rejects.toThrow(/id collision/)
  584. await ctx.fiber.dispose()
  585. })
  586. })