From 99ab9c432200145218c173b39c4880f094828009 Mon Sep 17 00:00:00 2001 From: awork Date: Sun, 18 Oct 2026 12:33:34 +0800 Subject: [PATCH 1/3] fix(preflight): compare foldable mass to deficit on one calibrated scale (#3645) The raw-range futility gate compared an UNCALIBRATED foldable pool against a CALIBRATED payload deficit. With a matching-origin k-hat > 1 the deficit is inflated x-k while the kernel range.tokens pool is not, so a fold that would bring the window back under the limit was declared futile and skipped, leaving the session bricked behind a non-retryable 502. - preflight.ts: route the foldable pool through applyEstimateCalibration before comparing it to the deficit (pre-walk gate, relaxed probe, mid-walk bail) and in the log/failure text, so both sides share one scale. Identity for k-hat=1 / absent / mismatched-origin keeps the #1841 uncalibrated path byte-identical. - server.ts: hoist the calibrated post-fold size so the fail-fast message quotes the same scale as the fit decision, instead of claiming a sub-window raw number exceeds the window when k-hat > 1. Regression: tests/issue3645-calibrated-futility.test.ts (calibrated case recovers; uncalibrated control unchanged). Fixes #3645 --- src/preflight.ts | 28 ++- src/server.ts | 12 +- tests/issue3645-calibrated-futility.test.ts | 222 ++++++++++++++++++++ 3 files changed, 249 insertions(+), 13 deletions(-) create mode 100644 tests/issue3645-calibrated-futility.test.ts diff --git a/src/preflight.ts b/src/preflight.ts index 79f486526c..95ea408e59 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -1480,6 +1480,16 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa // as absent (raw estimate) rather than deciding with a cross-model scale. const kFactor = currentCalibrationFactor(deps.session.stats, deps.session.metadata?.lastModel); const kOrigin = deps.session.stats.calibratedEstimateOrigin; + // #3645: kernel range.tokens are the UNCALIBRATED count, but + // result.payloadEstimate (hence every deficit derived from it) sits on the + // CALIBRATED scale once a matching-origin k̂ is set (#1933 F1). Folding a + // raw-mass range removes its mass from the text, so its calibrated saving + // is bounded by mass*k̂ — compare the foldable pool to the deficit on that + // same scale, or a k̂>1 session inflates the deficit ×k̂ against an + // un-scaled mass and the gate calls a recoverable round futile. Identity + // for k̂=1 / absent / mismatched-origin (applyEstimateCalibration → raw), so + // the uncalibrated #1841 path stays byte-identical. + const calibrateFoldMass = (rawMass: number): number => applyEstimateCalibration(rawMass, kFactor, kOrigin, deps.upstreamOrigin); let textTarget = Math.max(0, Math.min(limit, deps.compressionTarget ?? limit) - imageReserve); const result: PreflightResult = { compressedRanges: 0, savedTokens: 0, payloadEstimate: applyEstimateCalibration(estimateCoreMessages(messages) + wireOverhead, kFactor, kOrigin, deps.upstreamOrigin) + imageReserve, rangesRemaining: 0, fitsWindow: true }; if (limit <= 0) return result; @@ -1914,7 +1924,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa }, 0); let potential = resolvableMass(ranges); const deficit = result.payloadEstimate - limit; - if (potential > 0 && deficit > 0 && potential * FUTILITY_SLACK < deficit) { + if (potential > 0 && deficit > 0 && calibrateFoldMass(potential) * FUTILITY_SLACK < deficit) { if (!relaxed) { // The soft-protected recent zone is not in `ranges` yet; #330 // makes it foldable on relax. Probe the relaxed view (CPU-only, @@ -1931,14 +1941,14 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa }); const relaxedRanges = viableRanges(probe.nudge?.compressibleRanges ?? []).filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars); const relaxedPotential = resolvableMass(relaxedRanges); - if (relaxedPotential * FUTILITY_SLACK >= deficit) { + if (calibrateFoldMass(relaxedPotential) * FUTILITY_SLACK >= deficit) { activeConfig = relaxedConfig(deps.config); relaxed = true; textTarget = Math.max(0, limit - imageReserve); summaryCalls = 0; budgetHit = false; transientRetryBudget = TRANSIENT_EMPTY_RETRY_BUDGET; - deps.log("warn", `[preflight] foldable mass outside the protected recent zone (~${potential} tok) cannot close the ${deficit}-tok gap; relaxing soft protection up front and retrying (#1841)`); + deps.log("warn", `[preflight] foldable mass outside the protected recent zone (~${calibrateFoldMass(potential)} tok) cannot close the ${deficit}-tok gap; relaxing soft protection up front and retrying (#1841)`); continue; } // The relaxed pool is the superset: quote it as the true bound. @@ -1953,15 +1963,15 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa // instead of declaring futility here. Never entered for tiers=false // or emergency digest mode, so both paths stay byte-identical. if (eligibleForTierRecovery()) { - deps.log("info", `[preflight] raw-fold pool (~${potential} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`); + deps.log("info", `[preflight] raw-fold pool (~${calibrateFoldMass(potential)} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`); break; } // #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)`); + failure = { kind: "exhausted", deterministic: lastUnusableDetail === undefined && !poolQueueDrop, detail: `futile round: the maximum possible saving from all foldable content (~${calibrateFoldMass(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 ~${calibrateFoldMass(potential)} tok < required ~${deficit} tok${zoneNote}; zero summarization calls spent (#1841)`); break; } } @@ -2303,11 +2313,11 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa if (si !== undefined && ei !== undefined && si <= ei) remaining += rj.tokens; } const deficit = result.payloadEstimate - limit; - if (remaining > 0 && deficit > 0 && remaining * FUTILITY_SLACK < deficit) { + if (remaining > 0 && deficit > 0 && calibrateFoldMass(remaining) * FUTILITY_SLACK < deficit) { futileBail = true; - bailRemaining = remaining; + bailRemaining = calibrateFoldMass(remaining); bailDeficit = deficit; - deps.log("warn", `[preflight] remaining foldable mass (~${remaining} tok) cannot close the ~${deficit}-tok gap; stopping further summarization calls (#1841)`); + deps.log("warn", `[preflight] remaining foldable mass (~${calibrateFoldMass(remaining)} tok) cannot close the ~${deficit}-tok gap; stopping further summarization calls (#1841)`); break; } } diff --git a/src/server.ts b/src/server.ts index cd0f34b161..320a79ad6c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3358,6 +3358,7 @@ export async function preflightCompressIfNeeded( // #553) — the optimistic re-estimate is exactly what that regime distrusts. let outbound: Prepared = prepared; let fits: boolean; + let foldedCalibratedSize: number | undefined; if (result.compressedRanges > 0) { const rebuilt = await runPrepare(); // runPrepare re-incremented stats.requests; the rebuild is internal @@ -3388,9 +3389,12 @@ export async function preflightCompressIfNeeded( // The baseline anchor above stays raw deliberately: it is a floor for // future meters, and a deflated (k̂ < 1) value would only delay the // next trigger, never advance it. - fits = unknownBaseline - ? result.fitsWindow - : applyEstimateCalibration(rebuiltTextSize, kFactor, kOrigin, currentOrigin) + imageTokens < limit; + const rebuiltCalibrated = applyEstimateCalibration(rebuiltTextSize, kFactor, kOrigin, currentOrigin) + imageTokens; + // #3645: hoist the calibrated post-fold figure so the fail-fast message + // quotes the same scale as this fit and the pre-fold tokenCount — quoting + // the raw size there claimed a sub-window number exceeds the window when k̂>1. + foldedCalibratedSize = rebuiltCalibrated; + fits = unknownBaseline ? result.fitsWindow : rebuiltCalibrated < limit; // #1820: anchor the meter to the rebuilt payload's measured size — the // rebuild request's own usage report (the only sample that can supersede // this) hasn't landed yet, and the meter's fallback branches would size @@ -3534,7 +3538,7 @@ export async function preflightCompressIfNeeded( // rejection — deterministic for the identical payload) overrides the // status-based heuristic below; every other path keeps today's mapping. const retryable = f?.retryable === false ? false : f?.retryable === true || (f?.kind === "upstream" && f.status !== undefined && (f.status === 429 || f.status >= 500)); - const ff = failFast(status, f?.detail ?? "the payload still exceeds the window after preflight compression", retryable, result.compressedRanges > 0 ? session.stats.lastInputTokens : undefined, result.rangesRemaining); + const ff = failFast(status, f?.detail ?? "the payload still exceeds the window after preflight compression", retryable, result.compressedRanges > 0 ? foldedCalibratedSize : undefined, result.rangesRemaining); const contentDeadEnd = f?.kind === "exhausted" || (f?.kind === "upstream" && f.status !== undefined && f.status >= 400 && f.status < 500 && !retryable); if (contentDeadEnd && result.compressedRanges === 0) { const cooldownMs = preflightDeadEndCooldownMs(); diff --git a/tests/issue3645-calibrated-futility.test.ts b/tests/issue3645-calibrated-futility.test.ts new file mode 100644 index 0000000000..09ab4ec0db --- /dev/null +++ b/tests/issue3645-calibrated-futility.test.ts @@ -0,0 +1,222 @@ +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"; + +import { defaultConfig, defaultCountTokens } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +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"; + +// #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 +// deficit is inflated ×k while kernel range.tokens stay on the raw scale, so a fold +// that would fit the window was declared futile and skipped → non-retryable 502 +// (incident: k̂=2.13, raw pool 163K vs calibrated deficit 313K → skip, then 502). +// The gate must compare like with like: calibrate the fold mass onto the deficit's +// scale before judging. Identity for k̂=1 / absent / mismatched-origin (#1841 byte-stable). +// +// All token math is ASCII filler → ceil(len/4), matching the host estimator. +// Sizing (WINDOW=30K, slack 1.2, k̂=2): bash pairs are hard-protected (never +// foldable) and set the calibrated deficit D = 2·payload − 30K strictly between +// pool×1.2 (old raw gate → futile, the bug) and pool×2×1.2 (new calibrated gate → +// viable), while the protected bulk keeps the post-fold payload under the window so +// the recovered walk forwards. + +const WINDOW = 30_000; +const K = 2; // seeded calibration factor — deliberately >1 to expose the unit mismatch +const SUMMARY_TEXT = + "PREFLIGHT SUMMARY: this segment is a load-growth fixture whose every marker is derivable from its turn index."; + +type Call = { summary: boolean; raw: string }; +let CALLS: Call[] = []; +let summaryResponder: (raw: string) => { content: string; finishReason: string }; + +function chatSse(text: string, finishReason: string): string { + const chunk = (delta: Record, finish: string | null): string => + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-test", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`; + return chunk({ role: "assistant" }, null) + chunk({ content: text }, null) + chunk({}, finishReason) + "data: [DONE]\n\n"; +} + +function mockUpstream(): http.Server { + return http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + const isSummary = /TASK: The conversation segment below/.test(raw); + CALLS.push({ summary: isSummary, raw }); + if (!isSummary) { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(chatSse("forwarded answer", "stop")); + return; + } + const r = summaryResponder(raw); + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(chatSse(r.content, r.finishReason)); + }); + }); +} + +function proxyOptions(upstreamPort: number, recentTokens: number): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: WINDOW } } } } as ProxyOptions["routes"], + modelContextLimit: WINDOW, + kernelConfig: defaultConfig(WINDOW, { + preserveRecentMessages: 2, + preserveRecentTokens: recentTokens, + protectedTools: ["bash"], + compress: { minCompressRange: 1000, maxSummaryLength: 20000, minSummaryLength: 50 }, + }), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions; +} + +function plain(role: string, text: string): Record { + return { role, content: text }; +} + +function bashPair(id: number, resultRepeat: number): Record[] { + return [ + { role: "assistant", content: null, tool_calls: [{ id: `call_${id}`, type: "function", function: { name: "bash", arguments: JSON.stringify({ command: "echo hi" }) } }] }, + { role: "tool", tool_call_id: `call_${id}`, content: `BASH_RESULT_${id}_payload_`.repeat(resultRepeat) }, + ]; +} + +async function boot(recentTokens = 2000): Promise<{ proxyPort: number; upstreamPort: number; cleanup: () => Promise }> { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const upstream = mockUpstream(); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + const proxy = await startServer(proxyOptions(upstreamPort, recentTokens)); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + return { + proxyPort, + upstreamPort, + cleanup: async () => { + proxy.close(); + proxy.closeIdleConnections?.(); + await once(proxy, "close"); + upstream.close(); + upstream.closeIdleConnections?.(); + await once(upstream, "close"); + }, + }; +} + +function post(p: { proxyPort: number; upstreamPort: number }, session: string, messages: Record[]): Promise { + return fetch(`http://127.0.0.1:${p.proxyPort}/bili/http://127.0.0.1:${p.upstreamPort}/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": session }, + body: JSON.stringify({ model: "gpt-test", stream: true, messages }), + }); +} + +// Stamp a matching-origin calibration factor onto a fresh session (the incident had +// known usage evidence + persisted k̂). Pre-creating the session lets us set stats +// before the over-window request reaches preflight. No baseline is seeded: a +// named (non-anonymous) session is baseline-known from its first request (#1841). +function seedCalibratedSession(sessionId: string, upstreamPort: number): void { + const s = getSession(sessionId); + s.stats.calibratedEstimate = K; + s.stats.calibratedEstimateOrigin = `http://127.0.0.1:${upstreamPort}`; // == currentOrigin → ×K applies +} + +test("#3645: matching-origin k̂>1 no longer skips a raw fold that fits the window", async () => { + CALLS = []; + summaryResponder = () => ({ content: SUMMARY_TEXT, finishReason: "stop" }); + const p = await boot(9_000); + try { + // Plain-text only (tool turns couple into the protected-zone carve and shrink the + // exposed pool). OLD block = foldable pool P; RECENT block = last 2 runs, protected + // by preserveRecentTokens=9000, and kept under the calibrated half-window (K·floor<30K) + // so folding genuinely closes the gap. + const oldA = "OLD_A ".repeat(3334); + const oldB = "OLD_B ".repeat(3334); + const oldC = "OLD_C ".repeat(3334); + const oldD = "OLD_D ".repeat(3334); + const recA = "REC_A ".repeat(3000); + const recB = "REC_B ".repeat(3000); + const poolTok = defaultCountTokens(oldA) + defaultCountTokens(oldB) + defaultCountTokens(oldC) + defaultCountTokens(oldD); + const floorTok = defaultCountTokens(recA) + defaultCountTokens(recB); + assert.ok(poolTok > 15_000, `foldable pool must be large (got ${poolTok})`); + assert.ok(floorTok < WINDOW / K - 1_000, `recent floor must stay under the calibrated half-window (got ${floorTok})`); + assert.ok(K * (poolTok + floorTok) > WINDOW, `fixture must overflow on the calibrated scale (raw ${poolTok + floorTok} × ${K})`); + + const sessionId = "issue3645-calibrated"; + seedCalibratedSession(sessionId, p.upstreamPort); + + const messages: Record[] = [ + plain("user", oldA), + plain("assistant", oldB), + plain("user", oldC), + plain("assistant", oldD), + plain("user", recA), + plain("assistant", recB), + ]; + const resp = await post(p, sessionId, messages); + const body = await resp.text(); + // The distinguishing signal: the walk PROCEEDS instead of skipping as futile. + const summaries = CALLS.filter((c) => c.summary).length; + assert.ok(summaries >= 1, `walk proceeded — ${summaries} summary call(s); the buggy raw gate made ZERO (futility skip)`); + assert.ok(!/futile round/.test(body), `must not declare a viable fold futile (got: ${body.slice(0, 240)})`); + assert.equal(resp.status, 200, `the recovered fold closes the gap and forwards: HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.ok(body.includes("forwarded answer"), "the model reply must reach the client"); + } finally { + await p.cleanup(); + } +}); + +test("#3645 control: uncalibrated (k̂ absent) futility skip is unchanged (#1841)", async () => { + CALLS = []; + summaryResponder = () => ({ content: SUMMARY_TEXT, finishReason: "stop" }); + const p = await boot(); + try { + // Same shape, NO calibration seeded (identity path). Pool tiny vs a huge + // protected bulk → genuinely futile on the raw scale → the skip must remain. + const REPEAT = 3157; + const poolTok = 4 * 440; + const estTok = 2 * Math.round((REPEAT * 22 + 45) / 4) + poolTok; + assert.ok(estTok > WINDOW && estTok - WINDOW > poolTok * 1.2, `fixture must be raw-futile (${estTok} vs ${WINDOW}, pool ${poolTok})`); + + // No calibration seeded → identity path (k̂ absent), matching #1841 A exactly. + const sessionId = "issue3645-control"; + + const messages: Record[] = [ + plain("user", "OLD_WORK_A ".repeat(160)), + plain("assistant", "ANSWER_A ".repeat(160)), + ...bashPair(1, REPEAT), + ...bashPair(2, REPEAT), + plain("user", "OLD_WORK_B ".repeat(160)), + plain("assistant", "ANSWER_B ".repeat(160)), + plain("user", "ok"), + plain("assistant", "done"), + ]; + 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)}`); + 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/, `still names the futility verdict (got: ${json.error?.message})`); + assert.equal(CALLS.filter((c) => c.summary).length, 0, "the uncalibrated skip must spend ZERO summarization calls"); + } finally { + await p.cleanup(); + } +}); From 7351fce8b55e4c524c5bc0684e7087794973a295 Mon Sep 17 00:00:00 2001 From: awork Date: Sun, 18 Oct 2026 13:01:59 +0800 Subject: [PATCH 2/3] fix(preflight): quote the calibrated post-fold size in the compression log too (#3645) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on #3645: the 'preflight compressed N range(s)' info log mixed scales — calibrated pre-fold tokenCount vs the RAW post-fold anchor (session.stats.lastInputTokens), so for k̂>1 sessions the (A → B) pair no longer diffs to the reported saving. Quote foldedCalibratedSize instead; meter-anchor assignment is untouched. --- src/server.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server.ts b/src/server.ts index 320a79ad6c..0bf73a08f8 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3383,7 +3383,6 @@ export async function preflightCompressIfNeeded( session.stats.lastInputTokens = rebuiltTextSize; session.stats.lastInputTokensSource = "estimate"; } - log("info", `[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} → ${session.stats.lastInputTokens}) in ${Date.now() - started}ms`); // Same calibrated caliber as the trigger above — gate, per-round exit // and this final fit must judge the payload on one scale (#1933 F1). // The baseline anchor above stays raw deliberately: it is a floor for @@ -3394,6 +3393,7 @@ export async function preflightCompressIfNeeded( // quotes the same scale as this fit and the pre-fold tokenCount — quoting // the raw size there claimed a sub-window number exceeds the window when k̂>1. foldedCalibratedSize = rebuiltCalibrated; + log("info", `[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} → ${foldedCalibratedSize}) in ${Date.now() - started}ms`); fits = unknownBaseline ? result.fitsWindow : rebuiltCalibrated < limit; // #1820: anchor the meter to the rebuilt payload's measured size — the // rebuild request's own usage report (the only sample that can supersede From 8ede209a50e9424bcb835cab674b914d43d03be8 Mon Sep 17 00:00:00 2001 From: awork Date: Sun, 18 Oct 2026 13:01:59 +0800 Subject: [PATCH 3/3] test(preflight): pin the calibrated fail-fast figure for exhausted calibrated sessions (#3645) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on #3645: symptom 2 (fail-fast quoting the raw post-fold size) had no regression test. New e2e case: k̂=2 with heavy summaries so the walk exhausts deterministically (tiers off) with post-fold raw mass sub-window while the calibrated mass stays over — asserts the quoted context figure is on the calibrated (over-window) scale. Mutation-checked: fails on the pre-fix code with the self-contradictory sub-window quote. --- tests/issue3645-calibrated-futility.test.ts | 65 ++++++++++++++++++++- 1 file changed, 62 insertions(+), 3 deletions(-) diff --git a/tests/issue3645-calibrated-futility.test.ts b/tests/issue3645-calibrated-futility.test.ts index 09ab4ec0db..cbb0997001 100644 --- a/tests/issue3645-calibrated-futility.test.ts +++ b/tests/issue3645-calibrated-futility.test.ts @@ -62,7 +62,7 @@ function mockUpstream(): http.Server { }); } -function proxyOptions(upstreamPort: number, recentTokens: number): ProxyOptions { +function proxyOptions(upstreamPort: number, recentTokens: number, extraKernel: Record = {}): ProxyOptions { return { port: 0, host: "127.0.0.1", @@ -74,6 +74,7 @@ function proxyOptions(upstreamPort: number, recentTokens: number): ProxyOptions preserveRecentTokens: recentTokens, protectedTools: ["bash"], compress: { minCompressRange: 1000, maxSummaryLength: 20000, minSummaryLength: 50 }, + ...extraKernel, }), compress: { injectTool: true, injectNudge: true }, promptCache: { routing: "auto" }, @@ -97,14 +98,14 @@ function bashPair(id: number, resultRepeat: number): Record[] { ]; } -async function boot(recentTokens = 2000): Promise<{ proxyPort: number; upstreamPort: number; cleanup: () => Promise }> { +async function boot(recentTokens = 2000, extraKernel: Record = {}): Promise<{ proxyPort: number; upstreamPort: number; cleanup: () => Promise }> { _setStoreForTest(new SessionStore({ enabled: false })); setRegistryForTest({}); const upstream = mockUpstream(); upstream.listen(0, "127.0.0.1"); await once(upstream, "listening"); const upstreamPort = (upstream.address() as { port: number }).port; - const proxy = await startServer(proxyOptions(upstreamPort, recentTokens)); + const proxy = await startServer(proxyOptions(upstreamPort, recentTokens, extraKernel)); await once(proxy, "listening"); const proxyPort = (proxy.address() as { port: number }).port; return { @@ -184,6 +185,64 @@ test("#3645: matching-origin k̂>1 no longer skips a raw fold that fits the wind } }); +// #3645 symptom 2: the post-fold fail-fast message must quote the SAME scale as the fit +// decision. Fixture: k̂=2 with a summary HEAVIER than any single foldable span, so once +// the walk has folded everything reachable the payload is STILL over the window on the +// calibrated scale while its RAW mass stayed under it (tiers disabled → exhaustion is +// the terminal verdict). The old code quoted the raw size there: a sub-window number +// claiming to "exceed" the window. Head bash pairs are hard-protected (never foldable) +// and pin the terminal RAW mass; the contiguous plain runs merge into one range each +// (measured kernel behavior), so the terminal state is bulk + two heavy summaries. +const SUMMARY_HEAVY = "SUMMARY_PAYLOAD ".repeat(1750); // ~7000 tokens + +test("#3645 display: fail-fast quotes the calibrated post-fold size, not the raw one", async () => { + CALLS = []; + summaryResponder = () => ({ content: SUMMARY_HEAVY, finishReason: "stop" }); + const p = await boot(8_000, { tiers: { enabled: false }, compress: { minCompressRange: 1000, maxSummaryLength: 30_000, minSummaryLength: 50 } }); + try { + const oldText = (tag: string) => `${tag} `.repeat(1667); // ~2501 tokens + const recText = (tag: string) => `${tag} `.repeat(2334); // ~3501 tokens + const spanTok = defaultCountTokens(oldText("OLD_A")); + const recTok = defaultCountTokens(recText("REC_A")); + const sumTok = defaultCountTokens(SUMMARY_HEAVY); + const bulkTok = 2 * defaultCountTokens(`BASH_RESULT_1_payload_`.repeat(175)) + 40; + const poolTok = 4 * spanTok; + const floorTok = 2 * recTok; + assert.ok(spanTok >= 2_000 && spanTok <= 3_000, `span sizing drifted (${spanTok})`); + assert.ok(sumTok > spanTok, `summary must outgrow a single span so folds cannot close the gap (${sumTok} vs ${spanTok})`); + assert.ok(K * (bulkTok + poolTok + floorTok) > WINDOW, `fixture must overflow on the calibrated scale`); + assert.ok(bulkTok + 2 * sumTok < WINDOW, `terminal RAW mass (protected bulk + two heavy summaries) must stay sub-window`); + assert.ok(K * (bulkTok + 2 * sumTok) > WINDOW, `terminal calibrated mass must stay over the window`); + + const sessionId = "issue3645-display"; + seedCalibratedSession(sessionId, p.upstreamPort); + + const messages: Record[] = [ + ...bashPair(1, 175), + ...bashPair(2, 175), + plain("user", oldText("OLD_A")), + plain("assistant", oldText("OLD_B")), + plain("user", oldText("OLD_C")), + plain("assistant", oldText("OLD_D")), + plain("user", recText("REC_A")), + plain("assistant", recText("REC_B")), + ]; + const resp = await post(p, sessionId, messages); + const body = await resp.text(); + let json: { error?: { code?: string; message?: string } }; + try { json = JSON.parse(body); } catch { assert.fail(`expected a JSON fail-fast error, got HTTP ${resp.status}: ${body.slice(0, 240)}`); return; } + const summaries = CALLS.filter((c) => c.summary).length; + assert.ok(summaries >= 1, `folds actually landed before exhaustion — ${summaries} summary call(s)`); + assert.equal(resp.status, 413, `deterministic exhaustion must fail fast non-retryably: HTTP ${resp.status} ${body.slice(0, 240)}`); + assert.equal(json.error?.code, "preflight_compress_failed"); + const m = /context ~(\d+) tokens/.exec(json.error?.message ?? ""); + assert.ok(m, `fail-fast must quote a context figure (got: ${json.error?.message})`); + assert.ok(Number(m[1]) > WINDOW, `quoted figure must be on the calibrated (over-window) scale like the fit decision — got ~${m?.[1]} vs window ${WINDOW}; quoting the raw sub-window size is the #3645 display bug`); + } finally { + await p.cleanup(); + } +}); + test("#3645 control: uncalibrated (k̂ absent) futility skip is unchanged (#1841)", async () => { CALLS = []; summaryResponder = () => ({ content: SUMMARY_TEXT, finishReason: "stop" });