diff --git a/src/preflight.ts b/src/preflight.ts index fa6126e3fc..79f486526c 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -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). */ @@ -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; } @@ -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; @@ -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) { @@ -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 { diff --git a/src/server.ts b/src/server.ts index 4225814ccc..229056ebc7 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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 @@ -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. diff --git a/src/server/budget.ts b/src/server/budget.ts index 265ac8e372..68beb94a07 100644 --- a/src/server/budget.ts +++ b/src/server/budget.ts @@ -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"; @@ -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; + 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, field: OutputBudgetField, diff --git a/src/server/handle.ts b/src/server/handle.ts index 47cafeb2df..de34135e3f 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -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); diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index 1f292c589e..d23fd7c9fb 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -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"; @@ -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 @@ -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). diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 577ef21757..49fff948c3 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -23,7 +23,7 @@ import { reconcileSystemAnchor } from "../system-anchor.js"; import { logRawStripCounts, markerArtifactCount, stripRawStage } from "../marker/engine.js"; import { imageRescaleMaxDim, renderNone as knobRenderNone } from "../knobs.js"; import { applyImageRescalePass } from "../image-rescale.js"; -import { clampOutgoingOutput, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge } from "./budget.js"; +import { clampOutgoingOutput, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed } from "./budget.js"; import { estimateCoreMessages } from "../preflight.js"; import { effectiveAbsorbBlock } from "./prepare-responses.js"; import { injectGoogleTool, injectTool } from "./inject.js"; @@ -205,7 +205,12 @@ export async function prepareGoogle( // advisory punches through per 3 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 && shouldInject && !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 && shouldInject && !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, model, willInjectNudge, decideTier1Arm && !decideFallbackOverride)); processedMessages = stripKernelSummaries(turn.messages, turn.state); // #1001: a silent client history rewrite takes the same archive+prune path @@ -308,6 +313,8 @@ export async function prepareGoogle( nudgeOutcome = "skipped"; } } + } else if (emergencyPressureHeld) { + nudgeOutcome = "gated"; } } catch (err) { log("warn", `[${sessionId}] kernel transform failed, forwarding unchanged: ${String(err)}`); diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 3a6ea9aa20..f9bddb260c 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -27,7 +27,7 @@ import { reconcileSystemAnchor } from "../system-anchor.js"; import { logRawStripCounts, markerArtifactCount, stripRawStage } from "../marker/engine.js"; import { imageRescaleMaxDim, renderNone as knobRenderNone } from "../knobs.js"; import { applyImageRescalePass } from "../image-rescale.js"; -import { clampOutgoingOutput, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge } from "./budget.js"; +import { clampOutgoingOutput, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed } from "./budget.js"; import { effectiveAbsorbBlock } from "./prepare-responses.js"; import { injectOpenaiTool, injectTool } from "./inject.js"; import { resolveLaneDecisions } from "./lane-decisions.js"; @@ -222,7 +222,12 @@ export async function prepareOpenai( // counter on the same round, so at most ONE legacy advisory punches // through per DECIDE_FALLBACK_THRESHOLD consecutive decision failures. const decideFallbackOverride = decideTier1Arm && ladderMode(session.metadata) === "fallback"; - const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && !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 && shouldInject && !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, 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 @@ -354,6 +359,8 @@ export async function prepareOpenai( 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). diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 310f3c4756..2263705769 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -32,7 +32,7 @@ import type { ConversationIdentity } from "../session-id.js"; import { logRawStripCounts, markerArtifactCount, stripRawStage } from "../marker/engine.js"; import { imageRescaleMaxDim, keepResponseId as knobKeepResponseId, noCompressPrompt as knobNoCompressPrompt, noInjectTool as knobNoInjectTool, renderNone as knobRenderNone } from "../knobs.js"; import { applyImageRescaleItems } from "../image-rescale.js"; -import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, modelVisibleTools } from "./budget.js"; +import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed, modelVisibleTools } from "./budget.js"; import { FORCE_TEXT_PROTOCOL, injectResponsesTool, injectTool } from "./inject.js"; import { resolveLaneDecisions } from "./lane-decisions.js"; @@ -322,7 +322,12 @@ export async function prepareResponses( // advisory punches through per 3 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 && compressSurfaceOn && !isCompactionTrigger && (!nudgeSuppressed(session) || decideFallbackOverride) && !compressBreakerArmed(session) && !(autoFoldEngaged(loopConfig, session) && growthFoldingArmed(loopConfig, codexLane && codexCompactMode() === "intercept" ? loopConfig.modelContextLimit * CODEX_COMPACT_HEALTH_RATIO : undefined)) && (turn.nudge.shouldInject || emergencyNudge(turn.nudge, undefined, loopConfig.compress.minCompressRange)); + const nudgeEligible = opts.compress.injectNudge && !!turn.nudge && compressSurfaceOn && !isCompactionTrigger && (!nudgeSuppressed(session) || decideFallbackOverride) && !compressBreakerArmed(session) && !(autoFoldEngaged(loopConfig, session) && growthFoldingArmed(loopConfig, codexLane && codexCompactMode() === "intercept" ? loopConfig.modelContextLimit * CODEX_COMPACT_HEALTH_RATIO : undefined)); + // #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, parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride)); processedMessages = repairResponsesAssistantOrdering(applyReasoningDrop(stripKernelSummaries(turn.messages, turn.state), reasoningPlan, log, sessionId), originalMessages); reapOrphansLogged(session, msgs, log, sessionId); @@ -456,6 +461,8 @@ export async function prepareResponses( nudgeOutcome = "skipped"; } } + } else if (emergencyPressureHeld) { + nudgeOutcome = "gated"; } transformOk = true; } catch (err) { diff --git a/src/session-self-heal.ts b/src/session-self-heal.ts index 45082f5ca1..b58e13c756 100644 --- a/src/session-self-heal.ts +++ b/src/session-self-heal.ts @@ -120,7 +120,11 @@ function armSelfHeal(session: Session, detected: "plugin-lane-gone" | "nudge-idl session.metadata["selfHeal"] = { detected, action, since: Date.now() }; } -function reductionKey(session: Session): string { +/** Fingerprint of "a reduction landed": a committed fold advances + * nextBlockId (or the plugin-lane compress tool stamps lastCompress). Exported + * so other nudge machinery (#3461 emergency backoff) watches the SAME evidence + * instead of inventing a parallel signal. */ +export function reductionKeyOf(session: Session): string { return `${session.state.nextBlockId}:${session.lastCompress?.at ?? 0}`; } @@ -142,7 +146,8 @@ type SelfHealRoundInputs = { pluginHeaderPresent: boolean; /** the request's own tools array declares bili tools (live MCP lane) */ biliToolsDeclared: boolean; - /** a nudge was actually injected into this round's payload */ + /** a nudge was injected into this round's payload, or the round carried + * admitted over-limit pressure held only by the #3461 backoff ("gated") */ nudgeActive: boolean; /** bili tool_use entries in the re-sent history (plugin-mode evidence the agent is still compressing) */ biliToolUses: number; @@ -159,7 +164,7 @@ type LogFn = (level: "info" | "warn", message: string) => void; export function evaluateSelfHealRound(session: Session, inputs: SelfHealRoundInputs, log: LogFn): void { const st = counters.get(session) ?? { lastReductionKey: undefined, zombieStreak: 0, idleStreak: 0 }; counters.set(session, st); - const key = reductionKey(session); + const key = reductionKeyOf(session); const reduction = st.lastReductionKey !== undefined && key !== st.lastReductionKey; st.lastReductionKey = key; diff --git a/tests/issue1841-preflight-futility.test.ts b/tests/issue1841-preflight-futility.test.ts index f0207c9e9b..0e5536c154 100644 --- a/tests/issue1841-preflight-futility.test.ts +++ b/tests/issue1841-preflight-futility.test.ts @@ -167,7 +167,7 @@ test("#1841 A: a payload whose foldable pool cannot close the gap skips the roun ]; const resp = await post(p, "issue1841-futility-skip", messages); const body = await resp.text(); - assert.equal(resp.status, 502, `a futile round must fail fast: HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.equal(resp.status, 413, `a futile round must fail fast non-retryably (#3461): HTTP ${resp.status} ${body.slice(0, 240)}`); const json = JSON.parse(body) as { error?: { code?: string; message?: string } }; assert.equal(json.error?.code, "preflight_compress_failed"); assert.match(json.error?.message ?? "", /futile round/, `names the futility verdict (got: ${json.error?.message})`); @@ -246,6 +246,9 @@ test("#1841 B: mid-walk bail stops before summarizing ranges that cannot change ]; const resp = await post(p, "issue1841-futility-midbail", messages); const body = await resp.text(); + // Relay-dependent by fixture design (every summary comes back empty): + // a healthy relay could still fold the drawn range, so this verdict + // stays the retryable 502 — unlike case A's zero-call structural 413. assert.equal(resp.status, 502, `a bailed walk must fail fast: HTTP ${resp.status} ${body.slice(0, 240)}`); const json = JSON.parse(body) as { error?: { code?: string; message?: string } }; assert.equal(json.error?.code, "preflight_compress_failed"); diff --git a/tests/issue2155-self-heal.test.ts b/tests/issue2155-self-heal.test.ts index b1e4bb3a9a..f7e09b3ece 100644 --- a/tests/issue2155-self-heal.test.ts +++ b/tests/issue2155-self-heal.test.ts @@ -299,20 +299,20 @@ test("integration: nudge-idle loop (non-plugin) suppresses the nudge after the w }); try { const body = { model: "m", max_tokens: 20_000, messages: turn2Compressible() }; + const len = () => ((received[received.length - 1]!.messages as unknown[]) ?? []).length; await send({}, body); // r1 baseline — usage lands only after its own response (no nudge yet, no idle credit) - for (let i = 0; i < SELF_HEAL_WINDOW - 2; i++) await send({}, body); // r2..r4 — nudged, idle credit 3 - await send({}, body); // r5 — nudged, idle credit 4 - const before = ((received[received.length - 1]!.messages as unknown[]) ?? []).length; // nudged count + const base = len(); + await send({}, body); // r2 — first pressure round: the backoff gate opens once, nudged (idle credit 1) + assert.equal(len(), base + 1, "the first over-limit round still carries the nudge"); + for (let i = 0; i < SELF_HEAL_WINDOW - 2; i++) await send({}, body); // r3..r5 — #3461 backoff holds: no repeat injection, but the gated pressure rounds still earn idle credit (2..4) + assert.equal(len(), base, "#3461: no storm — the held rounds carry no nudge"); const sh = listSessions().find((x) => x.id === sessionId)!.metadata.selfHeal; - assert.equal(sh, undefined, "not yet armed at window-1 idle rounds"); - await send({}, body); // r6 — the 5th nudged idle round arms AFTER its own nudge went out + assert.equal(sh, undefined, "not yet armed at window-1 idle credits"); + await send({}, body); // r6 — the 5th credited pressure round arms suppression const armed = listSessions().find((x) => x.id === sessionId)!.metadata.selfHeal as { action: string }; assert.equal(armed.action, "suppress-nudge"); await send({}, body); // r7 runs suppressed - const suppressed = ((received[received.length - 1]!.messages as unknown[]) ?? []).length; - const nudged = ((received[received.length - 2]!.messages as unknown[]) ?? []).length; - assert.ok(nudged === before + 1 - 1, "the arming round was still nudged (baseline round carried no nudge)"); - assert.ok(suppressed === before - 1, "nudge message gone once suppression armed (back to the un-nudged count)"); + assert.equal(len(), base, "suppression keeps the nudge gone"); } finally { proxy.close(); proxy.closeIdleConnections?.(); diff --git a/tests/issue3461-overlimit-exits.test.ts b/tests/issue3461-overlimit-exits.test.ts new file mode 100644 index 0000000000..a3fdbc4bda --- /dev/null +++ b/tests/issue3461-overlimit-exits.test.ts @@ -0,0 +1,216 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +// #3461 problem 2 (real-model stress test, dsh/pi lanes, qwen3.8-27b @ sglang): +// a session pinned over its window with less foldable mass than the deficit had +// NO exit — preflight answered 502 (read as transient by status-code-driven +// headless hosts, which spun through 5+ doomed rounds) while the EMERGENCY +// tier-1 nudge override re-armed on EVERY request (measured 7 injections in +// 1 second). Pinned here: +// 1. unit — emergencyNudgeArmed: the override injects once per state; it +// re-arms only on a landed reduction, a full flat-growth step of new +// content, or the 10-minute wall-clock safety valve. Kernel-driven +// injections (shouldInject=true) never pass through the gate. +// 2. e2e — a payload that can never fit (oversized system prompt, nothing +// foldable left) fails fast 413 non-retryable instead of 502, and the +// dead-end cooldown replays the same verdict without touching the +// upstream again. + +import { defaultConfig, type NudgeDecision } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions, _resetSessionsForTest, type Session } from "../src/session.ts"; +import { emergencyNudgeArmed } from "../src/server/budget.ts"; +import { SELF_HEAL_SUPPRESS_CAP_MS } from "../src/session-self-heal.ts"; + +// ---- Part A: unit — the emergency override backoff gate --------------------- + +function mkSession(): Session { + return { + id: "s3461", + metadata: {}, + state: { nextBlockId: 1 }, + lastCompress: undefined, + } as unknown as Session; +} + +/** Over-limit (>= 0.7 escalation line), kernel declined (cadence), one + * executable range — the exact shape that made the pure check fire every + * request in the field report. */ +function overLimitDeclined(usage = 0.85): NudgeDecision { + return { shouldInject: false, contextUsage: usage, compressibleRanges: [{ chars: 20_000 }] } as unknown as NudgeDecision; +} + +test("#3461 unit: seven identical doomed retries inject the emergency nudge exactly once", () => { + const s = mkSession(); + const results = Array.from({ length: 7 }, () => emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000)); + assert.deepEqual(results, [true, false, false, false, false, false, false], "first retry arms, the rest stay quiet"); + const gate = s.metadata["emergencyNudgeGate"] as Record; + assert.equal(gate["tokens"], 90_000, "gate stamped with the injecting token count"); + assert.equal(gate["reductionKey"], "1:0", "gate stamps the reduction fingerprint"); + assert.equal(typeof gate["at"], "number"); +}); + +test("#3461 unit: a landed reduction re-arms the emergency nudge", () => { + const s = mkSession(); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), true); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), false); + s.state.nextBlockId = 2; // committed fold advanced the block cursor + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), true, "shrunken payload still needs the prompt"); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), false, "and stays quiet again until the next change"); +}); + +test("#3461 unit: only a full flat-growth step re-arms (no window rescaling)", () => { + const s = mkSession(); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), true); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000 + 49_999), false, "sub-step growth is noise"); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000 + 50_000), true, "a full 50K step is new content worth advising about"); + const s2 = mkSession(); + assert.equal(emergencyNudgeArmed(s2, overLimitDeclined(), 0, 1_000, 1_000), true); + assert.equal(emergencyNudgeArmed(s2, overLimitDeclined(), 0, 1_999, 1_000), false); + assert.equal(emergencyNudgeArmed(s2, overLimitDeclined(), 0, 2_000, 1_000), true, "honors the caller-supplied growth step"); +}); + +test("#3461 unit: wall-clock safety valve re-arms once after the cap", () => { + const realNow = Date.now; + let fake = 1_000_000; + Date.now = () => fake; + try { + const s = mkSession(); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), true); + fake += 9 * 60_000; + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), false, "under the cap: quiet"); + fake += 2 * 60_000; // total >= SELF_HEAL_SUPPRESS_CAP_MS (10 min) + assert.ok(fake - 1_000_000 >= SELF_HEAL_SUPPRESS_CAP_MS, "test clock crossed the cap"); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), true, "permanently stuck sessions still get periodic reminders"); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(), 0, 90_000), false, "the valve fires once, then the gate holds again"); + } finally { + Date.now = realNow; + } +}); + +test("#3461 unit: below the escalation line the gate never arms or stamps", () => { + const s = mkSession(); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(0.5), 0, 90_000), false); + assert.equal(emergencyNudgeArmed(s, overLimitDeclined(0.69), 0, 90_000), false); + assert.equal(s.metadata["emergencyNudgeGate"], undefined, "no state written for a declined pure check"); +}); + +test("#3461 unit: kernel-driven injections never pass through the gate", () => { + const s = mkSession(); + const kernelDriven = { shouldInject: true, contextUsage: 0.9, compressibleRanges: [{ chars: 20_000 }] } as unknown as NudgeDecision; + assert.equal(emergencyNudgeArmed(s, kernelDriven, 0, 90_000), false, "call sites OR shouldInject in BEFORE the emergency arm"); + assert.equal(s.metadata["emergencyNudgeGate"], undefined, "and must not consume the emergency gate"); +}); + +test("#3461 unit: no executable range keeps the pure-check refusal", () => { + const s = mkSession(); + const none = { shouldInject: false, contextUsage: 0.9, compressibleRanges: [] } as unknown as NudgeDecision; + assert.equal(emergencyNudgeArmed(s, none, 0, 90_000), false); + assert.equal(s.metadata["emergencyNudgeGate"], undefined); +}); + +// ---- Part B: e2e — deterministic exhaustion answers 413, not 502 ------------ + +// 8k keeps the fixed compress surface (system section + tool schemas, ~4.6k +// tokens measured — see issue #3461 problem 3) inside the window so turn 1 +// fits, while the 60k-char system swap on turn 2 still overshoots by ~2.5x. +const WINDOW = 8_000; + +function okSse(inputTokens: number): string { + const start: Record = { type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: inputTokens } } }; + const delta: Record = { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } }; + return ( + `event: message_start\ndata: ${JSON.stringify(start)}\n\n` + + `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } })}\n\n` + + `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: 0 })}\n\n` + + `event: message_delta\ndata: ${JSON.stringify(delta)}\n\n` + + `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n` + ); +} + +type Msg = { role: string; content: unknown }; + +test("#3461 e2e: a payload that can never fit fails fast 413 non-retryable, cooldown replays without upstream calls", async () => { + _resetSessionsForTest(); + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + let upstreamCalls = 0; + const server = http.createServer((_req, res) => { + upstreamCalls += 1; + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(okSse(500)); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const port = (server.address() as { port: number }).port; + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${port}`]: { models: { "claude-relay": { context: WINDOW } } } }, + modelContextLimit: WINDOW, + kernelConfig: defaultConfig(WINDOW), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + compat: { roles: {} }, streamErrorShape: "protocol", passthroughSource: null, autoRestartOnUpdate: false, updateTag: "latest", advisoryCheck: false, releaseNotesCheck: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const id = "sess-3461-exhausted"; + const url = `http://127.0.0.1:${(proxy.address() as { port: number }).port}/bili/http://127.0.0.1:${port}/v1/messages`; + const headers = { "content-type": "application/json", "x-acp-session": id }; + const post = (system: string, messages: Msg[]) => fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: "claude-relay", max_tokens: 1024, stream: true, system, messages }), + }); + try { + // Turn 1: normal-sized payload, succeeds, arms the usage-grade baseline + // and route evidence (so turn 2 takes the sizing path, not the + // fresh-session forward-once arbitration). + const smallSystem = "You are a helpful assistant."; + const r1 = await post(smallSystem, [{ role: "user", content: "go?" }]); + assert.equal(r1.status, 200, "turn 1 succeeds"); + await r1.text(); + + // Turn 2: the client swaps in an oversized system prompt (~60k chars ≈ + // well over the 4k window) on top of the short history. The system + // prompt is never foldable and the three history messages sit inside + // the protected recent zone — no combination of folds closes the gap, + // so the walk exhausts deterministically. + const hugeSystem = "S".repeat(60_000); + const r2 = await post(hugeSystem, [{ role: "user", content: "go?" }, { role: "assistant", content: "ok" }, { role: "user", content: "again?" }]); + const j2 = (await r2.json()) as Record; + assert.equal(r2.status, 413, `deterministic exhaustion must answer 413 (pre-#3461: 502), got ${r2.status}: ${JSON.stringify(j2)}`); + const err = j2["error"] as Record; + assert.match(String(err?.["message"]), /NOT forwarded/, "the diagnostic says the payload was not forwarded"); + assert.match(String(err?.["message"]), /exhaust|window|session/i, "the diagnostic carries the exhaustion reason"); + + // Turn 3: identical payload hits the dead-end cooldown — same verdict, + // zero upstream traffic. + const before = upstreamCalls; + const r3 = await post(hugeSystem, [{ role: "user", content: "go?" }, { role: "assistant", content: "ok" }, { role: "user", content: "again?" }]); + assert.equal(r3.status, 413, "cooldown replays the 413 verdict"); + await r3.text(); + assert.equal(upstreamCalls, before, "the cooldown round must not touch the upstream"); + const s = listSessions().find((x) => x.id === id); + assert.ok(s, "session exists"); + assert.equal((s!.metadata.preflightDeadEnd as Record)["status"], 413, "the dead-end marker carries the 413 status"); + } finally { + await new Promise((r) => proxy.close(() => r())); + await new Promise((r) => server.close(() => r())); + } +}); diff --git a/tests/issue496-forward-once-learn.test.ts b/tests/issue496-forward-once-learn.test.ts index cdf3d3ca30..f23c20e29c 100644 --- a/tests/issue496-forward-once-learn.test.ts +++ b/tests/issue496-forward-once-learn.test.ts @@ -128,14 +128,17 @@ mitm: { enabled: false, domains: [] }, // --- Request 2: overflow EVIDENCE now exists → NO forward-once → fail-fast --- const r2 = await fetch(url, { method: "POST", headers, body: screenshotPayload() }); - assert.equal(r2.status, 502, "second request fails fast instead of forwarding again"); + // #3461: the image payload is over-window per bili's own meter and no + // fold can close the gap — a structurally doomed verdict answers 413 + // (non-retryable) instead of the legacy 502. + assert.equal(r2.status, 413, "second request fails fast instead of forwarding again"); const err2 = JSON.parse(await r2.text()) as { error?: { code?: string } }; assert.equal(err2.error?.code, "preflight_compress_failed"); assert.deepEqual(streamForwards, [true], "request 2 was NEVER forwarded (loop broken after one rejection)"); // --- Request 3: stable — still fail-fast, still exactly one forward total --- const r3 = await fetch(url, { method: "POST", headers, body: screenshotPayload() }); - assert.equal(r3.status, 502, "third request also fails fast"); + assert.equal(r3.status, 413, "third request also fails fast (cooldown replays the same verdict, #3461)"); await r3.text(); assert.deepEqual(streamForwards, [true], "still exactly one forward total (no re-forwarding loop)"); } finally { diff --git a/tests/issue767-pixel-billing.test.ts b/tests/issue767-pixel-billing.test.ts index f8711ee09d..6cf2958767 100644 --- a/tests/issue767-pixel-billing.test.ts +++ b/tests/issue767-pixel-billing.test.ts @@ -357,7 +357,8 @@ test("e2e #767 control: explicit bytes route still fails fast — relay protecti s!.stats.lastInputTokens = STALE_BASELINE; const r2 = await fetch(url, { method: "POST", headers, body: imageTurn("img-byt-sess") }); - assert.equal(r2.status, 502, "byte-billed over-window images stay blocked locally"); + // #3461: structurally doomed (byte-billed images can't fold enough) → 413. + assert.equal(r2.status, 413, "byte-billed over-window images stay blocked locally"); const err2 = JSON.parse(await r2.text()) as { error?: { code?: string; message?: string } }; assert.equal(err2.error?.code, "preflight_compress_failed"); assert.ok(err2.error?.message?.includes("Images alone account for"), "fail-fast carries the image remedy wording"); @@ -439,7 +440,8 @@ test("e2e #767: learned-limit-only variant also closes forward-once (explicit by (s!.stats as { lastInputTokensSource: string }).lastInputTokensSource = "usage"; const r2 = await fetch(url, { method: "POST", headers, body: imageTurn("img-lrn-sess") }); - assert.equal(r2.status, 502, "overflow evidence (learned limit) closes #496 forward-once even with a fresh baseline"); + // #3461: structurally doomed (byte-billed images can't fold enough) → 413. + assert.equal(r2.status, 413, "overflow evidence (learned limit) closes #496 forward-once even with a fresh baseline"); const err2 = JSON.parse(await r2.text()) as { error?: { code?: string } }; assert.equal(err2.error?.code, "preflight_compress_failed"); assert.equal(stats.streamingForwards, 1, "image-bearing turn was never forwarded"); @@ -480,7 +482,8 @@ test("e2e #767: env BILI_IMAGE_BILLING beats per-provider route config", async ( } finally { delete process.env.BILI_IMAGE_BILLING; } - assert.equal(r2.status, 502, "env override downgrades the pixels route back to conservative byte billing"); + // #3461: structurally doomed (byte-billed images can't fold enough) → 413. + assert.equal(r2.status, 413, "env override downgrades the pixels route back to conservative byte billing"); const err2 = JSON.parse(await r2.text()) as { error?: { code?: string } }; assert.equal(err2.error?.code, "preflight_compress_failed"); assert.equal(stats.streamingForwards, 1); diff --git a/tests/issue857-image-baseline.test.ts b/tests/issue857-image-baseline.test.ts index 1c59430fd6..013712c69b 100644 --- a/tests/issue857-image-baseline.test.ts +++ b/tests/issue857-image-baseline.test.ts @@ -208,7 +208,8 @@ test("#857 B: genuine overflow evidence (learned limit == configured window) sti s.stats.lastInputTokensSource = "usage"; const r2 = await fetch(url, { method: "POST", headers, body: body(MODEL, "s857b", imageInput()) }); - assert.equal(r2.status, 502, "no blind forward when the upstream proved the window"); + // #3461: over-window per bili's own meter with no foldable mass left → 413. + assert.equal(r2.status, 413, "no blind forward when the upstream proved the window"); await r2.text(); assert.equal(stats.streamingForwards, 1, "image turn was not forwarded"); assert.equal(stats.imagesSeen, 0); @@ -246,7 +247,8 @@ test("#857 C: usage-grounded over-window baseline — hatch stays closed AND the // #1841 removes (old code walked both ranges, burned the calls, and // still failed here). const r2 = await fetch(url, { method: "POST", headers, body: body(FALLBACK_MODEL, "s857c", [...fillerHistory(16), ...imageInput()]) }); - assert.equal(r2.status, 502, "usage evidence keeps the hatch closed"); + // #3461: over-window per bili's own meter with no foldable mass left → 413. + assert.equal(r2.status, 413, "usage evidence keeps the hatch closed"); const err2 = JSON.parse(await r2.text()) as { error?: { code?: string; message?: string } }; assert.equal(err2.error?.code, "preflight_compress_failed"); assert.match(err2.error?.message ?? "", /futile round/, `the skipped round names its futility verdict (got: ${err2.error?.message})`); diff --git a/tests/preflight-fail-fast.test.ts b/tests/preflight-fail-fast.test.ts index 74c66b74f5..d516943ca5 100644 --- a/tests/preflight-fail-fast.test.ts +++ b/tests/preflight-fail-fast.test.ts @@ -225,7 +225,7 @@ test("e2e #301: payload fits the window + preflight 429 → request still forwar } }); -test("e2e #301: over-window payload with nothing compressible → structured 502, no summary call, no forward", async () => { +test("e2e #301: over-window payload with nothing compressible → structured 413 (#3461), no summary call, no forward", async () => { const calls: Call[] = []; const upstream = makeUpstream429(calls); upstream.listen(0, "127.0.0.1"); @@ -256,7 +256,7 @@ test("e2e #301: over-window payload with nothing compressible → structured 502 ], }), }); - assert.equal(r.status, 502, "fail-fast 502 when nothing is compressible"); + assert.equal(r.status, 413, "fail-fast 413 when nothing is compressible (#3461: deterministic exhaustion is non-retryable)"); const json = JSON.parse(await r.text()) as { error?: { code?: string; message?: string; retryable?: boolean } }; assert.equal(json.error?.code, "preflight_compress_failed"); assert.equal(json.error?.retryable, false); @@ -404,7 +404,7 @@ test("e2e #736: operator-shrunk window (compress.modelContextLimit below the mod ], }), }); - assert.equal(r.status, 502, "fail-fast 502 when nothing is compressible under the shrunken window"); + assert.equal(r.status, 413, "fail-fast 413 when nothing is compressible under the shrunken window (#3461)"); const json = JSON.parse(await r.text()) as { error?: { code?: string; message?: string } }; assert.equal(json.error?.code, "preflight_compress_failed"); const msg = json.error?.message ?? ""; @@ -433,7 +433,7 @@ test("e2e #736: operator-shrunk window (compress.modelContextLimit below the mod ], }), }); - assert.equal(r2.status, 502); + assert.equal(r2.status, 413); const msg2 = (JSON.parse(await r2.text()) as { error?: { message?: string } }).error?.message ?? ""; assert.ok(!msg2.includes("full window"), `no shrink note when the window was not operator-shrunk (got: ${msg2})`); proxyPlain.close(); @@ -487,7 +487,7 @@ test("e2e #737: output-headroom-shrunk window (non-Anthropic, no operator overri ], }), }); - assert.equal(r.status, 502, "fail-fast 502 when nothing is compressible under the headroom-shrunk window"); + assert.equal(r.status, 413, "fail-fast 413 when nothing is compressible under the headroom-shrunk window (#3461)"); const json = JSON.parse(await r.text()) as { error?: { code?: string; message?: string } }; assert.equal(json.error?.code, "preflight_compress_failed"); const msg = json.error?.message ?? "";