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
31 changes: 26 additions & 5 deletions src/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,12 @@ interface PreflightFailure {
kind: PreflightFailureKind;
/** A temporary transport failure, not evidence that this context cannot be compressed. */
retryable?: boolean;
/** Pure fold-math proved NO combination of folds can close the gap regardless of
* upstream health (#3461) — the host answers non-retryable 4xx instead of a
* transient 502. Relay-dependent exhaustion (empty/truncated/incomplete
* summaries, budget draws, pool saturation) deliberately leaves this unset:
* those walks can succeed on retry once the relay recovers. */
deterministic?: boolean;
/** Upstream HTTP status when kind === "upstream" and the failure was an HTTP response. */
status?: number;
/** Human-readable cause (safe to surface to the client). */
Expand Down Expand Up @@ -1950,7 +1956,11 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
deps.log("info", `[preflight] raw-fold pool (~${potential} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`);
break;
}
failure = { kind: "exhausted", detail: `futile round: the maximum possible saving from all foldable content (~${potential} tokens${zoneNote}) is below the required reduction (~${deficit} tokens) — no combination of folds can bring the payload under the target. Raise the model context window or restart the session.` };
// #3461: structurally doomed only when NO draw ever came back
// unusable and the pool never dropped — an unusable draw means
// the shortfall may be the relay, not the content, and the
// retry/canary machinery (#726/#2832) owns that case.
failure = { kind: "exhausted", deterministic: lastUnusableDetail === undefined && !poolQueueDrop, detail: `futile round: the maximum possible saving from all foldable content (~${potential} tokens${zoneNote}) is below the required reduction (~${deficit} tokens) — no combination of folds can bring the payload under the target. Raise the model context window or restart the session.` };
deps.log("warn", `[preflight] skipping futile round: max possible saving ~${potential} tok < required ~${deficit} tok${zoneNote}; zero summarization calls spent (#1841)`);
break;
}
Expand All @@ -1976,7 +1986,11 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
deps.log("warn", "[preflight] no compressible ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");
continue;
}
failure = { kind: "exhausted", detail: relaxed ? relaxedExhaustedDetail : subMinNoted
// #3461: every subcase here is structural — nothing compressible
// remains (or nothing above minCompressRange, or the whole relaxed
// zone already folded) — so no retry against a healthier relay can
// change the verdict.
failure = { kind: "exhausted", deterministic: true, detail: relaxed ? relaxedExhaustedDetail : subMinNoted
? `no foldable compressible ranges remain: all ${viable.length} viable range(s) are below minCompressRange (${minChars} chars)`
: "no compressible ranges remain in the conversation" };
break;
Expand Down Expand Up @@ -2657,7 +2671,10 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
deps.log("info", `[preflight] remaining raw-fold pool (~${bailRemaining} tok${zoneNote}) below deficit (~${bailDeficit} tok); deferring to bounded tier-distillation recovery (#2952)`);
break;
}
failure = { kind: "exhausted", detail: `futile round: after the folds so far, the remaining foldable content (~${bailRemaining} tokens${zoneNote}) cannot close the ~${bailDeficit}-token gap to the target even if every remaining range folded successfully.${skipNote} Raise the model context window or restart the session.` };
// #3461: doomed regardless of relay health only when no draw came
// back unusable and the pool never dropped — landed folds prove
// the relay worked, so the residual shortfall is real content.
failure = { kind: "exhausted", deterministic: lastUnusableDetail === undefined && !poolQueueDrop, detail: `futile round: after the folds so far, the remaining foldable content (~${bailRemaining} tokens${zoneNote}) cannot close the ~${bailDeficit}-token gap to the target even if every remaining range folded successfully.${skipNote} Raise the model context window or restart the session.` };
break;
}
if (!failure && !budgetHit && !relaxed && result.payloadEstimate >= limit) {
Expand Down Expand Up @@ -2701,14 +2718,18 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
if (budgetHit) {
failure = { kind: "exhausted", detail: `the preflight summarization budget (${summaryBudget} calls per protection regime) was exhausted before the payload fit the window${unusableNote}${skipNote}` };
} else if (relaxed && result.compressedRanges > 0) {
failure = { kind: "exhausted", detail: `${relaxedExhaustedDetail}${skipNote}` };
// #3461: "folded everything compressible" is only a structural
// verdict when nothing was lost to unusable draws or pool drops.
failure = { kind: "exhausted", deterministic: lastUnusableDetail === undefined && !poolQueueDrop, detail: `${relaxedExhaustedDetail}${skipNote}` };
} else if (result.compressedRanges === 0) {
const cause = poolQueueDrop
? "the shared summary pool was saturated and no summary call was ever dispatched (scheduler congestion, not a chain failure; auto-fold retries next turn)"
: skipReasons.length > 0
? skipReasons.slice(0, 3).join(" | ")
: "each was below minCompressRange, had an unusable summary, or failed to apply";
failure = { kind: "exhausted", detail: rangesTried === 0
// #3461: zero dispatches means the walk never touched the relay —
// the shortfall is structural unless the pool itself dropped work.
failure = { kind: "exhausted", deterministic: rangesTried === 0 && !poolQueueDrop && lastUnusableDetail === undefined, detail: rangesTried === 0
? `no viable range could be compressed: ${cause}${unusableNote}`
: `no range could be compressed across ${rangesTried} viable range${rangesTried === 1 ? "" : "s"}: ${cause}${unusableNote}` };
} else {
Expand Down
35 changes: 27 additions & 8 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1473,13 +1473,16 @@ export type Prepared = {
* ACTUALLY reached the payload, not the pre-gate intent. The model-decided
* gate runs asynchronously between diagNudge's label and the rebuild, so
* consumers that need truth (self-heal streaks, log labels) read this.
* "injected": an advisory/directive/fallback message landed; "vetoed":
* the decision gate ran and nothing was injected (model declined or the
* answer was unusable); "skipped": armed but nothing renderable (empty
* nudge text / yes-with-no-live-range). Undefined = no arm this round, or
* the arm was gated off before delivery was attempted (suppression /
* breaker / gate off) — consumers only ever test for "injected". */
nudgeOutcome?: "injected" | "vetoed" | "skipped";
* "injected": an advisory/directive/fallback message landed; "vetoed":
* the decision gate ran and nothing was injected (model declined or the
* answer was unusable); "skipped": armed but nothing renderable (empty
* nudge text / yes-with-no-live-range); "gated" (#3461): over-limit
* pressure admitted by every standing gate but held by the emergency
* backoff this round — a pressure fact for self-heal credit, not a
* delivery. Undefined = no arm this round, or the arm was gated off
* before delivery was attempted (suppression / breaker / gate off) —
* consumers test for "injected" (+ "gated" where pressure counts). */
nudgeOutcome?: "injected" | "vetoed" | "skipped" | "gated";
/** Render strategy the prepare used for processTurn ("none" for codex
* compaction triggers / ACP_RENDER_NONE). The #422 fold-refresh hook in
* forward() re-runs processTurn with the same strategy so the re-request
Expand Down Expand Up @@ -3449,7 +3452,23 @@ export async function preflightCompressIfNeeded(
}
// The payload still overflows the window: fail fast with a diagnostic
// error instead of forwarding a guaranteed-400 payload (#301).
const status = f?.kind === "upstream" && f.status === 429 ? 503 : 502;
// #3461 problem 2: DETERMINISTIC exhaustion (futile-round math proved no
// combination of folds can close the gap regardless of upstream health)
// can never succeed for this identical payload — answer it 413 like every
// other "can never fit as-is" verdict (#2847 lesson applied to the
// exhaustion path; #2921/#3146 doomed-bytes precedent) instead of 502,
// which status-code-driven headless hosts read as transient and spin on
// forever (field measurement: 5+ doomed rounds). Relay-dependent
// exhaustion (empty/truncated/incomplete summaries, budget draws, pool
// saturation) stays 502: those walks succeed once the relay recovers.
// AND only when bili's own calibrated meter agrees the payload is over the
// window (!payloadFitsWindow): when the calibrated estimate FITS but the
// walk still ran (char-count trigger arm, overflow-armed baseline), the
// doom is a relay-billing artifact bili cannot compute (#496/#767/#857
// byte-relay lanes) — bili must not declare structural doom for it; those
// lanes keep their 502 fail-fast contract where NOT re-forwarding IS the
// protection, not a client spin.
const status = f?.kind === "upstream" && f.status === 429 ? 503 : f?.kind === "exhausted" && f.deterministic && !payloadFitsWindow ? 413 : 502;
// #2189: an explicit retryable=false from preflight (credential-shape
// rejection — deterministic for the identical payload) overrides the
// status-based heuristic below; every other path keeps today's mapping.
Expand Down
58 changes: 58 additions & 0 deletions src/server/budget.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { defaultCountTokens, type CoreMessage, type NudgeDecision } from "acp-kernel";
import { googleSystemText, type BiliMessage, type GoogleRequestBody } from "acp-kernel/wire";
import { estimateCoreMessages } from "../preflight.js";
import { SELF_HEAL_SUPPRESS_CAP_MS, reductionKeyOf } from "../session-self-heal.js";
import type { Session } from "../session.js";
import { applyEstimateCalibration } from "../util.js";
import { readOutputBudget, writeOutputBudget, type OutputBudgetField } from "./side-request.js";

Expand Down Expand Up @@ -348,6 +350,62 @@ export function emergencyNudge(nudge: NudgeDecision | null | undefined, escalati
return !(typeof minBenefit === "number" && Number.isFinite(minBenefit) && minBenefit > 0 && (b.maxPending ?? 0) < minBenefit);
}

/** #3461 problem 2: backoff for the EMERGENCY override. The pure check above
* has no cadence of its own — once usage sits over the escalation line it
* re-arms on EVERY request, so a headless client retrying a doomed request
* injected the tier-1 nudge ~7×/second (field measurement, dsh/pi lanes). A
* repeat injection carries no new information unless something changed that
* could make compression newly viable or newly needed, so this wrapper adds a
* per-session gate stamped on every ALLOWED injection. Re-arm grounds:
* - first injection under the current state (no gate yet / corrupt shape);
* - a reduction landed since (reductionKeyOf moved — same evidence self-heal
* D1 watches: committed fold → nextBlockId advanced, or plugin-lane
* compress tool stamped lastCompress): the payload shrank and still needs
* the prompt;
* - input grew by ≥ the flat growth step since (KDD #8 discipline; the step
* is loopConfig.nudge.growthFloor, flat 50K by default — NOT rescaled with
* the window): new content worth advising about;
* - wall-clock safety valve (SELF_HEAL_SUPPRESS_CAP_MS precedent, 10 min):
* one more injection so a permanently stuck session gets periodic reminders
* instead of silence forever.
* Kernel-driven injections (nudge.shouldInject=true) never pass through here —
* call sites OR them in BEFORE the emergency arm, so normal cadence is
* untouched. State lives in session.metadata.emergencyNudgeGate (survives
* restarts with the snapshot, visible on /__bili/sessions like selfHeal). */
export function emergencyNudgeArmed(
session: Session,
nudge: NudgeDecision | null | undefined,
minCompressRange: number,
tokenCount: number,
growthStep?: number,
): boolean {
if (!emergencyNudge(nudge, undefined, minCompressRange)) return false;
const now = Date.now();
const key = reductionKeyOf(session);
const raw = session.metadata["emergencyNudgeGate"];
if (raw === null || typeof raw !== "object") {
session.metadata["emergencyNudgeGate"] = { at: now, tokens: tokenCount, reductionKey: key };
return true;
}
const g = raw as Record<string, unknown>;
const prevAt = typeof g["at"] === "number" ? g["at"] : NaN;
const prevTokens = typeof g["tokens"] === "number" ? g["tokens"] : NaN;
const prevKey = typeof g["reductionKey"] === "string" ? g["reductionKey"] : undefined;
const step = typeof growthStep === "number" && Number.isFinite(growthStep) && growthStep > 0 ? growthStep : 50_000;
let arm = false;
if (!Number.isFinite(prevAt) || !Number.isFinite(prevTokens) || prevKey === undefined) {
arm = true; // corrupt/legacy shape → re-stamp
} else if (prevKey !== key) {
arm = true; // a reduction landed since the last injection
} else if (tokenCount - prevTokens >= step) {
arm = true; // a full flat-growth step of new content
} else if (now - prevAt >= SELF_HEAL_SUPPRESS_CAP_MS) {
arm = true; // wall-clock safety valve
}
if (arm) session.metadata["emergencyNudgeGate"] = { at: now, tokens: tokenCount, reductionKey: key };
return arm;
}

export function clampOutgoingOutput(
rebuilt: Record<string, unknown>,
field: OutputBudgetField,
Expand Down
9 changes: 7 additions & 2 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2357,13 +2357,18 @@ async function handleRequest(
// model never received. Actual injection subsumes every factor
// the old expression listed: gated-off rounds (suppression /
// breaker / gate off / no arm) leave it undefined or yield
// "vetoed"/"skipped" — never "injected".
// "vetoed"/"skipped" — never "injected". #3461: "gated" joins
// "injected" as active — a pressure round held only by the
// emergency backoff still counts, otherwise the rate limit
// starves the streaks (#2155 zombie degrade, D1 suppression)
// that exist precisely for sessions pinned under continuous
// pressure.
if (!selfHealRoundDone && prepared.nudge !== undefined) {
selfHealRoundDone = true;
evaluateSelfHealRound(session, {
pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined,
biliToolsDeclared: biliToolsDeclaredOnWire(parsed, protocol),
nudgeActive: prepared.nudgeOutcome === "injected",
nudgeActive: prepared.nudgeOutcome === "injected" || prepared.nudgeOutcome === "gated",
biliToolUses: countBiliToolUses(prepared.processedMessages),
degradeAvailable: opts.compress.injectTool && !knobNoInjectTool(),
}, log);
Expand Down
11 changes: 9 additions & 2 deletions src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { logRawStripCounts, markerArtifactCount, stripRawStage } from "../marker
import { imageRescaleMaxDim, renderNone as knobRenderNone } from "../knobs.js";
import { applyImageRescalePass } from "../image-rescale.js";
import { isAutoModeClassifier } from "../auto-mode-forge.js";
import { countSystemAndToolsTokens, emergencyNudge, projectThinkingMass } from "./budget.js";
import { countSystemAndToolsTokens, emergencyNudge, emergencyNudgeArmed, projectThinkingMass } from "./budget.js";
import { effectiveAbsorbBlock } from "./prepare-responses.js";
import { injectSystem, injectTool } from "./inject.js";
import { resolveLaneDecisions } from "./lane-decisions.js";
Expand Down Expand Up @@ -325,7 +325,12 @@ export async function prepareAnthropic(
// consecutive decision failures.
const decideTier1Arm = decide !== undefined && !!turn.nudge && turn.nudge.tier === 1 && turn.nudge.breakdown.emergencyOverride !== 1;
const decideFallbackOverride = decideTier1Arm && ladderMode(session.metadata) === "fallback";
const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && !dshCompressSurfaceOff && (!nudgeSuppressed(session) || decideFallbackOverride) && !compressBreakerArmed(session) && !(autoFoldEngaged(loopConfig, session) && growthFoldingArmed(loopConfig)) && (turn.nudge.shouldInject || emergencyNudge(turn.nudge, undefined, loopConfig.compress.minCompressRange));
const nudgeEligible = opts.compress.injectNudge && !!turn.nudge && !dshCompressSurfaceOff && (!nudgeSuppressed(session) || decideFallbackOverride) && !compressBreakerArmed(session) && !(autoFoldEngaged(loopConfig, session) && growthFoldingArmed(loopConfig));
// #3461: pressure admitted by every standing gate but held by the backoff
// is still an active nudge round — self-heal credit (#2155/#3004) must
// not starve because we chose not to re-inject this round.
const emergencyPressureHeld = nudgeEligible && !!turn.nudge && !turn.nudge.shouldInject && emergencyNudge(turn.nudge, undefined, loopConfig.compress.minCompressRange);
const willInjectNudge = nudgeEligible && !!turn.nudge && (turn.nudge.shouldInject || emergencyNudgeArmed(session, turn.nudge, loopConfig.compress.minCompressRange, tokenCount, loopConfig.nudge.growthFloor));
log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, resolvedModel ?? parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride));
processedMessages = applyReasoningDrop(stripKernelSummaries(turn.messages, turn.state), reasoningPlan, log, sessionId);
// #1001: a silent client history rewrite takes the same archive+prune path
Expand Down Expand Up @@ -454,6 +459,8 @@ export async function prepareAnthropic(
nudgeOutcome = "skipped";
}
}
} else if (emergencyPressureHeld) {
nudgeOutcome = "gated";
}
// [#1343/#1457] surface any earlier undelivered retrieve as an ephemeral
// trailing user note (kept last so it never reorders cached messages).
Expand Down
Loading
Loading