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
2 changes: 2 additions & 0 deletions src/loop/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions src/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ interface PersistedSession {
cacheSamples?: number;
lastInputTokens?: number;
lastInputTokensSource?: string;
overflowArmTokens?: number;
contextTokens?: number;
};
/** Free-form escape hatch (v2+). */
Expand Down Expand Up @@ -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),
Expand Down
2 changes: 2 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 13 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)`);
Expand Down Expand Up @@ -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
Expand All @@ -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}`);
}
Expand Down Expand Up @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
39 changes: 39 additions & 0 deletions tests/side-request-isolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = { "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);
}
});
Loading