Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions src/fork-adoption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,3 +357,136 @@ 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)`);
}
}

/** #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
* 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) {
// 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) {
// 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) {
// 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);
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;
}
20 changes: 19 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -439,6 +439,24 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
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 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,
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.
Expand Down
3 changes: 2 additions & 1 deletion src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -1394,6 +1394,7 @@ async function handleRequest(
session.metadata.derivedFrom = derivedParent;
session.metadata.derivedFromSessionId = parentSession.id;
markDirty(session);
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
Expand Down
Loading
Loading