From b7c090d478ba6c3d9059aeb141c52c953bc6a30c Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 14:56:06 +0800 Subject: [PATCH] fix(fork): close the derived-blocks gate only on real block adoption (#3351) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit maybeAdoptDerivedFork set metadata.derivedBlocksAdopted = true unconditionally right after maybeAdoptResume, even when the registered parent had zero folded blocks at first contact. Because the request-time link lands exactly once (handle.ts gates it on derivedFromSessionId === undefined), that prematurely- persisted marker made every later boot sweep skip the session — so a multi-hop grandchild whose intermediate parent was still young (no folds yet) permanently lost block inheritance and kept replaying its full raw history (#2807 symptom recurrence in a P->C->G topology). maybeAdoptResume now returns { adoptedActive, seededRefs } and the gate closes only when adoptedActive > 0 — the same discipline reconcileDerivedLineage already applies (it sets the marker solely on a successful adoption). Ref-only seeding against a young, block-less parent leaves the door open so a later boot can adopt the blocks the parent folds afterwards. Regression tests pin both directions: the gate stays OPEN when the registered parent has no blocks at first contact (fails under the old unconditional set), and CLOSES when the parent carries fully-present blocks. --- src/fork-adoption.ts | 32 +++++-- tests/derived-fork-block-inheritance.test.ts | 91 +++++++++++++++++++- 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/src/fork-adoption.ts b/src/fork-adoption.ts index 87736f0e2a..5de73f8a2b 100644 --- a/src/fork-adoption.ts +++ b/src/fork-adoption.ts @@ -314,6 +314,15 @@ export function maybeAdoptForkBlocks(args: { } } +/** Outcome of an inheritance attempt (#3351): lets the caller tell "blocks + * were adopted" apart from "refs-only / nothing," so the derived-blocks gate + * closes only on real block adoption — the same discipline the boot sweep + * (reconcileDerivedLineage) applies, not on ref-only seeding. */ +interface AdoptionOutcome { + adoptedActive: number; + seededRefs: number; +} + /** #1486: copy-on-resume for an identified client whose resume forked a new * session id (Claude Code --resume). The parent is resolved by the caller * (memory first, then disk) via prefix-affinity's byte-exact full-history @@ -330,19 +339,19 @@ export function maybeAdoptResume(args: { upstreamOrigin: string; blocksEnabled: boolean; log: (level: string, msg: string) => void; -}): void { +}): AdoptionOutcome { const { session, parent, sharedDepth, protocol, parsed, upstreamOrigin, blocksEnabled, log } = args; const incomingMsgs = incomingCoreMessages(protocol, parsed); if (!incomingMsgs) { log("info", `[resume-inheritance] ${session.id}: resumed ${parent.id} (${sharedDepth} shared msgs) but ${protocol} has no adoption support in v1; lineage recorded, refs/blocks not inherited (#1486)`); - return; + return { adoptedActive: 0, seededRefs: 0 }; } const ids = new Set(incomingMsgs.map((m) => m.id)); const plan = planForkAdoption(parent, ids, { seedAllRefs: true, includeBlocks: blocksEnabled }); const seededRefs = Object.keys(plan.refs.byRaw).length; if (seededRefs === 0 && plan.adoptedActive === 0) { log("info", `[resume-inheritance] ${session.id}: resume of ${parent.id} had nothing to inherit (no overlapping refs${blocksEnabled ? " or fully-present blocks" : ""}); starting fresh (#1486)`); - return; + return { adoptedActive: 0, seededRefs: 0 }; } applyForkAdoption(session, plan, parent); log( @@ -356,6 +365,7 @@ export function maybeAdoptResume(args: { const n = Object.keys(storeSlice.byRef).length; 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)`); } + return { adoptedActive: plan.adoptedActive, seededRefs }; } /** #2807: the derived (plugin-register) fork link previously recorded @@ -365,8 +375,12 @@ export function maybeAdoptResume(args: { * 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 + * byte-prefix requirement. The call lands once per session (handle.ts gates + * it on derivedFromSessionId === undefined); the derivedBlocksAdopted marker + * it sets gates the BOOT reconcile, and since #3351 it is set only when blocks + * were actually adopted (mirroring reconcileDerivedLineage), so a young parent + * with no folds yet keeps the door open for a later retry. 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 @@ -383,8 +397,12 @@ export function maybeAdoptDerivedFork(args: { 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; + const outcome = maybeAdoptResume({ session, parent, sharedDepth: 0, protocol, parsed, upstreamOrigin, blocksEnabled: true, log }); + if (outcome.adoptedActive > 0) { + session.metadata.derivedBlocksAdopted = true; + } else { + log("info", `[${session.id}] [derived] no blocks adopted from ${parent.id} yet (refs-only or none fully present); leaving the gate open so the boot reconcile can retry once the parent folds (#3351)`); + } } catch (e) { log("warn", `[${session.id}] [derived] block adoption from ${parent.id} failed (${String(e)}); continuing fresh (#2807)`); } diff --git a/tests/derived-fork-block-inheritance.test.ts b/tests/derived-fork-block-inheritance.test.ts index 21583aa67a..0bcdaa0bf0 100644 --- a/tests/derived-fork-block-inheritance.test.ts +++ b/tests/derived-fork-block-inheritance.test.ts @@ -8,7 +8,7 @@ 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 { maybeAdoptResume, maybeAdoptDerivedFork, incomingCoreMessages } 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"; @@ -364,3 +364,92 @@ test("derived fork inherits parent refs and blocks via message-id intersection", // Parent session must stay untouched (copy-on-fork). assert.ok(r.parentUntouched, "parent session must stay untouched"); }); + +/** + * #3351: the weak-link gate must mirror the boot sweep's discipline — close + * ONLY when blocks were actually adopted. Pre-fix, maybeAdoptDerivedFork set + * derivedBlocksAdopted=true unconditionally right after maybeAdoptResume, so a + * multi-hop grandchild whose registered parent was still young (zero folds) at + * first contact permanently lost eligibility: the link lands exactly once + * (handle.ts gates it on derivedFromSessionId === undefined) and the + * prematurely-persisted marker made every later boot sweep skip it. These pin + * the gate discipline directly at the changed seam; the restart convergence is + * covered by the lineage-reconcile-boot suite (AC9/AC12). + */ + +function sharedWireBody(): { parsed: unknown; ids: string[] } { + const parsed = { + messages: [ + { role: "user", content: "shared turn one" }, + { role: "assistant", content: "shared reply one" }, + ], + }; + const msgs = incomingCoreMessages("openai", parsed); + assert.ok(msgs && msgs.length === 2, "wire body must yield two core messages"); + return { parsed, ids: msgs!.map((m) => m.id) }; +} + +function blankSession(id: string): Session { + return { + id, + metadata: {}, + // A real session always carries a content store; supply an empty one so + // contentStoreOf short-circuits instead of probing the (disabled) store. + contentStore: { version: 1, byHash: {}, byRef: {} }, + state: { blocks: [], messageRefs: { byRaw: {}, byRef: {} }, tokenSnapshot: {}, nextBlockId: 1, nextRunId: 1 }, + blockContents: new Map(), + } as unknown as Session; +} + +function seedParentRefs(parent: Session, ids: string[]): void { + parent.state.messageRefs.byRaw = { [ids[0]!]: "m00001", [ids[1]!]: "m00002" }; + parent.state.messageRefs.byRef = { m00001: ids[0]!, m00002: ids[1]! }; +} + +test("#3351: weak-link gate stays OPEN when the registered parent has no blocks at first contact", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const { parsed, ids } = sharedWireBody(); + const [idA] = [ids[0]!, ids[1]!]; + assert.ok(ids[0] && ids[1] && ids[0] !== ids[1], "core message ids must be distinct"); + + const parent = blankSession("P"); + seedParentRefs(parent, ids); + assert.equal(parent.state.blocks.length, 0, "precondition: parent is young (no folds yet)"); + + const child = blankSession("G"); + child.metadata.derivedFromSessionId = "P"; + maybeAdoptDerivedFork({ session: child, parent, protocol: "openai", parsed, upstreamOrigin: "http://127.0.0.1", enabled: true, log: () => {} }); + + assert.ok(idA in child.state.messageRefs.byRaw, "refs-only inheritance still happens against a young parent"); + assert.equal(child.state.blocks.length, 0, "no block adopted from a block-less parent"); + assert.notEqual(child.metadata.derivedBlocksAdopted, true, "#3351: gate must stay OPEN so a later boot can adopt once the parent folds"); +}); + +test("#3351: weak-link gate CLOSES when the registered parent has fully-present blocks", () => { + _setStoreForTest(new SessionStore({ enabled: false })); + const { parsed, ids } = sharedWireBody(); + + const parent = blankSession("P"); + seedParentRefs(parent, ids); + parent.state.blocks.push({ + blockId: "b1", + runId: 1, + tier: 1, + active: true, + summary: "summary over the shared prefix", + directMessageIds: [ids[0]!], + effectiveMessageIds: [...ids], + directBlockIds: [], + createdAt: 0, + compressedTokens: 900, + } as unknown as (typeof parent.state.blocks)[number]); + parent.blockContents.set("b1", { full: { text: "summary over the shared prefix", count: 1 }, one: null } as never); + + const child = blankSession("G"); + child.metadata.derivedFromSessionId = "P"; + maybeAdoptDerivedFork({ session: child, parent, protocol: "openai", parsed, upstreamOrigin: "http://127.0.0.1", enabled: true, log: () => {} }); + + assert.equal(child.state.blocks.length, 1, "block adopted from a folded parent"); + assert.equal(child.metadata.derivedBlocksAdopted, true, "gate closes on real block adoption"); + assert.ok(child.blockContents.has("b1"), "adopted block carries its stored content"); +});