From 6b7c165ec2db0be2ed4b2d3b0f5c69fd55b4fb62 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 22 Sep 2026 12:41:43 +0800 Subject: [PATCH] fix: side-request guard must not clamp on the host usage baseline (#1110) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guard's effective window was fed session.stats.lastInputTokens whenever lastInputTokensSource was 'usage' — but that value is ALSO what a healthy compressed host turn writes as its nudge baseline. A low baseline (e.g. 3k after compression) permanently 413'd an unrelated in-process caller's fixed-size request (MemOS retrieval filter) even though it fit the model's real window, with no config/env escape hatch. Decouple the two: add stats.overflowArmTokens, set ONLY by an upstream context-overflow 400 (the one-shot emergency arm per #554/#987) and cleared by the next real usage report and on compression reset. The guard reads overflowArmTokens, never the baseline. Existing overflow-arm e2e still pins the arm path; new e2e regression reproduces the 413 pre-fix and passes post-fix. --- src/loop/core.ts | 2 ++ src/persist.ts | 3 +++ src/plugin.ts | 2 ++ src/server.ts | 14 +++++++++- src/session.ts | 14 ++++++++++ tests/side-request-isolation.test.ts | 39 ++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/loop/core.ts b/src/loop/core.ts index 435ad4b8a6..1205cd8fbc 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -206,6 +206,8 @@ function recordUsage( if (total > 0) { ctx.session.stats.lastInputTokens = Math.max(0, total - (ctx.session.stats.compressCreditTokens ?? 0)); ctx.session.stats.lastInputTokensSource = "usage"; + // #1110: a real usage report retires the one-shot overflow arm. + delete ctx.session.stats.overflowArmTokens; } if (typeof cached === "number" && total > 0) { ctx.session.stats.cachedTokens += cached; diff --git a/src/persist.ts b/src/persist.ts index 57bb2cf536..6dc37de3f0 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -102,6 +102,7 @@ interface PersistedSession { cacheSamples?: number; lastInputTokens?: number; lastInputTokensSource?: string; + overflowArmTokens?: number; contextTokens?: number; }; /** Free-form escape hatch (v2+). */ @@ -603,6 +604,8 @@ function buildSession(parsed: PersistedSession): Session { // #857: provenance — legacy files lack it; absent stays absent and // evidence-grade consumers treat absent as untrusted. lastInputTokensSource: stats.lastInputTokensSource === "usage" || stats.lastInputTokensSource === "estimate" ? stats.lastInputTokensSource : undefined, + // #1110: one-shot overflow arm — legacy files lack it; absent = no arm. + overflowArmTokens: typeof stats.overflowArmTokens === "number" && Number.isFinite(stats.overflowArmTokens) && stats.overflowArmTokens > 0 ? stats.overflowArmTokens : undefined, // In-memory only — a fresh process has no pending compress fold. compressCreditTokens: 0, contextTokens: Math.max(0, stats.contextTokens ?? parsed.contextTokens ?? 0), diff --git a/src/plugin.ts b/src/plugin.ts index 3604f4cf5c..f5ef53b878 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -913,6 +913,8 @@ export function applyUsageSample(session: Session, sample: UsageSample, protocol // compress tool results shrink the next request, not this report. session.stats.lastInputTokens = Math.max(0, total - (session.stats.compressCreditTokens ?? 0)); session.stats.lastInputTokensSource = "usage"; + // #1110: a real usage report retires the one-shot overflow arm. + delete session.stats.overflowArmTokens; warnCacheCollapse(session, total, sample.cachedTokens ?? 0); // #695: per-request parity with the wire path's [acp-usage] — without // this, post-fold cache cliffs cannot be attributed from logs. diff --git a/src/server.ts b/src/server.ts index 8632518731..d0c3ceb9df 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1558,7 +1558,13 @@ async function handle( // hammering the upstream). Gate on the raw body estimate and fail // fast locally instead of forwarding (#301 precedent). const reqModel = requestModel; - const armedForGuard = session.stats.lastInputTokensSource === "usage" ? session.stats.lastInputTokens : 0; + // #1110: only a genuine overflow arm bounds the guard — never the + // nudge baseline (lastInputTokens). A healthy compressed host turn + // keeps that baseline low, which permanently 413'd an unrelated + // in-process caller's fixed-size request even though it fit the + // model's real window. overflowArmTokens is set ONLY by an upstream + // context-overflow 400 and cleared by the next real usage report. + const armedForGuard = typeof session.stats.overflowArmTokens === "number" && session.stats.overflowArmTokens > 0 ? session.stats.overflowArmTokens : 0; const guard = sideRequestGuard(parsed, protocol, reqConfig.modelContextLimit, imageBillingFor(opts, route?.rewrittenUrl ?? upstreamOrigin), headroomCap, armedForGuard); if (guard.blocked) { log("warn", `[${session.id}] side request (~${guard.estimate} tokens) ≥ effective window ${guard.limit} (model=${reqModel ?? "?"}) — NOT forwarded: guaranteed upstream 400 (side requests bypass preflight by design, #388)`); @@ -4081,6 +4087,9 @@ async function forward( // usage report on the next successful turn overwrites it. s.stats.lastInputTokens = info.window; s.stats.lastInputTokensSource = "usage"; + // #1110: record the arm SEPARATELY so the side-request guard + // can read it without ever touching the nudge baseline. + s.stats.overflowArmTokens = info.window; log("warn", `[${s.id}] upstream context overflow (model=${reqModel ?? "unknown"}) — window ${info.window} stated upstream; armed emergency shrink, declared window unchanged (#987)`); } else { // No window number stated — nothing to learn (and #987 @@ -4102,6 +4111,7 @@ async function forward( if (arm > 0) { s.stats.lastInputTokens = arm; s.stats.lastInputTokensSource = "usage"; + s.stats.overflowArmTokens = arm; // #1110: guard reads this, not the baseline } log("warn", `[${s.id}] upstream context overflow (window not parseable, model=${reqModel ?? "unknown"}) — armed emergency shrink at ~${arm} tokens (min of declared ${declared} and payload estimate), nothing learned (#987): ${info.message}`); } @@ -4576,6 +4586,8 @@ async function forward( total - (prepared.session.stats.compressCreditTokens ?? 0), ); prepared.session.stats.lastInputTokensSource = "usage"; + // #1110: a real usage report retires the one-shot overflow arm. + delete prepared.session.stats.overflowArmTokens; if (typeof cached === "number") { prepared.session.stats.cachedTokens += cached; prepared.session.stats.cacheSamples += 1; diff --git a/src/session.ts b/src/session.ts index cf08d902d6..1a459f6c8b 100644 --- a/src/session.ts +++ b/src/session.ts @@ -95,6 +95,16 @@ export type Session = { * overflow-evidence gate, stale-limit retraction) treat absent as * untrusted. */ lastInputTokensSource?: "usage" | "estimate"; + /** #1110: one-shot emergency ceiling armed by an upstream context- + * overflow 400 (server.ts overflow handler) — live evidence this + * session cannot exceed that size. Kept SEPARATE from lastInputTokens + * (the nudge baseline): a healthy compressed host turn keeps that + * baseline low, and feeding it into the side-request guard (#554) + * clamped an unrelated in-process caller's fixed-size request to a + * permanent 413. The guard reads THIS only. Cleared by the next real + * usage report (one-shot, per the #554 contract) and on compression + * reset. Absent on legacy session files → treated as no arm. */ + overflowArmTokens?: number; /** Tokens compressed THIS turn whose fold has not yet materialized in * an upstream usage report (the post-compress re-request re-sends the * UNFOLDED history for prefix-cache reasons, so its usage report @@ -397,6 +407,10 @@ export function resetSessionCompression(session: Session): void { session.stats.lastInputTokens = 0; // #857: a zeroed baseline carries no provenance — drop any stale flag. delete session.stats.lastInputTokensSource; + // #1110: the conversation was rebuilt — a pre-compaction overflow arm no + // longer bounds this session; drop it so the guard falls back to the + // declared window instead of clamping to a stale ceiling. + delete session.stats.overflowArmTokens; // #728: the pre-compaction outbound payload is gone — the old estimate // (measured against the pre-compaction wire) would read high and blind // the nudge fallback early; let the next prepare* re-measure. diff --git a/tests/side-request-isolation.test.ts b/tests/side-request-isolation.test.ts index 8a63b47f34..14623399f8 100644 --- a/tests/side-request-isolation.test.ts +++ b/tests/side-request-isolation.test.ts @@ -462,3 +462,42 @@ test("e2e: overflow 400 on a side request arms the stated window; next one is bl await closeRig(rig); } }); + +test("e2e: healthy host baseline must NOT clamp an unrelated side request (#1110)", async () => { + const rig = await startRig(); // declared window 200_000 + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/messages`; + const headers: Record = { "content-type": "application/json", "x-acp-session": SESSION }; + + // Host conversation active and healthy: one normal main turn whose real + // usage lands at MAIN_INPUT_TOKENS (50k) → nudge baseline 50k, source + // "usage". NO overflow ever happened, so there is NO overflow arm. + const r1 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 1024, stream: true, messages: mainConversation(8) }) }); + assert.equal(r1.status, 200); + await r1.text(); + + const s1 = getSession(SESSION); + assert.ok(s1, "session exists after the main turn"); + assert.equal(s1.stats.lastInputTokens, MAIN_INPUT_TOKENS, "healthy host turn sets the nudge baseline"); + assert.equal(s1.stats.lastInputTokensSource, "usage", "baseline provenance is a real usage report"); + assert.equal(s1.stats.overflowArmTokens, undefined, "#1110: no overflow occurred → no arm"); + + // An UNRELATED in-process caller's fixed-size request (the MemOS shape): + // no tools, tiny output budget → a side request, but its raw body (~90k + // tokens) exceeds the host's 50k baseline × 1.15 while still fitting the + // model's real 200k window. Pre-#1110 the guard clamped the effective + // window to that 50k baseline and 413'd this permanently; post-fix it + // must forward verbatim. + const bigSideContent = "z".repeat(360_000); + const r2 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 100, stream: true, messages: [{ role: "user", content: bigSideContent }] }) }); + assert.equal(r2.status, 200, "#1110: unrelated side request that fits the real window must forward, not be 413'd by the host baseline"); + await r2.text(); + assert.ok(rig.upstreamHits >= 2, "the unrelated side request reached the upstream"); + + // Side passthrough left the host baseline and kernel state untouched. + assert.equal(getSession(SESSION).stats.lastInputTokens, MAIN_INPUT_TOKENS, "side request did not clobber the host baseline"); + assert.equal(getSession(SESSION).stats.overflowArmTokens, undefined, "#1110: a forwarded (non-overflow) side request must not mint an arm"); + } finally { + await closeRig(rig); + } +});