mirror of
https://github.com/deepseek-ai/deepseek-harness
synced 2026-08-15 21:04:50 +00:00
refactor(session-persistence): extract a shared write coordinator
The JSONL and SQLite backends were byte-identical (or same-algorithm) for ALL of their write-path orchestration — the four maps (states/buffers/chains/inits), installWritePath, initFor, onCreated's four adoption cases, flush, drain, serialize, adopt/adoptLivePrefix, assertVersion, and the create/append/load/ has/delete skeletons. Only the storage primitives (write bytes vs INSERT rows) differed, so every fix landed twice. Extract that orchestration into a PersistenceCoordinator in the seam package. Each backend composes one (new PersistenceCoordinator(ctx, this)), implements a small PersistenceBackend hook interface (loadStored, loadLive, appendBatch, commitRepair, deleteStored, list, optional close), and delegates its six public service methods to it. Composition, not inheritance — a backend exposes only the hooks, can't reach the coordinator's private state, and the public SessionPersistence API is unchanged so a third-party backend may still implement it directly. The crash-repair torn-tail token is OPAQUE: the coordinator computes the synthetic closers (it owns interruptedTurnClosers) but only tests `tornMarker !== undefined` and round-trips it to commitRepair, never inspecting it (JSONL = byte offset, SQLite = seq). loadStored vs loadLive stay distinct so HMR adoption is cwd-scoped (a same-id log at a different cwd is a collision, not a resume). appendBatch carries meta so lazy-materialize + first-batch commit atomically (no separate materialize hook). Tests: the duplicated orchestration tests (adoption, HMR, collision, dispose-drain, crash-tail) move into one runCoordinatorContract suite run once per backend (memory + jsonl + sqlite) via hook fixtures; per-backend specs keep only storage mechanics. A through-coordinator torn-tail test per real backend keeps the commitRepair-with-marker branch covered under the 100% gate. Net -112 lines (the dedup outweighs the new coordinator + shared suite); 100% coverage; backends shrank ~1200 lines of duplicated churn. Migrates the write-coordinator RFC proposed -> implemented.
This commit is contained in:
@@ -3,11 +3,12 @@ import { Context } from 'cordis'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
import { openDatabase, scanRows, type EventRow } from '../src/schema.ts'
|
||||
import { runPersistenceContract, meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
|
||||
import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts'
|
||||
|
||||
const dirs: string[] = []
|
||||
afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
|
||||
@@ -38,6 +39,31 @@ runPersistenceContract('sqlite', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
// Run the shared coordinator orchestration suite against the real SQLite backend.
|
||||
// A FILE-backed db (not :memory:) is the shared storage scope so two mounted
|
||||
// instances see the same rows (HMR/reload). `corruptTail` INSERTs a row past the
|
||||
// committed seq whose `data` is invalid JSON — a never-committed torn tail that
|
||||
// drives the coordinator's commitRepair-with-tornMarker branch over real db rows.
|
||||
runCoordinatorContract('sqlite', async (): Promise<CoordinatorFixture> => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'dsh-sqlite-coord-'))
|
||||
const path = join(dir, 'sessions.db')
|
||||
return {
|
||||
mount: async ctx => ctx.plugin(SessionPersistenceSqlite, { path }),
|
||||
corruptTail: async (id) => {
|
||||
// A row past the committed region whose `data` does not parse: scanRows
|
||||
// bounds the preserved prefix at it and returns its seq as tornFrom, which
|
||||
// the backend surfaces to the coordinator as the tornMarker to delete from.
|
||||
const db = openDatabase(path)
|
||||
const next = (db.prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM events WHERE session_id = ?')
|
||||
.get(id) as { n: number }).n
|
||||
db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
|
||||
.run(id, next, 'assistant/chunk', 99, '{not valid json')
|
||||
db.close()
|
||||
},
|
||||
cleanup: async () => { await rm(dir, { recursive: true, force: true }) },
|
||||
}
|
||||
})
|
||||
|
||||
describe('scanRows', () => {
|
||||
// scanRows works off EventRows (data is a JSON string column); build them from
|
||||
// SessionEvents so the unit tests read in terms of the event vocabulary.
|
||||
@@ -108,35 +134,6 @@ describe('scanRows', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('SessionPersistenceSqlite: HMR adoption', () => {
|
||||
it('does not crash-repair an active open turn as interrupted', async () => {
|
||||
const path = await freshDbPath()
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const first = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
const session = ctx.sessions.create('hmr-open', { meta: { cwd: '/hmr' } })
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('step/start', { turn: 1, step: 1 })
|
||||
await ctx.parallel('session/flush', session)
|
||||
|
||||
await first.dispose()
|
||||
const db = openDatabase(path)
|
||||
db.prepare('INSERT INTO events (session_id, seq, type, time, data) VALUES (?, ?, ?, ?, ?)')
|
||||
.run('hmr-open', 2, 'step/end', 2, '{"torn":')
|
||||
db.close()
|
||||
const second = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
session.append('step/end', { turn: 1, step: 1 })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await ctx.parallel('session/flush', session)
|
||||
|
||||
const loaded = await ctx.sessionPersistence.load(SessionId('hmr-open'))
|
||||
expect(loaded.events.map(e => e.type)).toEqual(['turn/start', 'step/start', 'step/end', 'turn/end'])
|
||||
expect(loaded.events.at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'completed' } } })
|
||||
await second.dispose()
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SessionPersistenceSqlite: durability and crash semantics', () => {
|
||||
it('an interrupted turn (rows after the last turn/end) is PRESERVED and closed during load', async () => {
|
||||
const path = await freshDbPath()
|
||||
@@ -251,31 +248,6 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
|
||||
expect(() => openDatabase(olderPath)).toThrow(/incompatible with this build/)
|
||||
})
|
||||
|
||||
it('append snapshots the batch: mutating an event after the call does not corrupt the persisted copy', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
|
||||
const m = meta('snapshot')
|
||||
await ctx.sessionPersistence.create(m)
|
||||
const batch: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
|
||||
{ type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } } },
|
||||
{ type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
|
||||
]
|
||||
const p = ctx.sessionPersistence.append(m.id, batch)
|
||||
// Mutate the live array AND an event's data AFTER the call but before it
|
||||
// drains behind the per-session chain. The snapshot taken at call time must
|
||||
// shield the persisted copy.
|
||||
;(batch[1]!.data as { content: { type: 'text'; text: string }[] }).content[0]!.text = 'HACKED'
|
||||
batch.push({ type: 'user/message', seq: 3, time: 4, data: { content: [{ type: 'text', text: 'injected' }], source: { kind: 'user' } } })
|
||||
await p
|
||||
const loaded = await ctx.sessionPersistence.load(m.id)
|
||||
expect(loaded.events).toHaveLength(3) // the pushed event was not persisted
|
||||
const um = loaded.events[1]
|
||||
expect(um?.type === 'user/message' && (um.data.content[0] as { text: string }).text).toBe('original')
|
||||
await fiber.dispose()
|
||||
})
|
||||
|
||||
it('a corrupt-JSON row in the uncommitted tail is discarded on load, not unloadable', async () => {
|
||||
const path = await freshDbPath()
|
||||
const m = meta('corrupt-tail')
|
||||
@@ -344,183 +316,12 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
|
||||
await fiber2.dispose()
|
||||
})
|
||||
|
||||
it('rejects an unknown format version on load', async () => {
|
||||
const path = await freshDbPath()
|
||||
// Materialize a row with version 2 directly via the real schema.
|
||||
const db = openDatabase(path)
|
||||
db.prepare('INSERT INTO sessions (id, version, created_at) VALUES (?, ?, ?)')
|
||||
.run('v2', 2, 1)
|
||||
db.close()
|
||||
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
await expect(ctx.sessionPersistence.load(SessionId('v2'))).rejects.toThrow(/version 2/)
|
||||
await fiber.dispose()
|
||||
})
|
||||
|
||||
it('create rejects a duplicate id (in memory and on a persisted row)', async () => {
|
||||
const path = await freshDbPath()
|
||||
const m = meta('dup')
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
await ctx.sessionPersistence.create(m)
|
||||
// Same in-memory state.
|
||||
await expect(ctx.sessionPersistence.create(m)).rejects.toThrow(/already exists/)
|
||||
await ctx.sessionPersistence.append(m.id, oneTurnLog())
|
||||
await fiber.dispose()
|
||||
|
||||
// A fresh instance over the same file sees the persisted row.
|
||||
const ctx2 = new Context()
|
||||
await ctx2.plugin(SessionStore)
|
||||
const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
|
||||
await expect(ctx2.sessionPersistence.create(m)).rejects.toThrow(/already has a persisted row/)
|
||||
await fiber2.dispose()
|
||||
})
|
||||
|
||||
it('exposes the schema version constant', () => {
|
||||
expect(SCHEMA_VERSION).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SessionPersistenceSqlite: write path (session/event → flush)', () => {
|
||||
function send(session: Session, events: SessionEvent[]): void {
|
||||
for (const e of events) session.append(e.type, e.data)
|
||||
}
|
||||
|
||||
it('persists a turn appended through the live session on flush', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
|
||||
const session = ctx.sessions.create('w1')
|
||||
send(session, oneTurnLog())
|
||||
await ctx.parallel('session/flush', session)
|
||||
const loaded = await ctx.sessionPersistence.load(SessionId('w1'))
|
||||
expect(loaded.events.map(e => e.type)).toEqual(oneTurnLog().map(e => e.type))
|
||||
await fiber.dispose()
|
||||
})
|
||||
|
||||
it('a resumed session does not re-append its seed', async () => {
|
||||
const path = await freshDbPath()
|
||||
// Run 1: persist a full turn through the live session.
|
||||
const ctx1 = new Context()
|
||||
await ctx1.plugin(SessionStore)
|
||||
const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
|
||||
const s1 = ctx1.sessions.create('resume')
|
||||
for (const e of oneTurnLog()) s1.append(e.type, e.data)
|
||||
await ctx1.parallel('session/flush', s1)
|
||||
await fiber1.dispose()
|
||||
|
||||
// Run 2: reconstruct the live session from the loaded log (seed), then add a
|
||||
// second turn. The seed must NOT be re-appended (no UNIQUE collision), and
|
||||
// the second turn continues the seq.
|
||||
const ctx2 = new Context()
|
||||
await ctx2.plugin(SessionStore)
|
||||
const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
|
||||
const { events } = await ctx2.sessionPersistence.load(SessionId('resume'))
|
||||
const s2 = ctx2.sessions.create('resume', { seed: events })
|
||||
s2.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
s2.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
|
||||
await ctx2.parallel('session/flush', s2)
|
||||
const reloaded = await ctx2.sessionPersistence.load(SessionId('resume'))
|
||||
expect(reloaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
|
||||
await fiber2.dispose()
|
||||
})
|
||||
|
||||
it('HMR: applying the plugin seeds existing live sessions', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const session = ctx.sessions.create('hmr')
|
||||
for (const e of oneTurnLog()) session.append(e.type, e.data)
|
||||
// Plugin applied AFTER the session already has events.
|
||||
const fiber = await ctx.plugin(SessionPersistenceSqlite, { path: ':memory:' })
|
||||
await ctx.parallel('session/flush', session)
|
||||
expect(await ctx.sessionPersistence.has(SessionId('hmr'))).toBe(true)
|
||||
await fiber.dispose()
|
||||
})
|
||||
|
||||
it('dispose drains a pending buffer before closing the database', async () => {
|
||||
const path = await freshDbPath()
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const fiber = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
const session = ctx.sessions.create('drain')
|
||||
for (const e of oneTurnLog()) session.append(e.type, e.data)
|
||||
// No explicit flush — dispose must drain the buffer.
|
||||
await fiber.dispose()
|
||||
|
||||
const ctx2 = new Context()
|
||||
await ctx2.plugin(SessionStore)
|
||||
const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
|
||||
expect(await ctx2.sessionPersistence.has(SessionId('drain'))).toBe(true)
|
||||
await fiber2.dispose()
|
||||
})
|
||||
|
||||
it('rejects a different live session colliding on a persisted id', async () => {
|
||||
const path = await freshDbPath()
|
||||
const ctx1 = new Context()
|
||||
await ctx1.plugin(SessionStore)
|
||||
const fiber1 = await ctx1.plugin(SessionPersistenceSqlite, { path })
|
||||
const s1 = ctx1.sessions.create('collide')
|
||||
for (const e of oneTurnLog()) s1.append(e.type, e.data)
|
||||
await ctx1.parallel('session/flush', s1)
|
||||
await fiber1.dispose()
|
||||
|
||||
// A fresh, unrelated session reusing the id (no seed) must be rejected.
|
||||
const ctx2 = new Context()
|
||||
await ctx2.plugin(SessionStore)
|
||||
const fiber2 = await ctx2.plugin(SessionPersistenceSqlite, { path })
|
||||
const s2 = ctx2.sessions.create('collide')
|
||||
s2.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
await expect(ctx2.parallel('session/flush', s2)).rejects.toThrow(/id collision/)
|
||||
await fiber2.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SessionPersistenceSqlite: edge cases', () => {
|
||||
it('append of an empty batch is a no-op', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
const m = meta('empty-batch')
|
||||
await ctx.sessionPersistence.create(m)
|
||||
await ctx.sessionPersistence.append(m.id, [])
|
||||
expect(await ctx.sessionPersistence.has(m.id)).toBe(false) // still lazy
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('load rejects a missing session', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
await expect(ctx.sessionPersistence.load(SessionId('nope'))).rejects.toThrow(/not found/)
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('delete of a non-existent session is a no-op', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
await ctx.sessionPersistence.delete(SessionId('ghost'))
|
||||
expect(await ctx.sessionPersistence.has(SessionId('ghost'))).toBe(false)
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('append adopts a session that exists only in the DB (fresh instance)', async () => {
|
||||
const path = await freshDbPath()
|
||||
const m = meta('adopt-append')
|
||||
const b1 = await backend(path)
|
||||
await b1.ctx.sessionPersistence.create(m)
|
||||
await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
|
||||
await b1.dispose()
|
||||
|
||||
// A fresh instance appends a second turn WITHOUT a prior create/load: append
|
||||
// must adopt the on-disk row (cursor = stored length) and continue the seq.
|
||||
const b2 = await backend(path)
|
||||
await b2.ctx.sessionPersistence.append(m.id, [
|
||||
{ type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
|
||||
{ type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
|
||||
])
|
||||
const loaded = await b2.ctx.sessionPersistence.load(m.id)
|
||||
expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
|
||||
await b2.dispose()
|
||||
})
|
||||
|
||||
it('append rolls back and rethrows when an event INSERT fails inside the transaction', async () => {
|
||||
const path = await freshDbPath()
|
||||
const m = meta('rollback-insert')
|
||||
@@ -549,190 +350,6 @@ describe('SessionPersistenceSqlite: edge cases', () => {
|
||||
await b2.dispose()
|
||||
})
|
||||
|
||||
it('round-trips a header with parentSession (fork lineage)', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
const m: SessionHeader = { ...meta('child'), parentSession: SessionId('parent') }
|
||||
await ctx.sessionPersistence.create(m)
|
||||
await ctx.sessionPersistence.append(m.id, oneTurnLog())
|
||||
const loaded = await ctx.sessionPersistence.load(m.id)
|
||||
expect(loaded.meta.parentSession).toBe(SessionId('parent'))
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('a fresh live session reusing a previously-loaded id is rejected (ownerless guard)', async () => {
|
||||
const path = await freshDbPath()
|
||||
const m = meta('ownerless')
|
||||
const b1 = await backend(path)
|
||||
await b1.ctx.sessionPersistence.create(m)
|
||||
await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
|
||||
await b1.dispose()
|
||||
|
||||
const b2 = await backend(path)
|
||||
// load() leaves ownerless state with cursor 6.
|
||||
await b2.ctx.sessionPersistence.load(m.id)
|
||||
// A fresh, unrelated live session reusing the id has a shorter/non-matching
|
||||
// seed → its onCreated must reject rather than graft onto the loaded prefix.
|
||||
const s = b2.ctx.sessions.create('ownerless')
|
||||
s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
await expect(b2.ctx.parallel('session/flush', s)).rejects.toThrow(/id collision/)
|
||||
await b2.dispose()
|
||||
})
|
||||
|
||||
it('a live session whose seed matches the loaded prefix claims ownerless state and persists the suffix', async () => {
|
||||
const path = await freshDbPath()
|
||||
const m = meta('claim')
|
||||
const b1 = await backend(path)
|
||||
await b1.ctx.sessionPersistence.create(m)
|
||||
await b1.ctx.sessionPersistence.append(m.id, oneTurnLog())
|
||||
await b1.dispose()
|
||||
|
||||
const b2 = await backend(path)
|
||||
const { events } = await b2.ctx.sessionPersistence.load(m.id) // ownerless, cursor 6
|
||||
// A live session seeded with the loaded log PLUS a new turn claims the state
|
||||
// and persists only the suffix.
|
||||
const s = b2.ctx.sessions.create('claim', { seed: [
|
||||
...events,
|
||||
{ type: 'turn/start', seq: 6, time: 7, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } },
|
||||
{ type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
|
||||
] })
|
||||
await b2.ctx.parallel('session/flush', s)
|
||||
const loaded = await b2.ctx.sessionPersistence.load(m.id)
|
||||
expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
|
||||
await b2.dispose()
|
||||
})
|
||||
|
||||
it('an abandoned lazy session (never materialized) releases its id for reuse', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
const inits = (ctx.sessionPersistence as unknown as { inits: Map<Session, Promise<void>> }).inits
|
||||
let first!: Session
|
||||
const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
|
||||
first = inner.sessions.create('reuse')
|
||||
}, { inject: ['sessions'] }))
|
||||
await inits.get(first) // let the lazy create register the state
|
||||
await firstFiber.dispose() // disposed before any append → never materialized
|
||||
|
||||
let reuse!: Session
|
||||
await ctx.plugin(Object.assign((inner: Context) => {
|
||||
reuse = inner.sessions.create('reuse')
|
||||
}, { inject: ['sessions'] }))
|
||||
await expect(inits.get(reuse)).resolves.toBeUndefined()
|
||||
reuse.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
reuse.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await ctx.parallel('session/flush', reuse)
|
||||
expect(await ctx.sessionPersistence.has(SessionId('reuse'))).toBe(true)
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('does NOT reclaim an id whose abandoned owner still has buffered (unflushed) events', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
const inits = (ctx.sessionPersistence as unknown as { inits: Map<Session, Promise<void>> }).inits
|
||||
let first!: Session
|
||||
const firstFiber = await ctx.plugin(Object.assign((inner: Context) => {
|
||||
first = inner.sessions.create('buffered')
|
||||
}, { inject: ['sessions'] }))
|
||||
await inits.get(first)
|
||||
// Append a turn but do NOT flush — events sit in the write-behind buffer.
|
||||
first.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
first.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await firstFiber.dispose() // disposed before flush; not materialized, buffer pending
|
||||
|
||||
let reuse!: Session
|
||||
await ctx.plugin(Object.assign((inner: Context) => {
|
||||
reuse = inner.sessions.create('buffered')
|
||||
}, { inject: ['sessions'] }))
|
||||
await expect(inits.get(reuse)).rejects.toThrow(/already bound to a different live session/)
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('initFor is idempotent: re-emitting session/created does not re-initialize', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
const session = ctx.sessions.create('idem')
|
||||
ctx.emit('session/created', session) // second create event for the same object
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await ctx.parallel('session/flush', session)
|
||||
expect(await ctx.sessionPersistence.has(SessionId('idem'))).toBe(true)
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('a live session claims cursor-0 ownerless state created via the public API and persists its seed', async () => {
|
||||
const { ctx, dispose } = await backend()
|
||||
// create() registers ownerless state with cursor 0 (no events yet).
|
||||
await ctx.sessionPersistence.create(meta('cursor0'))
|
||||
// A live session reusing that id, seeded with a turn, claims the ownerless
|
||||
// state (cursor 0 trivially matches any seed) and persists the whole seed.
|
||||
const s = ctx.sessions.create('cursor0', { seed: [
|
||||
{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
|
||||
{ type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
|
||||
] })
|
||||
await ctx.parallel('session/flush', s)
|
||||
const loaded = await ctx.sessionPersistence.load(SessionId('cursor0'))
|
||||
expect(loaded.events.map(e => e.seq)).toEqual([0, 1])
|
||||
await dispose()
|
||||
})
|
||||
|
||||
it('HMR: reloading the backend adopts a still-live, already-materialized session', async () => {
|
||||
const path = await freshDbPath()
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
// The session lives in its OWN fiber so it survives the backend reload.
|
||||
let session!: Session
|
||||
await ctx.plugin(Object.assign((inner: Context) => {
|
||||
session = inner.sessions.create('hmr-adopt')
|
||||
}, { inject: ['sessions'] }))
|
||||
|
||||
// Backend instance 1 materializes the session on disk.
|
||||
const backend1 = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await ctx.parallel('session/flush', session)
|
||||
|
||||
// Hot-reload: dispose instance 1, plug in instance 2 over the SAME file
|
||||
// while the session stays live. Instance 2 has an empty states map but the
|
||||
// row is materialized on disk and is a prefix of the live events — it must
|
||||
// ADOPT (not reject), and a second turn then persists.
|
||||
await backend1.dispose()
|
||||
await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
|
||||
await expect(ctx.parallel('session/flush', session)).resolves.not.toThrow()
|
||||
|
||||
const loaded = await ctx.sessionPersistence.load(SessionId('hmr-adopt'))
|
||||
expect(loaded.events.filter(e => e.type === 'turn/start')).toHaveLength(2)
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('HMR: adoption persists the live SUFFIX that was ahead of the on-disk prefix', async () => {
|
||||
const path = await freshDbPath()
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
let session!: Session
|
||||
await ctx.plugin(Object.assign((inner: Context) => {
|
||||
session = inner.sessions.create('hmr-suffix')
|
||||
}, { inject: ['sessions'] }))
|
||||
|
||||
const backend1 = await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await ctx.parallel('session/flush', session)
|
||||
|
||||
// Append turn 2 to the LIVE session, then dispose instance 1 WITHOUT
|
||||
// flushing turn 2: it is now ONLY in the live session's events.
|
||||
await backend1.dispose()
|
||||
session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
|
||||
|
||||
// Instance 2 adopts the on-disk prefix (turn 1) and MUST persist the live
|
||||
// suffix (turn 2) carried in the session's events.
|
||||
await ctx.plugin(SessionPersistenceSqlite, { path })
|
||||
await ctx.parallel('session/flush', session)
|
||||
const loaded = await ctx.sessionPersistence.load(SessionId('hmr-suffix'))
|
||||
expect(loaded.events.map(e => e.seq)).toEqual([0, 1, 2, 3])
|
||||
expect(loaded.events.filter(e => e.type === 'turn/start')).toHaveLength(2)
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('HMR: a DIFFERENT session colliding with a materialized on-disk id is rejected', async () => {
|
||||
const path = await freshDbPath()
|
||||
// Instance 1 materializes a session and disposes.
|
||||
|
||||
Reference in New Issue
Block a user