From ac29ecda2390fb5402b4d8d139ff5f9242f9e8d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E9=85=B8?= Date: Mon, 12 Oct 2026 15:25:50 +0800 Subject: [PATCH 1/3] fix(sessions): reconcile forked-session fold lineage from disk at boot (#2807) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A forked child session starts with an empty fold ledger while carrying the parent's full raw history, so preflight re-estimates and re-folds everything and the payload overruns the model window. The lineage is written to metadata.derivedFromSessionId but never read back, so a restart (or a fork that missed the byte-exact prefix match) left the child orphaned. Add reconcileDerivedLineage(), run after initSessions()/loadConversations(): for every session that records a parent, holds no blocks, and has not yet adopted, load the parent from disk and re-run planForkAdoption + applyForkAdoption by message-id intersection — copy-on-fork, parent untouched, and the CCR content store is cloned for the inherited refs. Also fix the weak derived path: it read opts.forkAdoption (default OFF), so it never adopted blocks while the boot reconcile still did — two inheritance paths answering to two different switches. Gate it on resumeInheritance, the same switch as the strong resume path, and move the derivedBlocksAdopted marker to after the adoption call so a partial overlap does not close the gate permanently. Tests: tests/lineage-reconcile-boot.test.ts (adoption, idempotency across boots, resumeInheritance:false) and tests/derived-fork-block-inheritance.test.ts (byte-differing fork inherits, non-overlapping ids inherit nothing). --- src/fork-adoption.ts | 93 ++++++++++++++++++++++++++++++++++++++++++++ src/server.ts | 19 ++++++++- src/server/handle.ts | 37 ++++++++++++++++++ 3 files changed, 148 insertions(+), 1 deletion(-) diff --git a/src/fork-adoption.ts b/src/fork-adoption.ts index 090e31a933..cfb4556c0d 100644 --- a/src/fork-adoption.ts +++ b/src/fork-adoption.ts @@ -361,3 +361,96 @@ export function maybeAdoptResume(args: { log("info", `[resume-inheritance] ${session.id} adopted ${n} CCR content-store entr${n === 1 ? "y" : "ies"} for the inherited/cited refs from parent ${parent.id} (#1341/#1486)`); } } + +/** + * Lineage reconcile on boot (#2807 / #1333): the derived fork lineage is + * persisted (`metadata.derivedFromSessionId`, written by handle.ts:1363) but + * until now it was write-only — nothing ever read it back. Both adoption + * paths need process-local state the proxy does not have across a restart: + * the strong path scans `prefixAffinity.trackedChains` (in-memory), and the + * weak path needs `derivedParent` from the plugin register table + * (`pendingRegisters`, in-memory). A bili restart therefore leaves every + * forked child holding a full raw history with zero blocks while its parent's + * fold ledger sits on disk — which is how a session that upstream measured at + * ~480K tokens got rejected as ~1.4M. + * + * So reconcile the lineage the other way round: after boot, for every session + * that records a parent and still has no blocks, load the parent from disk and + * re-run adoption by raw-id set (see planForkAdoption). This closes the same + * gap as #2791 (anonymous pfa-* forks) without needing the identity chain. + * + * Gated by `resumeInheritance`, not `forkAdoption`: #1834 reserves + * `forkAdoption` for anonymous forks, while this is an identified lineage + * (the parent id came from the plugin register) and belongs with the + * byte-prefix strong path, which is on by default. + */ +export function reconcileDerivedLineage( + sessions: Session[], + opts: { log: (level: string, msg: string) => void; adoptionEnabled: boolean }, +): number { + const { log, adoptionEnabled } = opts; + if (!adoptionEnabled) return 0; + let adopted = 0; + for (const s of sessions) { + // A closed gate must not consume the marker either, so a session stays + // eligible if the operator turns adoption on and restarts. + const parentId: unknown = s.metadata.derivedFromSessionId; + if (typeof parentId !== "string") continue; + if (parentId === s.id) continue; + if (s.state.blocks.length > 0) continue; + if (s.metadata.derivedBlocksAdopted === true) continue; + + let parent = peekSession(parentId); + if (!parent) { + parent = getStore().loadSync(parentId, { + protocol: s.meta.protocol, + upstreamOrigin: s.meta.upstreamOrigin, + }) ?? undefined; + } + if (!parent) { + // Evicted before it was persisted — or restored later. Leave the + // marker unset and retry on the next boot rather than closing the + // door on a parent that may reappear. + log("info", `[lineage-reconcile] ${s.id} records parent ${parentId}, which is not on disk; will retry next boot`); + continue; + } + if (parent.state.blocks.length === 0) { + s.metadata.derivedBlocksAdopted = true; + log("info", `[lineage-reconcile] ${s.id}: parent ${parentId} has no blocks to adopt`); + continue; + } + + const incomingIds = new Set(Object.keys(s.state.messageRefs.byRaw)); + if (incomingIds.size === 0) { + s.metadata.derivedBlocksAdopted = true; + log("info", `[lineage-reconcile] ${s.id}: no refs to match parent ${parentId} against`); + continue; + } + + try { + const plan = planForkAdoption(parent, incomingIds, { seedAllRefs: true }); + if (plan.adoptedActive === 0) { + s.metadata.derivedBlocksAdopted = true; + log("info", `[lineage-reconcile] ${s.id}: parent ${parentId} has nothing fully present (${plan.straddled} block(s) straddle the fork); retrying would not change that`); + continue; + } + applyForkAdoption(s, plan, parent); + const wanted = new Set(Object.keys(plan.refs.byRef)); + const storeSlice = cloneStoreForRefs(contentStoreOf(parent), wanted); + if (storeSlice) { + adoptContentStore(s, storeSlice); + } + s.metadata.derivedFrom ??= parent.id; + s.metadata.derivedFromSessionId = parent.id; + s.metadata.derivedBlocksAdopted = true; + adopted++; + log("info", `[lineage-reconcile] ${s.id} adopted ${plan.adoptedActive} block(s) (~${plan.adoptedTokens} tokens, ${plan.straddled} straddled) from parent ${parent.id} (#2807)`); + } catch (e) { + // Transient (a corrupt parent file): leave the marker unset so a + // later boot can still try, but never let one bad session abort the + // whole sweep. + log("warn", `[lineage-reconcile] ${s.id}: adoption from parent ${parent.id} failed (${e instanceof Error ? e.message : String(e)}); continuing`); + } + } + return adopted; +} diff --git a/src/server.ts b/src/server.ts index 9c56cd5a24..5d90cb4b42 100644 --- a/src/server.ts +++ b/src/server.ts @@ -109,7 +109,7 @@ import { emitPreflightError } from "./stream-error.js"; import { agentProviderRecipes } from "./agent-providers.js"; import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, conversationHeaderSource, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, shouldStampRelayAffinityPck, type ConversationIdentity } from "./session-id.js"; import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js"; -import { maybeAdoptForkBlocks, maybeAdoptResume } from "./fork-adoption.js"; +import { maybeAdoptForkBlocks, maybeAdoptResume, reconcileDerivedLineage } from "./fork-adoption.js"; import { publicForkInputMatches } from "./plugin.js"; import { flushPrefixAffinity, hydratePrefixAffinity, scheduleAffinityPersist } from "./affinity-persist.js"; import { setSimhashAdoptionEnabled } from "./prefix-affinity.js"; @@ -412,6 +412,23 @@ export async function startServer(opts: ProxyOptions): Promise { await initSessions(); loadConversations(); log("info", `[persist] ${getStore().enabled ? "enabled" : "disabled"}`); + // #2807: restore fork lineage that a restart orphaned. Every fork writes + // metadata.derivedFromSessionId, but both adoption paths read process-local + // state (prefixAffinity.trackedChains for the byte-prefix path, the plugin + // register table for the derived path), so a restart leaves forked children + // at zero blocks while their parent's ledger is on disk — and the child + // re-sends the shared prefix raw (~1.4M tokens rejected as over-window). + // Must run after loadConversations(): the parent may live in the plugin + // conversation map rather than a session file. + try { + const adopted = reconcileDerivedLineage(listSessions(), { + log, + adoptionEnabled: opts.resumeInheritance !== false, + }); + if (adopted > 0) log("info", `[lineage-reconcile] restored fold state for ${adopted} forked session(s)`); + } catch (e) { + log("warn", `[lineage-reconcile] sweep failed: ${String(e)}`); + } // #1082: sweep stale small session files — boot pass + periodic. Runs // against the disk tree, not the in-memory map: evicted/capped sessions // leave files behind that only a disk walk sees. diff --git a/src/server/handle.ts b/src/server/handle.ts index 1af75f07f0..617aec5138 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -1369,6 +1369,43 @@ async function handleRequest( session.metadata.derivedFrom = derivedParent; session.metadata.derivedFromSessionId = parentSession.id; markDirty(session); + // #2807-followup: the weak path previously only recorded the + // lineage and fell back to read-only decompress/search_context. + // When the child replays the parent's messages (a fork that + // missed the byte-exact prefix match — timestamp drift, a + // re-decorated tail, a protocol switch), the fold ledger was + // orphaned: every folded block was invisible, so the whole + // raw history was re-sent and re-estimated. Seed the child + // from the parent by message-id intersection — the same + // copy-on-fork adoption the strong resume path runs, minus + // the byte-prefix requirement. Runs once per session. + // + // #2807-audit: gated on resumeInheritance, NOT forkAdoption — + // this is an identified fork (the parent came from the plugin + // register), the same class as the strong path at the top of + // this function, and #1834/#629 reserve forkAdoption for + // anonymous forks. Reading forkAdoption here made the two + // inheritance paths answer to two different switches: with + // its default OFF the weak path never adopted, while the + // boot-time lineage reconcile (src/fork-adoption.ts + // reconcileDerivedLineage) still did. + if (opts.resumeInheritance !== false && session.metadata.derivedBlocksAdopted !== true) { + try { + maybeAdoptResume({ + session, + parent: parentSession, + sharedDepth: 0, + protocol, + parsed, + upstreamOrigin, + blocksEnabled: true, // gated above on resumeInheritance; #1834/#629 reserve forkAdoption for anonymous forks + log, + }); + session.metadata.derivedBlocksAdopted = true; + } catch (adoptErr) { + log("warn", `[${session.id}] [derived] block adoption from ${parentSession.id} failed (${String(adoptErr)}); continuing fresh (#2807)`); + } + } log("info", `[${session.id}] [derived] linked to parent session ${parentSession.id} (conversation ${derivedParent}) — decompress/search_context fall back to it read-only (#1333)`); } else if (session.metadata.derivedLinkMissLogged !== true) { // The relaxed gate retries resolution on EVERY request until the link From 7831c9013d1b17fb6c4f11206dd168f30ea90076 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E9=85=B8?= Date: Mon, 12 Oct 2026 16:25:52 +0800 Subject: [PATCH 2/3] fix(sessions): add boot-lineage regression tests and defer non-success adoption gates (#2807) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PR described tests/lineage-reconcile-boot.test.ts and tests/derived-fork-block-inheritance.test.ts as green, but only the src files had been staged — the tests were untracked, so the branch carried no regression coverage for reconcileDerivedLineage at all. Both files are added now: - lineage-reconcile-boot: AC9 boot adoption, AC10 cross-boot idempotence plus an unreachable-parent orphan check, AC11 resumeInheritance:false, AC12 multi-hop lineage gate deferral. - derived-fork-block-inheritance: byte-prefix fork inheritance and the no-intersection case. AC12 is the regression test for review finding 2: reconcileDerivedLineage walks sessions by lastSeen descending, so in a P->C->G chain the grandchild is reached before the child has adopted from its own parent. Three branches (parent has no blocks, child has no refs, nothing fully present yet) previously set derivedBlocksAdopted, closing the gate permanently; the grandchild could then only rely on preflight compression. They now leave the marker unset so the next boot retries, matching the existing 'parent not on disk' philosophy. AC12 fails without this change and passes with it. Also corrects the boot comment: the sweep resolves parents by session id (peekSession, then the store), so the real ordering constraint is initSessions(), not loadConversations() — the plugin routing table is never consulted. --- src/fork-adoption.ts | 20 +- src/server.ts | 5 +- tests/derived-fork-block-inheritance.test.ts | 366 ++++++++++++++ tests/lineage-reconcile-boot.test.ts | 477 +++++++++++++++++++ 4 files changed, 860 insertions(+), 8 deletions(-) create mode 100644 tests/derived-fork-block-inheritance.test.ts create mode 100644 tests/lineage-reconcile-boot.test.ts diff --git a/src/fork-adoption.ts b/src/fork-adoption.ts index cfb4556c0d..3a3c6591b1 100644 --- a/src/fork-adoption.ts +++ b/src/fork-adoption.ts @@ -415,23 +415,31 @@ export function reconcileDerivedLineage( continue; } if (parent.state.blocks.length === 0) { - s.metadata.derivedBlocksAdopted = true; - log("info", `[lineage-reconcile] ${s.id}: parent ${parentId} has no blocks to adopt`); + // Nothing to adopt now. Leave the marker unset: the parent may fold + // later, and in a multi-hop lineage an intermediate parent may adopt + // after this one was visited. + log("info", `[lineage-reconcile] ${s.id}: parent ${parentId} has no blocks to adopt yet; will retry next boot`); continue; } const incomingIds = new Set(Object.keys(s.state.messageRefs.byRaw)); if (incomingIds.size === 0) { - s.metadata.derivedBlocksAdopted = true; - log("info", `[lineage-reconcile] ${s.id}: no refs to match parent ${parentId} against`); + // Leave the marker unset: this session has served no request yet, so + // its first request is still the real reconciliation point (the weak + // derived path adopts from the parent then). Closing the gate here + // would defeat that path. + log("info", `[lineage-reconcile] ${s.id}: no refs to match parent ${parentId} against; deferring to the first request`); continue; } try { const plan = planForkAdoption(parent, incomingIds, { seedAllRefs: true }); if (plan.adoptedActive === 0) { - s.metadata.derivedBlocksAdopted = true; - log("info", `[lineage-reconcile] ${s.id}: parent ${parentId} has nothing fully present (${plan.straddled} block(s) straddle the fork); retrying would not change that`); + // Nothing fully present. Do NOT set the marker: in a multi-hop + // lineage P→C→G the sweep may not have reached C yet, and a + // straddled block becomes fully-present once the child grows. + // Retry on the next boot — the plan is cheap. + log("info", `[lineage-reconcile] ${s.id}: parent ${parentId} has nothing fully present yet (${plan.straddled} block(s) straddle the fork); will retry next boot`); continue; } applyForkAdoption(s, plan, parent); diff --git a/src/server.ts b/src/server.ts index 5d90cb4b42..5e7d8b6fe5 100644 --- a/src/server.ts +++ b/src/server.ts @@ -418,8 +418,9 @@ export async function startServer(opts: ProxyOptions): Promise { // register table for the derived path), so a restart leaves forked children // at zero blocks while their parent's ledger is on disk — and the child // re-sends the shared prefix raw (~1.4M tokens rejected as over-window). - // Must run after loadConversations(): the parent may live in the plugin - // conversation map rather than a session file. + // Must run after initSessions(): the parent is resolved by session id + // (peekSession, then the on-disk store), so it has to be resident first. + // The plugin conversation routing table is irrelevant to this sweep. try { const adopted = reconcileDerivedLineage(listSessions(), { log, diff --git a/tests/derived-fork-block-inheritance.test.ts b/tests/derived-fork-block-inheritance.test.ts new file mode 100644 index 0000000000..21583aa67a --- /dev/null +++ b/tests/derived-fork-block-inheritance.test.ts @@ -0,0 +1,366 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { maybeAdoptResume } from "../src/fork-adoption.ts"; +import type { Session } from "../src/session.ts"; +import { listSessions } from "../src/session.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +/** + * derived-fork block inheritance: fork 出的子会话在弱路径 `derived` 命中 + * (身份头已确认父子关系)时,必须按消息 id 交集继承父会话的活跃折叠 block, + * 不依赖字节精确前缀匹配。 + * + * 场景模拟 pi fork: + * 1. 父会话(x-acp-session=A)长到压缩触发,产生 refs + blocks + * 2. 用 register 端点声明子会话 B 的 parentConversationId=A + * 3. 子会话(x-acp-session=B)发送 FULL history + 一条新消息 + * 4. 因为父子消息流存在字节差异(fork 重新分配 timestamp),prefix-affinity + * 字节前缀匹配失败 → 不走 resume-inheritance,走弱路径 derived + * 5. 弱路径必须按消息 id 交集继承父会话的 refs + blocks + lineage + */ + +let scenarioSeq = 0; +function nextRunTag(): string { + scenarioSeq += 1; + return `dfork${scenarioSeq}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function close(server: http.Server): Promise { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +} + +function sseLine(obj: unknown): string { + return `data: ${JSON.stringify(obj)}\n\n`; +} + +function parseRefIds(body: string): string[] { + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null = null; + while ((m = re.exec(body)) !== null) ids.push(m[1]); + return ids; +} + +const FILLER = "the quick brown fox jumps over the lazy dog again and again. "; + +function userText(run: string, i: number): string { + return `run ${run} user turn ${i}: ${FILLER.repeat(12)}`; +} + +function relayReply(body: string, n: number): string { + let lastUser = ""; + try { + const parsed = JSON.parse(body) as { messages?: Array<{ role: string; content: string }> }; + const msgs = parsed.messages ?? []; + for (let i = msgs.length - 1; i >= 0; i--) { + if (msgs[i]!.role === "user") { + lastUser = msgs[i]!.content; + break; + } + } + } catch { + /* fall through with empty echo */ + } + return `run reply ${n} to <${lastUser.slice(0, 48)}>: ${FILLER.repeat(10)}`; +} + +type RelayState = { upstreamReqs: string[]; compressed: boolean }; + +function startMockUpstream(state: RelayState): http.Server { + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + state.upstreamReqs.push(body); + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + const refIds = parseRefIds(body); + if (!state.compressed && refIds.length >= 5) { + state.compressed = true; + const from = refIds[1]!; + const to = refIds[refIds.length - 3]!; + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" } }] })); + res.write(sseLine({ + id: "c1", + object: "chat.completion.chunk", + choices: [{ + index: 0, + delta: { + tool_calls: [{ + index: 0, + id: "call_compress_1", + type: "function", + function: { name: "compress", arguments: JSON.stringify({ content: [{ startId: from, endId: to, topic: "folded", summary: `summary covering ${from}..${to}` }] }) }, + }], + }, + }], + })); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })); + } else { + const text = relayReply(body, state.upstreamReqs.length); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: text } }] })); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 500, completion_tokens: 50 } })); + } + res.write("data: [DONE]\n\n"); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + return server; +} + +type ChatMsg = { role: string; content: string }; + +async function chat(url: string, messages: ChatMsg[], sessionId?: string): Promise { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", ...(sessionId ? { "x-acp-session": sessionId } : {}) }, + body: JSON.stringify({ model: "gpt-test", stream: true, messages }), + }); + if (!res.ok) assert.fail(`HTTP ${res.status}: ${await res.text()}`); + let raw = ""; + for await (const chunk of res.body!) raw += Buffer.from(chunk).toString("utf8"); + let reply = ""; + for (const line of raw.split("\n")) { + if (!line.startsWith("data:")) continue; + const payload = line.slice(5).trim(); + if (payload === "[DONE]") continue; + try { + const parsed = JSON.parse(payload) as { choices?: Array<{ delta?: { content?: string } }> }; + reply += parsed.choices?.[0]?.delta?.content ?? ""; + } catch { + /* ignore keepalives */ + } + } + return reply; +} + +function proxyOpts(relayUrl: string): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: {} as ProxyOptions["routes"], + modelContextLimit: 1_000_000, + kernelConfig: defaultConfig(1_000_000, { + preserveRecentMessages: 2, + preserveRecentTokens: 400, + compress: { minCompressRange: 200, minSummaryLength: 20, maxSummaryLength: 5000 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions; +} + +type ScenarioResult = { + parentId: string; + childId: string; + parentRefs: Record; + parentBlockIds: string[]; + childRefs: Record; + childBlockIds: string[]; + lineage: string | undefined; + parentUntouched: boolean; +}; + +async function runDerivedForkScenario(): Promise { + const run = nextRunTag(); + const parentId = `${run}-A`; + const childId = `${run}-B`; + process.env.XDG_STATE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "derived-fork-")); + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const state: RelayState = { upstreamReqs: [], compressed: false }; + const relay = startMockUpstream(state); + await listen(relay); + const relayPort = (relay.address() as { port: number }).port; + const opts = proxyOpts(`http://127.0.0.1:${relayPort}/v1/chat/completions`); + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${relayPort}/v1/chat/completions`; + try { + // Parent conversation grown past the mock's one-shot fold trigger. + const history: ChatMsg[] = []; + for (let i = 1; i <= 8; i++) { + history.push({ role: "user", content: userText(run, i) }); + const reply = await chat(url, history, parentId); + assert.ok(reply.length > 0, `parent turn ${i} must produce a reply`); + history.push({ role: "assistant", content: reply }); + } + const parent = listSessions().find((s) => s.id === parentId); + assert.ok(parent, "parent session must exist"); + const parentRefs = { ...parent.state.messageRefs.byRaw }; + const activeBlocks = parent.state.blocks.filter((b) => b.active); + const parentBlockIds = activeBlocks.map((b) => b.blockId); + assert.ok(Object.keys(parentRefs).length >= 5, "parent must have assigned refs"); + assert.ok(parentBlockIds.length >= 1, `parent must have folded a block (got ${parentBlockIds.length})`); + const parentBlocksBefore = parent.state.blocks.length; + + // Register the child fork — this makes derivedParent known to the server. + const registerRes = await fetch(`http://127.0.0.1:${proxyPort}/__bili/plugin/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: childId, agent: "pi", parentConversationId: parentId }), + }); + assert.equal(registerRes.status, 200, `register must succeed: ${await registerRes.text()}`); + + // Fork: child replays FULL history + one new message under a fresh id. + // The child's request body is not a byte-exact continuation of the + // parent's tracked chain (mock relay returns position-dependent + // echoes), so prefix-affinity's byte-exact match fails and the + // derived (weak) path is the one that must inherit. + // + // To force the WEAK path: append a resume-time decoration to the + // LAST shared message (mimics #1486's "re-decorated tails"). This + // breaks the byte-exact prefix match without changing any message + // id (ids are content-hashed, decoration changes content → new id, + // but the decoration is on a message OUTSIDE the fold range, so + // block adoption is unaffected). + const forkHistory: ChatMsg[] = [ + ...history.slice(0, history.length - 2), + { role: history[history.length - 2]!.role, content: history[history.length - 2]!.content + "\n\n[resume-time context reminder]" }, + { role: history[history.length - 1]!.role, content: history[history.length - 1]!.content }, + { role: "user", content: userText(`${run}-fork`, 1) }, + ]; + const reply1 = await chat(url, forkHistory, childId); + assert.ok(reply1.length > 0, "fork first turn must produce a reply"); + + const child = listSessions().find((s) => s.id === childId); + assert.ok(child, "fork child session must exist"); + const childRefs = { ...child.state.messageRefs.byRaw }; + const childBlockIds = child.state.blocks.map((b) => b.blockId); + const lineage = child.metadata.derivedFromSessionId as string | undefined; + + return { + parentId, + childId, + parentRefs, + parentBlockIds, + childRefs, + childBlockIds, + lineage, + parentUntouched: parent.state.blocks.length === parentBlocksBefore && JSON.stringify(parent.state.messageRefs.byRaw) === JSON.stringify(parentRefs), + }; + } finally { + await close(proxy); + await close(relay); + } +} + +test("a derived child whose ids do not overlap the parent inherits nothing (AC4)", async () => { + // AC4: parent and child sharing no message ids is a genuinely new + // conversation, not a fork — adoption must seed nothing. The id-intersection + // gate is what decides this, so an empty intersection has to be pinned + // independently of the byte-prefix machinery above. + const parent = { + state: { + blocks: [], + messageRefs: { byRaw: {}, byRef: {} }, + tokenSnapshot: {}, + nextBlockId: 1, + nextRunId: 1, + }, + blockContents: new Map(), + } as unknown as Session; + const child = { + state: { + blocks: [], + messageRefs: { byRaw: {}, byRef: {} }, + tokenSnapshot: {}, + nextBlockId: 1, + nextRunId: 1, + }, + blockContents: new Map(), + } as unknown as Session; + const parentRaw: Record = { rawA1: "m00001", rawA2: "m00002" }; + const parentRef: Record = { m00001: "rawA1", m00002: "rawA2" }; + parent.state.messageRefs.byRaw = parentRaw; + parent.state.messageRefs.byRef = parentRef; + parent.state.blocks.push({ + blockId: "b1", + runId: 1, + tier: 0, + active: true, + summary: "parent summary", + directMessageIds: ["rawA1"], + effectiveMessageIds: ["rawA1", "rawA2"], + directBlockIds: [], + createdAt: 0, + compressedTokens: 900, + } as unknown as (typeof parent.state.blocks)[number]); + parent.blockContents.set("b1", { full: { text: "parent summary", count: 1 }, one: null }); + + const logs: Array<[string, string]> = []; + maybeAdoptResume({ + session: child, + parent, + sharedDepth: 0, + protocol: "openai", + // Raw ids are content-hashed by the wire adapters, so an unrelated + // body cannot collide with the parent's `rawA1`/`rawA2` by accident. + parsed: { messages: [{ role: "user", content: "an unrelated conversation" }] }, + upstreamOrigin: "http://127.0.0.1", + blocksEnabled: true, + log: (level, msg) => logs.push([level, msg]), + }); + + assert.equal(child.state.blocks.length, 0, "no shared message id means no block may be adopted"); + assert.equal(child.blockContents.size, 0, "nothing to copy from the parent"); + assert.deepEqual(Object.keys(child.state.messageRefs.byRaw), [], "the child must keep its own empty ref space"); + assert.ok( + logs.some(([, msg]) => msg.includes("nothing to inherit")), + "the no-overlap case must be logged, not silently dropped", + ); +}); + +test("derived fork inherits parent refs and blocks via message-id intersection", async () => { + const r = await runDerivedForkScenario(); + + // Lineage must link to the parent. + assert.equal(r.lineage, r.parentId, "derivedFrom lineage must link to the parent"); + + // Every parent ref assignment must survive into the child, except + // the one we deliberately broke (the decorated message's raw id changed + // because we altered its content). + const missingKeys = Object.keys(r.parentRefs).filter((k) => !(k in r.childRefs)); + assert.equal(missingKeys.length, 1, `exactly one ref should be missing (the decorated message's new raw id): ${JSON.stringify(missingKeys)}`); + for (const [raw, ref] of Object.entries(r.parentRefs)) { + if (missingKeys.includes(raw)) continue; + assert.equal(r.childRefs[raw], ref, `ref ${ref} for a shared message must be preserved across the fork`); + } + + // At least one block must be adopted. + const adopted = r.parentBlockIds.filter((id) => r.childBlockIds.includes(id)); + assert.ok(adopted.length >= 1, `fork child must adopt the parent's block(s) (parent=${JSON.stringify(r.parentBlockIds)} child=${JSON.stringify(r.childBlockIds)})`); + + // Parent session must stay untouched (copy-on-fork). + assert.ok(r.parentUntouched, "parent session must stay untouched"); +}); diff --git a/tests/lineage-reconcile-boot.test.ts b/tests/lineage-reconcile-boot.test.ts new file mode 100644 index 0000000000..ad33f5db4e --- /dev/null +++ b/tests/lineage-reconcile-boot.test.ts @@ -0,0 +1,477 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { listSessions } from "../src/session.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +/** + * lineage-reconcile on boot (#2807): `metadata.derivedFromSessionId` is + * persisted, but before #2807 it was write-only. Both fork adoption paths read + * process-local state — `prefixAffinity.trackedChains` for the byte-prefix + * strong path, the plugin register table for the derived weak path — so a bili + * restart orphans every forked child: it keeps the full raw history while its + * parent's fold ledger sits on disk. This is the restart case the weak-path + * adoption cannot cover (the register table is empty). + * + * reconcileDerivedLineage() runs after boot and re-adopts by raw-id set, + * gated on `resumeInheritance`. + */ + +let scenarioSeq = 0; +function nextRunTag(): string { + scenarioSeq += 1; + return `lrec${scenarioSeq}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function close(server: http.Server): Promise { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +} + +function sseLine(obj: unknown): string { + return `data: ${JSON.stringify(obj)}\n\n`; +} + +function parseRefIds(body: string): string[] { + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null = null; + while ((m = re.exec(body)) !== null) ids.push(m[1]); + return ids; +} + +const FILLER = "the quick brown fox jumps over the lazy dog again and again. "; + +function userText(run: string, i: number): string { + return `run ${run} user turn ${i}: ${FILLER.repeat(12)}`; +} + +function relayReply(body: string, n: number): string { + let lastUser = ""; + try { + const parsed = JSON.parse(body) as { messages?: Array<{ role: string; content: string }> }; + const msgs = parsed.messages ?? []; + for (let i = msgs.length - 1; i >= 0; i--) { + if (msgs[i]!.role === "user") { + lastUser = msgs[i]!.content; + break; + } + } + } catch { + /* fall through with empty echo */ + } + return `run reply ${n} to <${lastUser.slice(0, 48)}>: ${FILLER.repeat(10)}`; +} + +type RelayState = { upstreamReqs: string[]; compressed: boolean }; + +function startMockUpstream(state: RelayState): http.Server { + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + state.upstreamReqs.push(body); + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + const refIds = parseRefIds(body); + if (!state.compressed && refIds.length >= 5) { + state.compressed = true; + const from = refIds[1]!; + const to = refIds[refIds.length - 3]!; + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" } }] })); + res.write(sseLine({ + id: "c1", + object: "chat.completion.chunk", + choices: [{ + index: 0, + delta: { + tool_calls: [{ + index: 0, + id: "call_compress_1", + type: "function", + function: { name: "compress", arguments: JSON.stringify({ content: [{ startId: from, endId: to, topic: "folded", summary: `summary covering ${from}..${to}` }] }) }, + }], + }, + }], + })); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })); + } else { + const text = relayReply(body, state.upstreamReqs.length); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: text } }] })); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 500, completion_tokens: 50 } })); + } + res.write("data: [DONE]\n\n"); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + return server; +} + +type ChatMsg = { role: string; content: string }; + +async function chat(url: string, messages: ChatMsg[], sessionId?: string): Promise { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", ...(sessionId ? { "x-acp-session": sessionId } : {}) }, + body: JSON.stringify({ model: "gpt-test", stream: true, messages }), + }); + if (!res.ok) assert.fail(`HTTP ${res.status}: ${await res.text()}`); + let raw = ""; + for await (const chunk of res.body!) raw += Buffer.from(chunk).toString("utf8"); + let reply = ""; + for (const line of raw.split("\n")) { + if (!line.startsWith("data:")) continue; + const payload = line.slice(5).trim(); + if (payload === "[DONE]") continue; + try { + const parsed = JSON.parse(payload) as { choices?: Array<{ delta?: { content?: string } }> }; + reply += parsed.choices?.[0]?.delta?.content ?? ""; + } catch { + /* ignore keepalives */ + } + } + return reply; +} + +function proxyOpts(relayUrl: string, resumeInheritance?: boolean): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: {} as ProxyOptions["routes"], + modelContextLimit: 1_000_000, + kernelConfig: defaultConfig(1_000_000, { + preserveRecentMessages: 2, + preserveRecentTokens: 400, + compress: { minCompressRange: 200, minSummaryLength: 20, maxSummaryLength: 5000 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + ...(resumeInheritance !== undefined ? { resumeInheritance } : {}), + } as ProxyOptions; +} + +/** Grow a parent past the mock's one-shot fold trigger, then fork a child the + * way pi does: register the lineage, then replay full history + a new tail + * under a fresh session id. The child's request body is NOT a byte-exact + * continuation (position-dependent mock echoes), so the byte-prefix strong + * path fails and only lineage knows the pair. */ +type ForkSetup = { + run: string; + parentId: string; + childId: string; + history: ChatMsg[]; + parentBlockIds: string[]; + parentRefs: Record; +}; + +async function setupForkOnDisk(resumeInheritance?: boolean): Promise { + const run = nextRunTag(); + const parentId = `${run}-A`; + const childId = `${run}-B`; + const state: RelayState = { upstreamReqs: [], compressed: false }; + const relay = startMockUpstream(state); + await listen(relay); + const relayPort = (relay.address() as { port: number }).port; + const opts = proxyOpts(`http://127.0.0.1:${relayPort}/v1/chat/completions`, resumeInheritance); + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${relayPort}/v1/chat/completions`; + try { + const history: ChatMsg[] = []; + for (let i = 1; i <= 8; i++) { + history.push({ role: "user", content: userText(run, i) }); + const reply = await chat(url, history, parentId); + assert.ok(reply.length > 0, `parent turn ${i} must produce a reply`); + history.push({ role: "assistant", content: reply }); + } + const parent = listSessions().find((s) => s.id === parentId); + assert.ok(parent, "parent session must exist"); + const activeBlocks = parent.state.blocks.filter((b) => b.active); + assert.ok(activeBlocks.length >= 1, `parent must have folded a block (got ${activeBlocks.length})`); + + const registerRes = await fetch(`http://127.0.0.1:${proxyPort}/__bili/plugin/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: childId, agent: "pi", parentConversationId: parentId }), + }); + assert.equal(registerRes.status, 200, `register must succeed: ${await registerRes.text()}`); + + const reply1 = await chat(url, [...history, { role: "user", content: userText(`${run}-fork`, 1) }], childId); + assert.ok(reply1.length > 0, "fork first turn must produce a reply"); + const child = listSessions().find((s) => s.id === childId); + assert.ok(child, "fork child session must exist"); + assert.equal(child.metadata.derivedFromSessionId, parentId, "child must record its lineage"); + // The weak-path adoption may already have seeded the child. Strip the + // blocks so we can measure what the BOOT reconcile does on its own — + // that is the path a restart exercises (register table empty). + for (const b of child.state.blocks) child.blockContents.delete(b.blockId); + child.state.blocks.length = 0; + delete child.metadata.derivedBlocksAdopted; + + return { + run, + parentId, + childId, + history, + parentBlockIds: activeBlocks.map((b) => b.blockId), + parentRefs: { ...parent.state.messageRefs.byRaw }, + }; + } finally { + await close(proxy); + await close(relay); + } +} + +test("AC9: boot reconcile adopts the parent's blocks into a restarted fork child", async () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "lrec-")); + process.env.XDG_STATE_HOME = stateDir; + // Stand up the fork with persistence on so both sessions land on disk, then + // tear the proxy down: the child is exactly the post-restart state. + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const setup = await setupForkOnDisk(true); + + // Simulate the restart: a brand-new store (empty in-memory map), then boot. + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const state: RelayState = { upstreamReqs: [], compressed: false }; + const relay = startMockUpstream(state); + await listen(relay); + const relayPort = (relay.address() as { port: number }).port; + const opts = proxyOpts(`http://127.0.0.1:${relayPort}/v1/chat/completions`, true); + const proxy = await startServer(opts); // boot runs reconcileDerivedLineage + await listen(proxy); + try { + const child = listSessions().find((s) => s.id === setup.childId); + assert.ok(child, "fork child must be loaded from disk"); + assert.ok(child.state.blocks.length > 0, "boot reconcile must seed the child with the parent's blocks"); + assert.ok(child.blockContents.size > 0, "adopted blocks must carry their summaries"); + assert.equal(child.metadata.derivedFromSessionId, setup.parentId, "lineage link must survive"); + + const parent = listSessions().find((s) => s.id === setup.parentId); + assert.ok(parent, "parent must also be loaded"); + // Copy-on-fork: the parent keeps every block and ref it had. + for (const id of setup.parentBlockIds) { + assert.ok(parent.state.blocks.some((b) => b.blockId === id), `parent must still own block ${id}`); + } + assert.ok( + Object.keys(setup.parentRefs).every((k) => k in parent.state.messageRefs.byRaw), + "parent must keep all of its refs", + ); + } finally { + await close(proxy); + await close(relay); + } +}); + +test("AC10: reconcile is idempotent across repeated boots", async () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "lrec-")); + process.env.XDG_STATE_HOME = stateDir; + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + // Leaves the child orphaned (no blocks, no marker) — the post-restart state. + const setup = await setupForkOnDisk(true); + + // First boot: must adopt. + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const relay1 = startMockUpstream({ upstreamReqs: [], compressed: false }); + await listen(relay1); + const port1 = (relay1.address() as { port: number }).port; + const proxy1 = await startServer(proxyOpts(`http://127.0.0.1:${port1}/v1/chat/completions`, true)); + await listen(proxy1); + let blocksAfterFirstBoot: string[] = []; + let contentsAfterFirstBoot = 0; + try { + const child = listSessions().find((s) => s.id === setup.childId); + assert.ok(child, "fork child must load from disk"); + assert.ok(child.state.blocks.length > 0, "first boot must adopt the parent's blocks"); + blocksAfterFirstBoot = child.state.blocks.map((b) => b.blockId); + contentsAfterFirstBoot = child.blockContents.size; + } finally { + await close(proxy1); + await close(relay1); + } + + // Second boot: the marker is set and blocks are seeded, so the sweep skips. + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const relay2 = startMockUpstream({ upstreamReqs: [], compressed: false }); + await listen(relay2); + const port2 = (relay2.address() as { port: number }).port; + const proxy2 = await startServer(proxyOpts(`http://127.0.0.1:${port2}/v1/chat/completions`, true)); + await listen(proxy2); + try { + const child = listSessions().find((s) => s.id === setup.childId); + assert.ok(child, "fork child must still load from disk"); + assert.deepEqual( + child.state.blocks.map((b) => b.blockId), + blocksAfterFirstBoot, + "a second boot must not re-adopt or reorder blocks", + ); + assert.equal(child.blockContents.size, contentsAfterFirstBoot, "block contents must not be duplicated"); + + // A child whose parent is not on disk must survive without crashing and + // without consuming the marker, so a later boot can still try. + const { reconcileDerivedLineage } = await import("../src/fork-adoption.ts"); + const logs: Array<[string, string]> = []; + const orphan = { + ...child, + id: `${setup.childId}-orphan`, + state: { + ...child.state, + blocks: [], + messageRefs: { byRaw: { ...child.state.messageRefs.byRaw }, byRef: {} }, + }, + metadata: { + ...child.metadata, + derivedFromSessionId: `${setup.run}-GONE`, + derivedBlocksAdopted: undefined, + }, + } as typeof child; + reconcileDerivedLineage([orphan], { log: (lvl, msg) => logs.push([lvl, msg]), adoptionEnabled: true }); + assert.equal(orphan.state.blocks.length, 0, "an unreachable parent must seed nothing"); + assert.notEqual(orphan.metadata.derivedBlocksAdopted, true, "an unreachable parent must not close the door"); + assert.ok( + logs.some(([lvl, msg]) => lvl === "info" && msg.includes("not on disk")), + "an unreachable parent must be logged, not silently dropped", + ); + } finally { + await close(proxy2); + await close(relay2); + } +}); + +test("AC11: resumeInheritance:false disables boot reconcile", async () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "lrec-")); + process.env.XDG_STATE_HOME = stateDir; + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + // Build the fork with adoption ON so the lineage link is recorded, then + // strip the child's blocks: we want to see only what a gated-off boot does. + const setup = await setupForkOnDisk(true); + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const relay = startMockUpstream({ upstreamReqs: [], compressed: false }); + await listen(relay); + const relayPort = (relay.address() as { port: number }).port; + const proxy = await startServer(proxyOpts(`http://127.0.0.1:${relayPort}/v1/chat/completions`, false)); + await listen(proxy); + try { + const child = listSessions().find((s) => s.id === setup.childId); + assert.ok(child, "fork child must load from disk"); + assert.equal(child.metadata.derivedFromSessionId, setup.parentId, "lineage link must survive the gate"); + assert.notEqual(child.metadata.derivedBlocksAdopted, true, "gate-off must not consume the marker"); + } finally { + await close(proxy); + await close(relay); + } +}); + +// Upstream review finding 2: the sweep walks sessions by lastSeen descending, +// so in a P→C→G chain the grandchild is often reached before the child has +// adopted from its own parent. If G closed its gate while C was still empty, +// G could never retry (the weak derived path also skips once the lineage link +// is persisted) and would depend on preflight compression alone. Every +// non-success branch must leave the marker unset so the next boot retries. +test("AC12: a multi-hop grandchild stays eligible when its intermediate parent has nothing to adopt yet", async () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "lrec-hop-")); + process.env.XDG_STATE_HOME = stateDir; + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const setup = await setupForkOnDisk(true); + const { run, parentId, childId, history } = setup; + + // Build the third generation off the (now block-less) child. + const grandchildId = `${run}-C`; + // compressed:true so this relay answers the grandchild's request directly + // instead of spending its one fold turn on it. + const relay = startMockUpstream({ upstreamReqs: [], compressed: true }); + await listen(relay); + const relayPort = (relay.address() as { port: number }).port; + const proxy = await startServer(proxyOpts(`http://127.0.0.1:${relayPort}/v1/chat/completions`, true)); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + try { + const registerRes = await fetch(`http://127.0.0.1:${proxyPort}/__bili/plugin/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: grandchildId, agent: "pi", parentConversationId: childId }), + }); + assert.equal(registerRes.status, 200, `register must succeed: ${await registerRes.text()}`); + const reply = await chat( + `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${relayPort}/v1/chat/completions`, + [...history, { role: "user", content: userText(`${run}-hop`, 1) }], + grandchildId, + ); + assert.ok(reply.length > 0, "grandchild first turn must produce a reply"); + + const grandchild = listSessions().find((s) => s.id === grandchildId); + assert.ok(grandchild, "grandchild session must exist"); + assert.equal(grandchild.metadata.derivedFromSessionId, childId, "grandchild must record its lineage"); + + // Post-restart shape: both generations stripped, as a restart leaves them + // (the register table and prefixAffinity chains are process-local). + for (const id of [childId, grandchildId]) { + const s = listSessions().find((x) => x.id === id); + assert.ok(s, `${id} must be on disk`); + for (const b of s.state.blocks) s.blockContents.delete(b.blockId); + s.state.blocks.length = 0; + delete s.metadata.derivedBlocksAdopted; + } + } finally { + await close(proxy); + await close(relay); + } + + // Boot: the grandchild has a later lastSeen, so the sweep reaches it first. + _setStoreForTest(new SessionStore({ enabled: true, dir: path.join(stateDir, "sessions") })); + setRegistryForTest({}); + const relay2 = startMockUpstream({ upstreamReqs: [], compressed: false }); + await listen(relay2); + const port2 = (relay2.address() as { port: number }).port; + const proxy2 = await startServer(proxyOpts(`http://127.0.0.1:${port2}/v1/chat/completions`, true)); + await listen(proxy2); + try { + const child = listSessions().find((s) => s.id === childId); + const grandchild = listSessions().find((s) => s.id === grandchildId); + assert.ok(child && grandchild, "both generations must load from disk"); + assert.ok(child.state.blocks.length > 0, "the child must adopt the root's blocks on boot"); + assert.notEqual( + grandchild.metadata.derivedBlocksAdopted, + true, + "a grandchild whose parent was empty at visit time must stay eligible, not close its gate", + ); + } finally { + await close(proxy2); + await close(relay2); + } +}); From c33e1f9c55b31760fc37e258f93dea126695daaa Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 18:07:03 +0800 Subject: [PATCH 3/3] refactor: extract weak-path derived-fork adoption into maybeAdoptDerivedFork (no behavior change) --- src/fork-adoption.ts | 32 ++++++++++++++++++++++++++++++++ src/server/handle.ts | 40 ++-------------------------------------- 2 files changed, 34 insertions(+), 38 deletions(-) diff --git a/src/fork-adoption.ts b/src/fork-adoption.ts index 10915532fc..87736f0e2a 100644 --- a/src/fork-adoption.ts +++ b/src/fork-adoption.ts @@ -358,6 +358,38 @@ export function maybeAdoptResume(args: { } } +/** #2807: the derived (plugin-register) fork link previously recorded + * lineage only and fell back to read-only decompress/search_context — a + * replay-fork child that missed the byte-exact prefix match (timestamp + * drift, a re-decorated tail, a protocol switch) re-sent the whole raw + * history while the parent's fold ledger sat on disk. Adopt the parent's + * fully-present blocks by message-id intersection at link time — the same + * copy-on-fork seeding maybeAdoptResume runs for the strong path, minus the + * byte-prefix requirement. Runs once per session (derivedBlocksAdopted). + * Gated on resumeInheritance, NOT forkAdoption: this is an identified fork + * (the parent came from the plugin register), same class as the strong + * path; #1834/#629 reserve forkAdoption for anonymous forks, and answering + * to two different switches left the weak path dark while the boot-time + * reconcile (below) still adopted. */ +export function maybeAdoptDerivedFork(args: { + session: Session; + parent: Session; + protocol: WireProtocol; + parsed: unknown; + upstreamOrigin: string; + enabled: boolean; + log: (level: string, msg: string) => void; +}): void { + const { session, parent, protocol, parsed, upstreamOrigin, enabled, log } = args; + if (!enabled || session.metadata.derivedBlocksAdopted === true) return; + try { + maybeAdoptResume({ session, parent, sharedDepth: 0, protocol, parsed, upstreamOrigin, blocksEnabled: true, log }); + session.metadata.derivedBlocksAdopted = true; + } catch (e) { + log("warn", `[${session.id}] [derived] block adoption from ${parent.id} failed (${String(e)}); continuing fresh (#2807)`); + } +} + /** * Lineage reconcile on boot (#2807 / #1333): the derived fork lineage is * persisted (`metadata.derivedFromSessionId`, written by handle.ts:1363) but diff --git a/src/server/handle.ts b/src/server/handle.ts index 398b9bf732..041f6e1215 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -37,7 +37,7 @@ import { affinityToken, conversationHeaderSource, claudeSubagentAgentId, claudeS import { personaConversationOrder } from "../session-resolve.js"; import { prefixAffinity, type AnonymousAffinity } from "../prefix-affinity.js"; import { buildAnonymousProvenance, type AnonymousProvenance } from "../anon-provenance.js"; -import { maybeAdoptForkBlocks, maybeAdoptResume } from "../fork-adoption.js"; +import { maybeAdoptForkBlocks, maybeAdoptResume, maybeAdoptDerivedFork } from "../fork-adoption.js"; import { resolveClaudeTranscriptLineage } from "../claude-transcript-lineage.js"; import { consumePluginRegisterFor, pluginAgentHeader, pluginConversationHeader, pluginHeadersMatchModel, pluginReportedContextWindow, pluginReportedMaxOutput, pluginReportedModel, pluginRequestAgentHeader, pluginRuntimeInfoFor, pluginRuntimeInfoForConversation, publicForkInputMatches, recordChainVerdict, recordPluginSession, rememberPluginMessages, resolveConversation, runtimeConversationId, takePendingPluginRegister } from "../plugin.js"; import { scheduleAffinityPersist } from "../affinity-persist.js"; @@ -1394,43 +1394,7 @@ async function handleRequest( session.metadata.derivedFrom = derivedParent; session.metadata.derivedFromSessionId = parentSession.id; markDirty(session); - // #2807-followup: the weak path previously only recorded the - // lineage and fell back to read-only decompress/search_context. - // When the child replays the parent's messages (a fork that - // missed the byte-exact prefix match — timestamp drift, a - // re-decorated tail, a protocol switch), the fold ledger was - // orphaned: every folded block was invisible, so the whole - // raw history was re-sent and re-estimated. Seed the child - // from the parent by message-id intersection — the same - // copy-on-fork adoption the strong resume path runs, minus - // the byte-prefix requirement. Runs once per session. - // - // #2807-audit: gated on resumeInheritance, NOT forkAdoption — - // this is an identified fork (the parent came from the plugin - // register), the same class as the strong path at the top of - // this function, and #1834/#629 reserve forkAdoption for - // anonymous forks. Reading forkAdoption here made the two - // inheritance paths answer to two different switches: with - // its default OFF the weak path never adopted, while the - // boot-time lineage reconcile (src/fork-adoption.ts - // reconcileDerivedLineage) still did. - if (opts.resumeInheritance !== false && session.metadata.derivedBlocksAdopted !== true) { - try { - maybeAdoptResume({ - session, - parent: parentSession, - sharedDepth: 0, - protocol, - parsed, - upstreamOrigin, - blocksEnabled: true, // gated above on resumeInheritance; #1834/#629 reserve forkAdoption for anonymous forks - log, - }); - session.metadata.derivedBlocksAdopted = true; - } catch (adoptErr) { - log("warn", `[${session.id}] [derived] block adoption from ${parentSession.id} failed (${String(adoptErr)}); continuing fresh (#2807)`); - } - } + maybeAdoptDerivedFork({ session, parent: parentSession, protocol, parsed, upstreamOrigin, enabled: opts.resumeInheritance !== false, log }); log("info", `[${session.id}] [derived] linked to parent session ${parentSession.id} (conversation ${derivedParent}) — decompress/search_context fall back to it read-only (#1333)`); } else if (session.metadata.derivedLinkMissLogged !== true) { // The relaxed gate retries resolution on EVERY request until the link