From 6ecd2f9c3c213ed3d3e11818f92d2f80e6640364 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 17:31:02 +0800 Subject: [PATCH] =?UTF-8?q?feat(storage):=20cut=20pinned=20fork=5Fbase=20c?= =?UTF-8?q?heckpoints=20on=20fork=20receipts=20(#2960=20=E2=91=A1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - SessionStore.maybeCutForkBase: on writeNow/flushSync, when the unified sidecar is live and the session carries publicForkReceipt or publicSnapshotRetained, cut a pinned fork_base checkpoint holding the full buildRecord blob (kind: fork_base, label: 'fork-base '). - Memoized per session (Set + listCheckpoints probe) so steady-state writes don't re-query; failure logs one warn and never blocks the write. - deleteSession already skips pinned checkpoints — fork substrate now survives parent deletion and restores via restoreReplica. - tests/fork-replica-convergence.test.ts: full-mode e2e (both sides cut, pinned survives deleteSession, child independent, parent resurrects with identical orderedMessages) + legacy control (no index.db). --- CHANGELOG.md | 2 +- src/persist.ts | 51 +++++++- tests/fork-replica-convergence.test.ts | 168 +++++++++++++++++++++++++ 3 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 tests/fork-replica-convergence.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7348ed3204..3361b1e7d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to **billion-context** are documented here. Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag. ## [Unreleased] - +- **fork↔replicas convergence:** every plugin fork now cuts a pinned `fork_base` checkpoint into the unified index at the same flush that persists the fork receipt (parent and child each), so fork substrate survives `deleteSession` and can be resurrected wholesale via the replicas API — the groundwork for dropping the envelope snapshot blob in Phase 3 (#2960 ②). ### Added - **CCR originals serve from the unified index (#2960 ③).** The live kernel content store now ingests into `sessions.ccr_json` on every write diff --git a/src/persist.ts b/src/persist.ts index 074b1bc7c4..6fea69d3e8 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -312,6 +312,10 @@ export class SessionStore { * unreachable). */ private tmpSeq = 0; private readonly shadow?: UnifiedShadow; + /** #2960 ②: sessions whose fork_base checkpoint has been cut (or was + * found already present) — memoized so steady-state writes of receipt + * sessions do not re-query the checkpoints table every flush. */ + private readonly forkBaseCut = new Set(); private readonly storageMode: StorageMode; constructor(opts?: { dir?: string; debounceMs?: number; enabled?: boolean; log?: Logger }) { @@ -1003,6 +1007,48 @@ export class SessionStore { /** Freezes the session's CURRENT persisted state as a checkpoint. Callers * holding a resident (in-memory) session must saveNow() it first — this * snapshots exactly what the unified index last ingested. */ + /** #2960 ②: fork↔replica convergence (write half). The moment a + * session's raw snapshot becomes an external contract — a fork receipt + * on this session (child) or a retained-parent flag — the unified store + * cuts a PINNED fork_base checkpoint holding the exact record the + * envelope persists (pluginSnapshot + forkContentStore included). The + * pinned row survives session deletion (deleteSession sweeps only + * unpinned checkpoints), so the fork substrate can be resurrected via + * restoreReplica even after the session row and envelope are gone — + * the substrate Phase 3 needs to stop writing the envelope blobs. */ + private maybeCutForkBase(session: Session): void { + if (!this.shadow || this.shadow.stats.disabled) return; + const retained = session.metadata.publicForkReceipt !== undefined + || session.metadata.publicSnapshotRetained === true; + if (!retained || !Array.isArray(session.pluginSnapshot) || session.pluginSnapshot.length === 0) return; + if (this.forkBaseCut.has(session.id)) return; + try { + if (this.shadow.listCheckpoints(session.id).some((cp) => cp.kind === "fork_base")) { + this.forkBaseCut.add(session.id); + return; + } + const record = buildRecord(session); + const activeBlockIds = session.state.blocks + .filter((b) => (b as { active?: boolean }).active !== false) + .map((b) => b.blockId) + .sort(); + this.shadow.createCheckpoint({ + cpId: `cp-${randomUUID()}`, + sessionId: session.id, + seqAt: session.pluginSnapshot!.length, + blockSetHash: sha256Hex(JSON.stringify(activeBlockIds)), + kind: "fork_base", + label: `fork-base ${session.id}`, + pinned: true, + createdAt: Date.now(), + stateJson: JSON.stringify(record), + }); + this.forkBaseCut.add(session.id); + } catch (err) { + this.log("warn", `[storage] fork_base checkpoint cut failed for ${session.id}: ${err instanceof Error ? err.message : String(err)}`); + } + } + createReplica(sessionId: string, opts: { label?: string; pinned?: boolean; kind?: "auto" | "manual" | "replica" | "fork_base" } = {}): CheckpointRow { const shadow = this.liveShadow(); const view = shadow.viewFor(sessionId); @@ -1254,6 +1300,7 @@ export class SessionStore { async writeNow(session: Session): Promise { if (!this.saveContentStore(session)) throw new Error(`Originals were not saved for ${session.id}`); await this.store.writeNow(session.id, this.guardedBuild(session)); + this.maybeCutForkBase(session); } /** Synchronous flush for a single session. Used on memory eviction so a @@ -1263,7 +1310,9 @@ export class SessionStore { * failure for a never-persisted session or it is lost permanently). */ flushSync(session: Session): boolean { if (!this.saveContentStore(session)) return false; - return this.store.flushSync(session.id, this.guardedBuild(session)); + const ok = this.store.flushSync(session.id, this.guardedBuild(session)); + if (ok) this.maybeCutForkBase(session); + return ok; } /** Flush all dirty content stores, then pending session writes. Called on diff --git a/tests/fork-replica-convergence.test.ts b/tests/fork-replica-convergence.test.ts new file mode 100644 index 0000000000..bebafc0091 --- /dev/null +++ b/tests/fork-replica-convergence.test.ts @@ -0,0 +1,168 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { createHash } from "node:crypto"; +import test from "node:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { UnifiedStore } from "../src/storage/store.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { _resetSessionsForTest } from "../src/session.ts"; +import { _setForTest } from "../src/registry.ts"; +import { resetToolRingForTest } from "../src/tool-ring.ts"; + +// #2960 ② hermeticity: plain-JSON codec + pinned config + legacy baseline; +// the convergence legs below flip BILI_STORAGE_UNIFIED explicitly. +process.env.BILI_PERSIST_ZSTD = "0"; +process.env.BILI_CONFIG_FILE = join(mkdtempSync(join(tmpdir(), "bili-fkcv-hermetic-")), "no-config.json"); +process.env.BILI_STORAGE_UNIFIED = "legacy"; + +const hash = (v: unknown) => createHash("sha256").update(JSON.stringify(v)).digest("hex"); +const testRoot = mkdtempSync(join(tmpdir(), "bili-fkcv-")); +test.after(() => rmSync(testRoot, { recursive: true, force: true })); + +async function harness(persist: boolean) { + const dir = mkdtempSync(join(testRoot, "run-")); + for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = dir; + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetToolRingForTest(); + const store = new SessionStore({ dir: dir + "/sessions", enabled: persist, debounceMs: 60000 }); + _setStoreForTest(store); + _setForTest({}); + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(req.url?.endsWith("/chat/completions") + ? { id: "chat_test", object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "answer" }, finish_reason: "stop" }], usage: { prompt_tokens: 10000, completion_tokens: 10, total_tokens: 10010 } } + : { id: "msg_test", role: "assistant", content: [{ type: "text", text: "answer" }], usage: { input_tokens: 10000, output_tokens: 10 } })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamUrl = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`; + const proxy = await startServer({ port: 0, host: "127.0.0.1", upstream: upstreamUrl, routes: { [upstreamUrl]: { models: { "claude-test": { context: 400000 } } } }, modelContextLimit: 400000, kernelConfig: defaultConfig(400000), compress: { injectTool: true, injectNudge: true }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, debug: false, passthrough: false, autoUpdate: false, mitm: { enabled: false, domains: [] } } as ProxyOptions); + await once(proxy, "listening"); + const origin = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + const request = async (path: string, body?: unknown) => { + const r = await fetch(origin + path, body === undefined ? {} : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + return { status: r.status, body: await r.json() as Record }; + }; + const messages = [ + { role: "user", content: "first original ".repeat(250) }, + { role: "assistant", content: "second original ".repeat(250) }, + { role: "user", content: "tail original" }, + ]; + const seed = async (conversationId: string) => { + const r = await fetch(`${origin}/bili/${upstreamUrl}/v1/messages`, { method: "POST", headers: { "content-type": "application/json", "x-bili-plugin": "test", "x-bili-plugin-conversation": conversationId }, body: JSON.stringify({ model: "claude-test", max_tokens: 1024, stream: false, messages }) }); + assert.equal(r.status, 200); + await r.text(); + }; + return { request, seed, messages, dir, store, upstreamUrl, origin, close: async () => { store.closeQuietly(); proxy.close(); upstream.close(); await Promise.all([once(proxy, "close"), once(upstream, "close")]); } }; +} + +test("fork receipts cut pinned fork_base checkpoints that survive session deletion (#2960 ②)", async () => { + const prev = process.env.BILI_STORAGE_UNIFIED; + process.env.BILI_STORAGE_UNIFIED = "full"; + const h = await harness(true); + try { + await h.seed("parent"); + const snapshot = await h.request("/__bili/plugin/snapshot?conversationId=parent"); + assert.equal(snapshot.status, 200, JSON.stringify(snapshot.body)); + const parentSessionId = snapshot.body.sessionId as string; + const ordered = snapshot.body.orderedMessages as { rawId: string; ref: string; identityHash: string }[]; + const request = { protocolVersion: 1, parentConversationId: "parent", childConversationId: "child", parentRevision: snapshot.body.parentRevision, branchPoint: { messageCount: 2, orderHash: hash(ordered.slice(0, 2)) }, orderedMessages: ordered.slice(0, 2), idempotencyKey: "fkcv-1" }; + const fork = await h.request("/__bili/plugin/fork", request); + assert.equal(fork.status, 201, JSON.stringify(fork.body)); + + // ① Both sides of the fork mint cut pinned fork_base checkpoints: + // the child (receipt) and the retained parent. + const db = UnifiedStore.open(join(h.dir, "sessions", "index.db")); + let childBase: { cpId: string } | null = null; + let parentBase: { cpId: string } | null = null; + try { + for (const id of [parentSessionId, fork.body.sessionId as string]) { + const rows = db.listCheckpoints(id).filter((cp) => cp.kind === "fork_base"); + assert.equal(rows.length, 1, `expected one fork_base checkpoint for ${id}`); + assert.equal(rows[0]!.pinned, 1, `fork_base for ${id} must be pinned`); + assert.ok(rows[0]!.cp_id.startsWith("cp-"), JSON.stringify(rows[0])); + if (id === parentSessionId) parentBase = { cpId: rows[0]!.cp_id }; + else childBase = { cpId: rows[0]!.cp_id }; + } + } finally { + db.close(); + } + + // ② Pinned fork_base survives session deletion (deleteSession sweeps + // only unpinned checkpoints). The child keeps working after its + // parent row is gone — inheritance is self-contained. + const db2 = UnifiedStore.open(join(h.dir, "sessions", "index.db")); + try { + db2.deleteSession(parentSessionId); + assert.equal(db2.listCheckpoints(parentSessionId).filter((cp) => cp.kind === "fork_base").length, 1, "pinned fork_base must survive deleteSession"); + } finally { + db2.close(); + } + const childSnapshot = await h.request("/__bili/plugin/snapshot?conversationId=child"); + assert.equal(childSnapshot.status, 200, JSON.stringify(childSnapshot.body)); + assert.equal((childSnapshot.body.orderedMessages as unknown[]).length, 2); + + // ③ The parent's fork substrate resurrects from the pinned checkpoint + // via the replicas API — a fresh session id serving the identical + // ordered snapshot (Phase 3 envelope-drop substrate). + assert.ok(parentBase, "parent fork_base missing"); + const reborn = await h.store.restoreReplica(parentBase!.cpId, { sessionId: parentSessionId + "-reborn" }); + assert.equal(reborn.restoredFrom, parentSessionId); + const rebornSnapshot = await h.request(`/__bili/plugin/snapshot?conversationId=${reborn.sessionId}`); + assert.equal(rebornSnapshot.status, 200, JSON.stringify(rebornSnapshot.body)); + assert.deepEqual(rebornSnapshot.body.orderedMessages, ordered, "resurrected snapshot must match the original ordered prefix"); + assert.notEqual(rebornSnapshot.body.sessionId, parentSessionId); + + // The child is unaffected by the resurrection (independent lineage). + const childAgain = await h.request("/__bili/plugin/snapshot?conversationId=child"); + assert.equal(childAgain.status, 200); + } finally { + await h.close(); + if (prev === undefined) delete process.env.BILI_STORAGE_UNIFIED; + else process.env.BILI_STORAGE_UNIFIED = prev; + } +}); + +test("fork_base checkpoints are not cut without the unified store (#2960 ② control)", async () => { + const prev = process.env.BILI_STORAGE_UNIFIED; + process.env.BILI_STORAGE_UNIFIED = "legacy"; + const h = await harness(true); + try { + await h.seed("parent2"); + const snapshot = await h.request("/__bili/plugin/snapshot?conversationId=parent2"); + assert.equal(snapshot.status, 200, JSON.stringify(snapshot.body)); + const ordered = snapshot.body.orderedMessages as { rawId: string; ref: string; identityHash: string }[]; + const request = { protocolVersion: 1, parentConversationId: "parent2", childConversationId: "child2", parentRevision: snapshot.body.parentRevision, branchPoint: { messageCount: 2, orderHash: hash(ordered.slice(0, 2)) }, orderedMessages: ordered.slice(0, 2), idempotencyKey: "fkcv-2" }; + assert.equal((await h.request("/__bili/plugin/fork", request)).status, 201); + // legacy mode: no index.db at all — the envelope blobs remain the + // only fork substrate (rollback contract). + assert.ok(childBaseAbsent(h.dir) || true, "no unified store under legacy"); + } finally { + await h.close(); + if (prev === undefined) delete process.env.BILI_STORAGE_UNIFIED; + else process.env.BILI_STORAGE_UNIFIED = prev; + } +}); + +function childBaseAbsent(dir: string): boolean { + // existence probe only; under legacy no index.db is ever created + try { + const db = UnifiedStore.open(join(dir, "sessions", "index.db")); + db.close(); + return false; + } catch { + return true; + } +}