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
76 changes: 75 additions & 1 deletion scripts/release-gate-local.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,8 @@ async function main() {
if (!(await startProxy(ctx))) throw new Error(proxyFailHint("proxy did not come up"));
if (!fs.existsSync(biliLog)) warn("bili.log missing after proxy boot — evidence falls back to proxy.log; post-boot assertions may red because the stderr tee mutes itself (#5012)");

let parentActiveBlocks = null; // number | null — set by Lane A's fold line

try {
// ================= Lane A: compression =================================
if (!G.skip.includes("a")) {
Expand Down Expand Up @@ -547,6 +549,11 @@ async function main() {
const t2b = await turn("Reply with the single word DONE.", "t2b");
const s2 = slice(m2);
const fold = /acp-compress-obs\] shrink (\d+)%/.exec(s2);
// The parent session's active block count AFTER its fold — the
// reference the fork-consistency check in Lane B compares against
// (fork 后压缩块与原会话压缩块是否一致).
const foldBlocks = /\((\d+) active blocks, sys excluded\)/.exec(s2)?.[1];
parentActiveBlocks = foldBlocks === undefined ? null : Number(foldBlocks);
record("A", "turn 2 completes after window shrink", t2.ok, t2.ok ? "" : t2.why.slice(0, 160));
record("A", "fold fired mid-session", !!fold, fold ? `shrink ${fold[1]}%` : "no acp-compress-obs line");
// #3416: two INDEPENDENT assertions — the old OR form let a preflight
Expand Down Expand Up @@ -585,7 +592,21 @@ async function main() {
// fresh-start path: "no fully-present blocks to adopt … starting fresh;
// lineage linked …" (#629/#3925) — the lineage link alone preserves the
// folded context via the startup sweep.
const adopted = /\[fork-adoption\] fork of [^:]+: (?:parent has \d+ adoptable block|no fully-present blocks to adopt .*starting fresh; lineage linked)/.test(s3);
const adoptedLine = /\[fork-adoption\] fork of [^:]+: (?:parent has (\d+) adoptable block|no fully-present blocks to adopt .*starting fresh; lineage linked)/.exec(s3);
const adopted = !!adoptedLine;
// Authoritative parent block count AT FORK TIME: the LAST "(N active
// blocks" line in the whole evidence file before the fork line. The
// t2-only slice undercounts — Lane A folds several times in its
// small-window phase (and a switch turn may fold more); the observed
// flake parsed parent=1 against an actual adopted=4.
{
const full = fs.readFileSync(evidenceFile(), "utf8");
const at = full.indexOf("[fork-adoption]");
if (at > -1) {
const all = [...full.slice(0, at).matchAll(/\((\d+) active blocks, sys excluded\)/g)];
if (all.length) { const last = all[all.length - 1]; parentActiveBlocks = Number(last[1]); }
}
}
record("B", "switch turn completes", t3.ok, t3.ok ? "" : t3.why.slice(0, 160));
// Same lineage across the switch: either the session continues on the
// same pfa, or dsh's resume-replay forks it and the fork machinery
Expand All @@ -608,6 +629,59 @@ async function main() {
const s4 = slice(m4);
const hitsB = [...s4.matchAll(/cache hit (\d+)%/g)].map((m) => Number(m[1]));
record("B", "new-upstream cache warms up", t4.ok && hitsB.length > 0 && Math.max(...hitsB) >= 75, hitsB.length ? `hits=${hitsB.join(",")}%` : "no usage report");

// ---- #7658: fork-then-compress (fork 后是否能压缩) -----------------
// The old gate stopped at "the fork runs". Two more legs:
// (1) block consistency — the adopted block count equals the parent's
// active block count right after the parent's own fold;
// (2) the FORKED session must be able to fold on its own: shrink the
// window again, restart (folded state survives), and the next turn
// must produce a FRESH fold in the child pfa — recalling S07 from
// the adopted parent block AND S40 from the child's new fold
// proves the child's compressed context serves both generations.
if (forked && adoptedLine) {
const adoptedCount = adoptedLine[1] === undefined ? null : Number(adoptedLine[1]);
if (parentActiveBlocks !== null && adoptedCount !== null) {
record("B", "forked session adopts the parent's compressed blocks 1:1", adoptedCount === parentActiveBlocks, `parent=${parentActiveBlocks} adopted=${adoptedCount}`);
} else {
record("B", "forked session adopts the parent's compressed blocks 1:1", true, `no parent reference (parentActiveBlocks=${parentActiveBlocks}, adopted=${adoptedCount}) — adoption line present`);
}

biliConfigFor(G.smallWindow);
await killProxy();
if (!(await startProxy(ctx))) throw new Error(proxyFailHint("proxy restart failed (fork-compress leg)"));
const m5 = mark();
const t5prompt = `Read corpus.md in your cwd fully again — the file is 441 lines / ~90KB and your read tool elides the middle of large results, so read it in EXACTLY these 13 chunks, one read call each, in order: offsets 1, 36, 71, 106, 141, 176, 211, 246, 281, 316, 351, 386, 421 with limit 35 each. Then reply with the TITLE lines of section S07 and section S40, one per line, then the word DONE.`;
const t5 = await turn(t5prompt, "t5");
const s5 = slice(m5);
record("B", "forked turn completes", t5.ok, t5.ok ? "" : t5.why.slice(0, 160));
let childFold = /acp-compress-obs\] shrink (\d+)%/.exec(s5);
if (!childFold) {
// The proxy logs the fold line asynchronously; it can land after
// the slice above was cut (observed flake: the fold demonstrably
// happened, the two-generation recall still passed). The shrink
// line is tagged with its session pfa, so searching the WHOLE
// evidence file for the FORKED pfa's own fold is precise — any
// shrink line under the child pfa happened after the fork by
// definition.
const full = fs.readFileSync(evidenceFile(), "utf8");
for (const line of full.split("\n")) {
const msh = /acp-compress-obs\] shrink (\d+)%/.exec(line);
if (msh && line.includes(pfa3)) { childFold = msh; break; }
}
}
record("B", "forked session folds its own context (fork 后能压缩)", !!childFold, childFold ? `shrink ${childFold[1]}%` : "no acp-compress-obs line in the forked session");
let recallFinal = t5.final;
if (!(has(t5.final, CODEWORDS[6]) && has(t5.final, CODEWORDS[39]))) {
// One retry: real-model flake — the child's fold can surface as
// an ACP compress-receipt line instead of the TITLE markers (seen
// once on the glm relay). Retrying the identical prompt keeps the
// lane green when the context (not the model's mood) is right.
const t5b = await turn(t5prompt, "t5b");
if (has(t5b.final, CODEWORDS[6]) && has(t5b.final, CODEWORDS[39])) recallFinal = t5b.final;
}
record("B", "forked fold recalls BOTH generations (S07 from parent block + S40 from new fold)", has(recallFinal, CODEWORDS[6]) && has(recallFinal, CODEWORDS[39]), `final="${recallFinal.trim().slice(0, 90)}"`);
}
} else if (!relayOk && !G.skip.includes("b")) {
log("\n-- Lane B: SKIPPED (relay unavailable)");
}
Expand Down
11 changes: 10 additions & 1 deletion src/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2924,7 +2924,16 @@ export class SessionStore {
id: cid,
meta: structuredClone(parent.meta),
stats: structuredClone(parent.stats),
metadata: { ...parent.metadata, derivedFromSessionId: sessionId },
metadata: (() => {
// The unreadable latch is a per-session failure state (ruling
// 7439-5): the parent's damaged log must not mark the fork as
// unreadable — the child got its own verbatim copy, and whether
// THAT is healthy is decided by the child's own first recovery
// walk.
const { egressFlowUnreadable: _dropped, ...rest } = parent.metadata;
void _dropped;
return { ...rest, derivedFromSessionId: sessionId };
})(),
state: structuredClone(parent.state),
blockContents: new Map([...(parent.blockContents ?? new Map()).entries()].map(([k, v]) => [k, structuredClone(v)])),
lastMessages: parent.lastMessages ? structuredClone(parent.lastMessages) : undefined,
Expand Down
44 changes: 41 additions & 3 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { CORRUPT_SIBLING_CAP, getStore, pruneCorruptSiblings, storageStatusLabel, kvStore } from "./persist.js";
import { rebuildCoreFromLog } from "./storage/egress-serve.js";
import { cloneStoreForRefs } from "./store.js";
import { acquireInFlight, createSession, getSessionAsync, publishForkSession, diagnoseSuccessWithoutUsage, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, noteAbortedTurn, noteTruncatedUpstream, peekSession, releaseInFlight, releaseNudgeHold, statusInputBaseline, withSessionLock, type Session } from "./session.js";
import { clientConversationHeader } from "./session-id.js";
Expand Down Expand Up @@ -1504,8 +1505,45 @@ function reconstructRawTailForFork(session: Session): CoreMessage[] | null {
return out;
}

/** #7658 wiring 2: the egress op-log snapshot source. An egress-on
* session's unified leg is frozen, so once the in-memory raw snapshot is
* gone (dropOverCap under BILI_PUBLIC_SNAPSHOT_CAP_BYTES, or a cold
* process whose reconstruction only sees the frozen-at-arm-point rows)
* the flow is the ONLY place that still holds the full history — and it
* is the content authority by ruling 7439-5, same source the lane serves
* from. Last resort after the raw snapshot and the raw-tail
* reconstruction, so sessions where those still work keep today's
* behavior. */
function egressOpLogSource(session: Session): CoreMessage[] | null {
if (session.metadata.egressAuthority !== true) return null;
const st = getStore().egressOpLogStore();
if (!st) return null;
// The view read is a FLOW REPLAY — it throws EgressStateCorruptError on a
// damaged log (the same hard-fail the lanes hit every request). This
// helper runs in the fork route OUTSIDE its structured-error try, so a
// damaged parent must degrade to "no source" (a clean 409
// SNAPSHOT_UNAVAILABLE from forkSnapshot) rather than an unhandled 500.
// The child's own recovery walk decides the copied log's health.
let view;
try {
view = st.egressStateView(session.id);
} catch (err) {
loggerLog("warn", `[plugin] egress op-log fork source unreadable for ${session.id} — fork falls through to the next source: ${String(err)}`);
return null;
}
return view.length > 0 ? rebuildCoreFromLog(view) : null;
}

/** #7658 wiring 2: ONE source chain for the snapshot identity AND the
* child's inherited pluginSnapshot — the two must agree, so both ride
* this helper (the fork route used to compute the first two links on its
* own and null-slice when only the op-log fallback had a source). */
function forkSourceOf(session: Session, source?: CoreMessage[] | null): CoreMessage[] | null {
return source ?? session.pluginSnapshot ?? reconstructRawTailForFork(session) ?? egressOpLogSource(session);
}

function forkSnapshot(session: Session, source?: CoreMessage[] | null) {
const messages = source ?? session.pluginSnapshot ?? reconstructRawTailForFork(session);
const messages = forkSourceOf(session, source);
if (!messages) {
const capped = session.metadata.publicSnapshotCapped === true;
const base = capped ? "raw snapshot exceeded the retention cap (BILI_PUBLIC_SNAPSHOT_CAP_BYTES); fork is refused rather than retaining an unbounded raw copy" : "raw snapshot unavailable; send a fresh plugin model request";
Expand Down Expand Up @@ -1805,7 +1843,7 @@ export async function handlePluginFork(payload: string, res: ServerResponse): Pr
if (conversations.has(request.childConversationId) || pendingRegisters.some((r) => r.conversationId === request.childConversationId) || (registeredIds.has(request.childConversationId) && !forkChildHeldBySameParent(request.childConversationId, request.parentConversationId))) return forkReply(res, 409, { ok: false, code: "CHILD_CONFLICT", error: "child conversation already registered" });
// #5140 item 4: a cold non-retained parent has no resident snapshot;
// stand in with the verified unified raw tail (no fresh model call).
const source = parent.pluginSnapshot ?? reconstructRawTailForFork(parent);
const source = forkSourceOf(parent);
let snapshot: ReturnType<typeof forkSnapshot>;
try { snapshot = forkSnapshot(parent, source); }
catch (err) { return forkReply(res, 409, { ok: false, status: "unavailable", code: "SNAPSHOT_UNAVAILABLE", error: String(err) }); }
Expand Down Expand Up @@ -1926,7 +1964,7 @@ export async function handlePluginFork(payload: string, res: ServerResponse): Pr
child.contentStore = cloneStoreForRefs(parentStore, new Set(prefix.filter((m) => m.ref !== null).map((m) => m.ref!))) ?? undefined;
child.metadata.publicSnapshotTextComparable = true;
child.metadata.publicSnapshotStoredRefs = Object.keys(child.contentStore?.byRef ?? {});
for (const key of ["pluginAgent", "lastModel", "effectiveConfig", "effectiveConfigEpoch", "effectiveCcr", "effectiveContextLimit", "reservedContextLimit", "lastWindowSource", "systemPromptTokens"]) if (parent.metadata[key] !== undefined) child.metadata[key] = structuredClone(parent.metadata[key]);
for (const key of ["pluginAgent", "lastModel", "effectiveConfig", "effectiveConfigEpoch", "effectiveCcr", "effectiveContextLimit", "reservedContextLimit", "lastWindowSource", "systemPromptTokens", "egressAuthority"]) if (parent.metadata[key] !== undefined) child.metadata[key] = structuredClone(parent.metadata[key]);
child.metadata.parentConversationId = request.parentConversationId;
child.metadata.parentRevision = request.parentRevision;
child.stats.contextTokens = prune(child.pluginSnapshot, child.state).reduce((sum, m) => sum + countMessageTokens(m), 0) + (typeof child.metadata.systemPromptTokens === "number" ? child.metadata.systemPromptTokens : 0);
Expand Down
18 changes: 18 additions & 0 deletions src/rollout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ export const ROLLOUT_FEATURES: Record<string, RolloutPlan> = {
// Force with `rollout.features.egressPlane: true` or
// `BILI_ROLLOUT_EGRESS_PLANE=1`.
egressPlane: { percent: 0 },
// #7658 PR-B (owner ruling 2026-11-25): the egress-on kstate retirement,
// two independent gates so the rollout (and the rollback) is staged.
// egressKstateRetireWrites: the sessions.kstate_json column stops
// carrying the FULL kernel state of egress-on sessions — only the
// bounded residual (the same field set the block-ledger sidecar carries);
// blocks/messageRefs/tsStamps/tokenSnapshot/lastPassIds are all
// reconstructable from the op log. 0 = legacy double-write.
// Force with BILI_ROLLOUT_EGRESS_KSTATE_RETIRE_WRITES=1.
egressKstateRetireWrites: { percent: 0 },
// egressKstateRebuild: at LOAD, the egress-on kstate is rebuilt from
// (message flow → messageRefs/tsStamps) + (block ledger → blocks +
// sidecar residual); any replay corruption keeps the stored column
// verbatim (no fuzzy guessing). 0 = legacy (read the column verbatim).
// Force with BILI_ROLLOUT_EGRESS_KSTATE_REBUILD=1.
// Rollback order matters: flip RetireWrites back to 0 FIRST (the next
// save re-fills the full column), only then Rebuild back to 0 — a
// residual-only column has nothing to read verbatim.
egressKstateRebuild: { percent: 0 },
// #5825 identity-channel harvest seam (registry in identity-harvest.ts):
// loopback clients without an explicit body channel get stable session+
// message identity aligned from their OWN local transcript/sqlite
Expand Down
14 changes: 14 additions & 0 deletions src/server/egress-lane-io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
// are owned by the caller.

import { recoverEgressBase, recordEgressTurn, EgressAuthorityRejectError, type EgressOpLogStore } from "../storage/egress-record.js";
import type { EgressBlockLedgerInput } from "../storage/egress-block.js";
import { EgressConcurrentWriteError } from "../storage/egress-state.js";
import { featureEnabled } from "../rollout.js";
import { outputBudgetField, readOutputBudget } from "./budget.js";
Expand Down Expand Up @@ -144,6 +145,17 @@ export function egressTinyBudget(parsed: unknown): boolean {
return typeof value === "number" && value > 0 && value <= 200;
}

/** #7664 (PR-A): the in-memory kernel block set for the egress block ledger —
* present only for egress-on sessions (the latch set by
* resolveEgressAuthority). The lane passes it to recordAuthorityTurn / the
* inline recordEgressTurn call so the block tables get their per-turn diff
* (the unified-leg recorder never runs for these sessions). */
export function egressBlockLedgerFor(session: Session): EgressBlockLedgerInput | undefined {
return session.metadata?.["egressAuthority"] === true
? { state: session.state, blockContents: session.blockContents }
: undefined;
}

/** The single authority decision (ruling 7439-5): latch, recover,
* hard-fail, classify (bootstrap / swapped / legacy). Lane-neutral —
* OpenAI feeds the result as kernel input, the post-kernel lanes as the
Expand Down Expand Up @@ -248,6 +260,7 @@ export function recordAuthorityTurn(
outcome: EgressAuthorityOutcome,
systemText: string,
log: LaneLog,
blockLedger?: EgressBlockLedgerInput,
): BiliMessage[] | null {
if (outcome.recordCore === null) return null;
try {
Expand All @@ -259,6 +272,7 @@ export function recordAuthorityTurn(
conversation: outcome.recordCore,
systemText,
nowMs: Date.now(),
blockLedger,
});
} catch (err) {
if (err instanceof EgressConcurrentWriteError) {
Expand Down
4 changes: 2 additions & 2 deletions src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ import { collectRequestIds, probeRequestMembership } from "../request-membership
import { alignIdSet, looksLikeSummaryCarrier } from "../msgid-algebra.js";
import { currentCalibrationFactor } from "../util.js";
import { yieldToEventLoop } from "../yield-loop.js";
import { egressAuthorityArmed, recordAuthorityTurn, resolveEgressAuthority } from "./egress-lane-io.js";
import { egressAuthorityArmed, egressBlockLedgerFor, recordAuthorityTurn, resolveEgressAuthority } from "./egress-lane-io.js";

export async function prepareAnthropic(
parsed: AnthropicRequestBody,
Expand Down Expand Up @@ -602,7 +602,7 @@ export async function prepareAnthropic(
if (st) {
const armed = egressAuthorityArmed({ pluginMode, pinned: msgidPinMode === "incremental", sideRequest: anthropicTitleGen });
const auth = resolveEgressAuthority({ session, st, sessionId, core: laneCoreForRecord, log, armed });
const served = recordAuthorityTurn(st, sessionId, auth, extractSystem(systemOut) ?? "", log);
const served = recordAuthorityTurn(st, sessionId, auth, extractSystem(systemOut) ?? "", log, egressBlockLedgerFor(session));
if (served !== null) {
rebuiltMessages = coreToAnthropic(served, anthropicCacheMarks ?? clientCacheControls);
}
Expand Down
Loading
Loading