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
44 changes: 40 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ import { codexResponsesCodec, responsesCodec } from "./responses-ws.js";
import { currentFetchTransport } from "./fetch-transport.js";
import { demoteGate, hasLeakedBiliToolsOnly, isSideRequest, outputBudgetField, resolveSideLane, restoreOutputBudget, SIDE_REQUEST_MAX_TOKENS, sideRequestGuard, stripLeakedBiliTools } from "./server/side-request.js";
import { DSH_COMPACTION_SHAPE_MSGS, dshCompactionRefusal, isDshCompactionCall } from "./server/dsh-compaction-guard.js";
import { clampOutgoingOutput, countSystemAndToolsTokens, emergencyNudge, estimateInputTokens, estimateWireOverhead, projectThinkingMass } from "./server/budget.js";
import { clampOutgoingOutput, countSystemAndToolsTokens, emergencyNudge, estimateInputTokens, estimateWireOverhead, projectThinkingMass, readOutputBudget } from "./server/budget.js";
import { pipeThrough } from "./server/stream-io.js";
import { artifactSeedHit, detectAcpArtifacts } from "./server/chain-artifacts.js";
import { droppedOpenaiParts } from "./wire-drop-warn.js";
Expand Down Expand Up @@ -3710,7 +3710,42 @@ export async function preflightCompressIfNeeded(
// payload) fails fast with 413 instead of burning a multi-MB guaranteed-400
// forward. This replaces the old char-count reject-forward gate, which
// fail-fasted a successfully-folded payload that actually fit (#3146).
if (unknownBaseline && !growthArmed) {
// #4185: the gate above keyed on unknownBaseline, whose `anonymous &&`
// (#553 trigger-side concern) excluded IDENTIFIED fresh sessions — the
// dsh/codex/claude-code lanes stamp their own session ids, so their first
// over-headroom request skipped this gate and hit the final fail-fast;
// #3846 pinned every retry and the session was dead from message one
// (2026-10-21 raccoon incident: ~227K est vs the 192001 headroom target
// while payload + clamped output budget fit the 256000 native window).
// Two more arms, same internals: noUpstreamEvidence extends "zero
// evidence → arbitrate" to identified fresh sessions — but only for a
// DETERMINISTIC exhaustion (zero compressible ranges after maximum
// folding, #4185's shape): a relay-dependent failure (transient summary
// 503/429/524, empty or truncated summaries) keeps the classic 502
// fail-fast, because the walk may succeed once the relay recovers and
// forwarding an over-window payload then would only hammer the upstream
// (#301/#726). nativeFitAfterClamp forwards whenever the OUTBOUND body
// (already #453/#2096-clamped in prepare) plus its declared output budget
// fits the NATIVE window — the headroom reservation is a policy
// preference, not a physical limit, and with nothing left to fold the
// choice is a smaller output budget vs a dead session. statedWall > 0
// (the upstream already stated its overflow wall on record) keeps the
// native-fit arm closed; doom bytes (#2490) and #3846 guard every arm.
const deterministicExhaustion = f?.kind === "exhausted" && f.deterministic;
const noUpstreamEvidence = session.stats.lastInputTokens <= 0 && statedWall <= 0 && deterministicExhaustion;
let outboundBudgetTokens: number | undefined;
try {
const outBody: unknown = JSON.parse(typeof outbound.body === "string" ? outbound.body : outbound.body.toString("utf8"));
const outField = outputBudgetField(outBody);
const rawBudget = outField !== null ? readOutputBudget(outBody as Record<string, unknown>, outField) : undefined;
if (typeof rawBudget === "number" && rawBudget > 0) outboundBudgetTokens = rawBudget;
} catch {
outboundBudgetTokens = undefined;
}
const outboundCalibrated = foldedCalibratedSize ?? calibratedPayload;
const nativeFitAfterClamp = statedWall <= 0 && outboundBudgetTokens !== undefined && typeof resolvedNativeWindow === "number" && resolvedNativeWindow > 0
&& outboundCalibrated + outboundBudgetTokens <= resolvedNativeWindow;
if ((unknownBaseline || noUpstreamEvidence || nativeFitAfterClamp) && !growthArmed) {
const outMsgs = outbound.processedMessages.length > 0 ? outbound.processedMessages : outbound.originalMessages;
const doomBytes = estimateCoreMessagesUpperBytes(outMsgs);
if (doomBytes > Math.max(DOOMED_PROBE_ABSOLUTE_BYTES, limit * DOOMED_PROBE_BYTES_PER_TOKEN)) {
Expand All @@ -3723,9 +3758,10 @@ export async function preflightCompressIfNeeded(
if (localRefusalHere) {
// #3846: bili already refused this scope locally — do not re-bet on
// the estimator; fall through to the fail-fast below.
log("warn", `[${session.id}] fresh-session payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) but this origin/model was locally refused (413) at an equal or wider window — NOT re-forwarding for size arbitration (#3846)`);
log("warn", `[${session.id}] payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) but this origin/model was locally refused (413) at an equal or wider window — NOT re-forwarding for size arbitration (#3846/#4185)`);
} else {
log("info", `[${session.id}] fresh-session payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) with no upstream evidence — forwarding once for the upstream to arbitrate size before failing fast (#3146)`);
const viaNativeFit = nativeFitAfterClamp && !noUpstreamEvidence && !unknownBaseline;
log("info", `[${session.id}] payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) ${viaNativeFit ? `but the outbound view (~${Math.round(outboundCalibrated)} tok) + clamped output budget ${outboundBudgetTokens ?? 0} fits the native window ${resolvedNativeWindow}` : "with no upstream evidence"} — forwarding once for the upstream to arbitrate size before failing fast (#3146/#4185)`);
return outbound;
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/server/budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import type { Session } from "../session.js";
import { applyEstimateCalibration } from "../util.js";
import { readOutputBudget, writeOutputBudget, type OutputBudgetField } from "./side-request.js";

export { readOutputBudget };

// #453 hard backstop: cap the forwarded output budget so input+output can never
// exceed the window on request-rebuilding upstreams (vLLM rejects an oversized
// total instead of clamping). Non-Anthropic only — Anthropic enforces its input
Expand Down
15 changes: 15 additions & 0 deletions tests/deferred-tool-budget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,22 @@ import { defaultConfig, defaultCountTokens } from "acp-kernel";
import type { ProxyOptions } from "../src/config.ts";
import { SessionStore, _setStoreForTest } from "../src/persist.ts";
import { _setForTest as setRegistryForTest } from "../src/registry.ts";
import { getSession } from "../src/session.ts";
import { startServer } from "../src/server.ts";
import { normalizeUpstreamOrigin } from "../src/util.ts";
import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, estimateInputTokens, estimateWireOverhead, modelVisibleTools } from "../src/server/budget.ts";

// #4185: an identified fresh session whose preflight ends in deterministic
// exhaustion now forwards once for upstream arbitration instead of failing
// fast locally. These pins assert the LOCAL stop-before-forward contract, so
// they carry a settled usage baseline to keep testing the evidence-driven path.
function seedEvidence(upstreamPort: number, sessionId: string): void {
const s = getSession(sessionId);
s.stats.lastInputTokens = 100;
s.stats.lastInputTokensSource = "usage";
s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(`http://127.0.0.1:${upstreamPort}`);
}

const deferred = {
type: "function", name: "large_schema", description: "x".repeat(1_200_000),
parameters: { type: "object", properties: {} }, defer_loading: true,
Expand Down Expand Up @@ -133,9 +146,11 @@ test("#2391: a 272k Responses proxy forwards the full deferred catalog and rejec
assert.equal(accepted.status, 200, await accepted.text());
assert.equal(received.length, 1);
assert.deepEqual(received[0].tools, tools, "full upstream definitions must stay unchanged");
seedEvidence(upstreamPort, "2391-eager");
const eager = await send({ ...body, tools: [{ ...deferred, defer_loading: false }, search] }, "2391-eager");
assert.notEqual(eager.status, 200, await eager.text());
assert.equal(received.length, 1, "eager overflow must be stopped before forwarding");
seedEvidence(upstreamPort, "2391-loaded");
const loaded = await send({ ...body, input: [{ type: "additional_tools", tools: [deferred] }, ...body.input] }, "2391-loaded");
assert.notEqual(loaded.status, 200, await loaded.text());
assert.equal(received.length, 1, "loaded overflow must be stopped before forwarding");
Expand Down
14 changes: 14 additions & 0 deletions tests/issue1841-preflight-futility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ 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 { getSession } from "../src/session.ts";
import { normalizeUpstreamOrigin } from "../src/util.ts";

// #4185: an identified fresh session whose preflight ends in deterministic
// exhaustion now forwards once for upstream arbitration instead of failing
// fast locally. This pin asserts the LOCAL futility-skip contract, so it
// carries a settled usage baseline to keep testing the evidence-driven path.
function seedEvidence(upstreamPort: number, sessionId: string): void {
const s = getSession(sessionId);
s.stats.lastInputTokens = 100;
s.stats.lastInputTokensSource = "usage";
s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(`http://127.0.0.1:${upstreamPort}`);
}

// #1841: when the cumulative mass of ALL foldable content cannot close the gap
// between the payload and the preflight target, the old behavior walked every
Expand Down Expand Up @@ -165,6 +178,7 @@ test("#1841 A: a payload whose foldable pool cannot close the gap skips the roun
plain("user", "ok"),
plain("assistant", "done"),
];
seedEvidence(p.upstreamPort, "issue1841-futility-skip");
const resp = await post(p, "issue1841-futility-skip", messages);
const body = await resp.text();
assert.equal(resp.status, 413, `a futile round must fail fast non-retryably (#3461): HTTP ${resp.status} ${body.slice(0, 240)}`);
Expand Down
13 changes: 13 additions & 0 deletions tests/issue3645-calibrated-futility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ import type { ProxyOptions } from "../src/config.ts";
import { SessionStore, _setStoreForTest } from "../src/persist.ts";
import { getSession } from "../src/session.ts";
import { _setForTest as setRegistryForTest } from "../src/registry.ts";
import { normalizeUpstreamOrigin } from "../src/util.ts";

// #4185: an identified fresh session whose preflight ends in deterministic
// exhaustion now forwards once for upstream arbitration instead of failing
// fast locally. This control asserts the LOCAL futility-skip contract, so it
// carries a settled usage baseline to keep testing the evidence-driven path.
function seedEvidence(upstreamPort: number, sessionId: string): void {
const s = getSession(sessionId);
s.stats.lastInputTokens = 100;
s.stats.lastInputTokensSource = "usage";
s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(`http://127.0.0.1:${upstreamPort}`);
}

// #3645: the raw-range futility gate compared an UNCALIBRATED foldable mass against
// a CALIBRATED payload deficit. Once a matching-origin k̂>1 is set (#1933 F1), the
Expand Down Expand Up @@ -358,6 +370,7 @@ test("#3645 control: uncalibrated (k̂ absent) futility skip is unchanged (#1841
plain("user", "ok"),
plain("assistant", "done"),
];
seedEvidence(p.upstreamPort, sessionId);
const resp = await post(p, sessionId, messages);
const body = await resp.text();
assert.equal(resp.status, 413, `a raw-futile round must still fail fast non-retryably: HTTP ${resp.status} ${body.slice(0, 240)}`);
Expand Down
Loading
Loading