From 0dec9ea6d411a38eab9da19bbd68807d94ad4f16 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 7 Oct 2026 15:08:42 +0800 Subject: [PATCH 1/3] fix(preflight): gate the entry meter on baseline provenance (#2313) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The preflightCompress entry meter trusted lastInputTokens regardless of its source, while every other decision site in the request path gates it on usage/overflow-arm provenance (#1492). An estimate-sourced value is a one-way ratchet written by failed turns and post-rebuild anchors — in incident #2313 it pinned the round-0 kernel view at ~10.3M phantom scale for 12 h while the folded view the gate actually judges drained underneath, and the #1933 F3 depth budgets scaled off the same phantom (raw inbound list) instead of the view being folded. - entry meter now gated on lastInputTokensSource (usage/overflow-arm); the empty-input exception mirrors the per-round floor (a transform-failed outbound IS raw) - depth budgets decided at first measurement on the folded view; a payload that already fits never pays for the decision --- src/preflight.ts | 52 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/src/preflight.ts b/src/preflight.ts index 552529b054..56d1770914 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -1027,7 +1027,16 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa // for the whole loop — lastInputTokens mutates mid-loop and must not flip it. const baselineKnown = deps.unknownBaseline !== true; const countText = baselineKnown ? defaultCountTokens : (text: string): number => text.length; - let currentTokens = baselineKnown ? deps.session.stats.lastInputTokens : estimateCoreMessagesUpper(messages); + // #2313: provenance-gate the entry meter exactly like the per-round + // baselineFloor below (#1492): an estimate-sourced lastInputTokens is a + // one-way ratchet written by failed turns and post-rebuild anchors, not + // upstream evidence — trusting it here pins the round-0 kernel view at + // phantom scale while the folded view the gate actually judges drains + // underneath (incident #2313: entry stuck ~10.3M for 12 h). The + // empty-input exception mirrors the floor: a transform-failed outbound IS raw. + const baselineTrusted = deps.session.stats.lastInputTokensSource === "usage" || deps.session.stats.lastInputTokensSource === "overflow-arm"; + const entryBaseline = baselineTrusted || messages.length === 0 ? deps.session.stats.lastInputTokens : 0; + let currentTokens = baselineKnown ? entryBaseline : estimateCoreMessagesUpper(messages); let decisionTokens = 0; let finalUpper = baselineKnown ? 0 : estimateCoreMessagesUpper(messages); let startTokens = -1; @@ -1057,18 +1066,18 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa let transientRetryBudget = TRANSIENT_EMPTY_RETRY_BUDGET; let rangesTried = 0; let rangesRemaining = 0; - // #1933 F3: scale the depth budgets with the entry overshoot (coverage-bound - // note atop the file). A raised budget is only a ceiling — well-behaved - // payloads exit early exactly as before; only genuinely huge payloads burn - // toward it before the fail-fast reports how far it ran out. - const entryLocal = (baselineKnown ? estimateCoreMessages(messages) : estimateCoreMessagesUpper(messages)) + imageReserve + wireOverhead; - const entryTokens = Math.max(baselineKnown ? deps.session.stats.lastInputTokens : 0, entryLocal); - const overshootRatio = limit > 0 && entryTokens > 0 ? entryTokens / limit : 1; - const summaryBudget = Math.min(MAX_SUMMARY_CALLS_PER_PREFLIGHT * 2, Math.max(MAX_SUMMARY_CALLS_PER_PREFLIGHT, Math.ceil(MAX_SUMMARY_CALLS_PER_PREFLIGHT * overshootRatio))); - const roundBudget = Math.min(MAX_PREFLIGHT_ROUNDS * 2, Math.max(MAX_PREFLIGHT_ROUNDS, Math.ceil(MAX_PREFLIGHT_ROUNDS * overshootRatio))); - if (summaryBudget > MAX_SUMMARY_CALLS_PER_PREFLIGHT) { - deps.log("warn", `[preflight] payload ~${entryTokens} tok vs window ${limit} (~${overshootRatio.toFixed(1)}x) — raising summarization budget ${MAX_SUMMARY_CALLS_PER_PREFLIGHT} -> ${summaryBudget}, rounds ${MAX_PREFLIGHT_ROUNDS} -> ${roundBudget}`); - } + // #1933 F3 + #2313: scale the depth budgets with the entry overshoot + // (coverage-bound note atop the file), measured on the FOLDED view after + // the first pipeline pass — not on the raw inbound list, which stays at + // full-history scale forever because prior server-side folds hide content + // behind blocks (incident #2313: the entry reading and the raised budgets + // stayed pinned at full-history scale for 12 h while the real payload + // drained). A raised budget is only a ceiling — well-behaved payloads exit + // early exactly as before; only genuinely huge payloads burn toward it + // before the fail-fast reports how far it ran out. + let summaryBudget = MAX_SUMMARY_CALLS_PER_PREFLIGHT; + let roundBudget = MAX_PREFLIGHT_ROUNDS; + let budgetsDecided = false; for (let round = 0; round < roundBudget; round++) { if (deps.signal?.aborted) { failure = ABORTED_FAILURE; @@ -1104,7 +1113,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa // currentTokens at millions and burn rounds folding ranges the window // never needed. const baselineFloor = messages.length > 0 - ? ((deps.session.stats.lastInputTokensSource === "usage" || deps.session.stats.lastInputTokensSource === "overflow-arm") ? deps.session.stats.lastInputTokens : 0) + ? (baselineTrusted ? deps.session.stats.lastInputTokens : 0) : deps.session.stats.lastInputTokens; const rawRoundText = estimateCoreMessages(turn.messages) + wireOverhead; // #1933 F1: same calibrated caliber as the gate's trigger/fit checks — @@ -1128,6 +1137,21 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa // (the floor can be stale — see PreflightResult.payloadEstimate). result.payloadEstimate = roundText + imageReserve; if (startTokens < 0) startTokens = currentTokens; + // #2313: first measurement of this invocation — decide the depth + // budgets on the view being folded (see the note above); a payload + // that already fits never pays for the decision. + if (!budgetsDecided) { + budgetsDecided = true; + if (decisionTokens >= textTarget) { + const entryTokens = Math.max(baselineKnown ? entryBaseline : 0, baselineKnown ? result.payloadEstimate : finalUpper); + const overshootRatio = limit > 0 && entryTokens > 0 ? entryTokens / limit : 1; + summaryBudget = Math.min(MAX_SUMMARY_CALLS_PER_PREFLIGHT * 2, Math.max(MAX_SUMMARY_CALLS_PER_PREFLIGHT, Math.ceil(MAX_SUMMARY_CALLS_PER_PREFLIGHT * overshootRatio))); + roundBudget = Math.min(MAX_PREFLIGHT_ROUNDS * 2, Math.max(MAX_PREFLIGHT_ROUNDS, Math.ceil(MAX_PREFLIGHT_ROUNDS * overshootRatio))); + if (summaryBudget > MAX_SUMMARY_CALLS_PER_PREFLIGHT) { + deps.log("warn", `[preflight] payload ~${entryTokens} tok vs window ${limit} (~${overshootRatio.toFixed(1)}x) — raising summarization budget ${MAX_SUMMARY_CALLS_PER_PREFLIGHT} -> ${summaryBudget}, rounds ${MAX_PREFLIGHT_ROUNDS} -> ${roundBudget}`); + } + } + } if (decisionTokens < textTarget) break; // #847: drop sub-minimum ranges at list level too — every chunk of a // sub-min range fails the apply-side gate, so walking them only burns From 12a5df401e7ff3427e33bfcb29d3fa5673102685 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 7 Oct 2026 15:08:42 +0800 Subject: [PATCH 2/3] test(preflight): regression suite for the #2313 entry-meter livelock Unit-level direct preflightCompress runs shaped like the incident: a session whose prior folds hide most history behind blocks, with an estimate-sourced ratcheted lastInputTokens. Proves the new code raises depth budgets on honest scale (~1.x, uncapped) and fits the window, stays silent for payloads that already fit, and keeps the legacy cap on the trusted-floor path. Verified against stashed old code: the two phantom-scale tests fail there, the trusted-floor test passes both sides. --- tests/issue2313-preflight-entry-meter.test.ts | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 tests/issue2313-preflight-entry-meter.test.ts diff --git a/tests/issue2313-preflight-entry-meter.test.ts b/tests/issue2313-preflight-entry-meter.test.ts new file mode 100644 index 0000000000..b469f7e58c --- /dev/null +++ b/tests/issue2313-preflight-entry-meter.test.ts @@ -0,0 +1,142 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { createCore, createInitialState, defaultConfig, defaultPrompts, type CoreMessage } from "acp-kernel"; +import { preflightCompress, MAX_SUMMARY_CALLS_PER_PREFLIGHT } from "../src/preflight.ts"; +import type { Session } from "../src/session.ts"; + +process.env.NODE_ENV = "test"; + +// #2313: the preflight entry meter (the "[preflight] payload ~N tok" reading +// and the #1933 depth-budget scaling) was measured on the RAW inbound message +// list plus an UNPROVENANCED floor on stats.lastInputTokens. Two defects made +// it lie about the work actually left: +// +// 1. Prior server-side folds hide content behind blocks, but the raw list +// still carries it — so the entry reading stayed pinned at full-history +// scale forever while the folded view the gate judges drains underneath +// (incident #2313: trigger stuck ~10.3M for 12 h against a real payload +// near the window; the raised budgets rode along at the cap the whole +// time). +// 2. An estimate-sourced lastInputTokens (a one-way ratchet written by +// failed turns / post-rebuild anchors, NOT upstream evidence) floored +// the entry meter while the per-round baselineFloor already refused it +// (#1492 provenance discipline) — internal inconsistency inside one +// function. +// +// The fix measures the entry overshoot on the FOLDED view after the first +// pipeline pass and gates the baseline floor on source +// ("usage"/"overflow-arm"), mirroring the per-round floor. These tests pin: +// - an estimate-grade phantom must not cap the budgets (folded scale wins); +// - a usage-grade baseline still floors the entry meter (legacy ceiling); +// - a converged payload (folded view under the window) pays nothing. + +const WINDOW = 100_000; +const PHANTOM = 50_000_000; +const SUMMARY = + "PREFLIGHT ENTRY METER SUMMARY: the segment covered earlier implementation work. " + + "Key decisions and remaining tasks are preserved for the next turn."; + +interface Fixture { + core: ReturnType; + messages: CoreMessage[]; + state: ReturnType; +} + +// A tiny opening user message (the first-user pin — prune keeps it even when +// covered), one huge early assistant message pre-folded behind a block (so +// the RAW list stays at full-history scale while the rendered view carries +// only its summary), ten foldable middle messages sized by midRepeats, and a +// protected recent tail. +function buildFixture(midRepeats: number): Fixture { + const core = createCore(); + const config = defaultConfig(WINDOW); + config.preserveRecentMessages = 5; + config.preserveRecentTokens = 5000; + config.compress.minCompressRange = 5000; + const messages: CoreMessage[] = [ + { id: "start", role: "user", contentType: "text", text: "Start of session." }, + { id: "hidden", role: "assistant", contentType: "text", text: "HIDDEN_RAW ".repeat(400_000) }, + ...Array.from({ length: 10 }, (_, i): CoreMessage => ({ id: `mid-${i}`, role: i % 2 ? "assistant" : "user", contentType: "text", text: `MID_${i} `.repeat(midRepeats) })), + { id: "recent-a", role: "user", contentType: "text", text: "RECENT_A ".repeat(1_000) }, + { id: "recent-b", role: "assistant", contentType: "text", text: "RECENT_B ".repeat(1_000) }, + ]; + const turn = core.processTurn({ messages, state: createInitialState(), config: { ...config, modelContextLimit: WINDOW * 100 }, tokenCount: WINDOW, renderTags: "text-only" }); + const hiddenRef = turn.state.messageRefs.byRaw.hidden; + const folded = core.applyCompression({ messages, state: turn.state, config: { ...config, preserveRecentMessages: 0, preserveRecentTokens: 0 }, ranges: [{ startRef: hiddenRef, endRef: hiddenRef, summary: SUMMARY }] }); + assert.equal(folded.result.blocksCreated, 1, "fixture must carry one active block hiding the raw history"); + return { core, messages, state: folded.state }; +} + +async function runPreflight(fixture: Fixture, source: "usage" | "estimate"): Promise<{ result: Awaited>; logs: string[]; summaryCalls: number }> { + const session: Session = { + id: "entry-meter", meta: {}, metadata: {}, state: fixture.state, + stats: { requests: 1, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: PHANTOM, lastInputTokensSource: source, compressCreditTokens: 0, contextTokens: PHANTOM, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + createdAt: Date.now(), lastSeen: Date.now(), blockContents: new Map(), inFlight: 0, persisted: false, pendingRetrievals: [], + }; + const config = defaultConfig(WINDOW); + config.preserveRecentMessages = 5; + config.preserveRecentTokens = 5000; + config.compress.minCompressRange = 5000; + let summaryCalls = 0; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + summaryCalls += 1; + void Buffer.concat(chunks); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ output_text: SUMMARY })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const logs: string[] = []; + try { + const result = await preflightCompress({ + core: fixture.core, session, config, prompts: defaultPrompts, protocol: "responses", + url: `http://127.0.0.1:${(upstream.address() as { port: number }).port}`, headers: {}, model: "test", + log: (_level, message) => logs.push(message), + }, fixture.messages); + return { result, logs, summaryCalls }; + } finally { + const closed = once(upstream, "close"); + upstream.close(); + upstream.closeAllConnections(); + await closed; + } +} + +test("#2313: an estimate-grade phantom baseline must not cap the preflight depth budgets — the folded view decides", async () => { + // Folded view ~117k vs a 100k window (~1.2x): a modest overshoot whose + // honest budget is well below the 2x cap. The raw list is ~1.2M tokens — + // the old meter read THAT (plus the 50M phantom floor) and capped at 32. + const { result, logs, summaryCalls } = await runPreflight(buildFixture(7_500), "estimate"); + const raises = logs.filter((m) => m.includes("raising summarization budget")); + assert.ok(raises.length === 1, `exactly one budget-decision log expected, got: ${JSON.stringify(logs)}`); + assert.ok(!logs.some((m) => m.includes(`-> ${MAX_SUMMARY_CALLS_PER_PREFLIGHT * 2}`)), `the phantom must not cap the budgets at 2x base:\n${logs.join("\n")}`); + assert.match(raises[0], /~1\.\d+x/, `the reading must sit on the folded scale (~1.2x), got: ${raises[0]}`); + assert.equal(result.fitsWindow, true, JSON.stringify(result)); + assert.ok(result.compressedRanges >= 1, "the middle range must fold under the honest budget"); + assert.ok(summaryCalls >= 1 && summaryCalls <= MAX_SUMMARY_CALLS_PER_PREFLIGHT, `base budget suffices (got ${summaryCalls} calls)`); +}); + +test("#2313: a usage-grade baseline still floors the entry meter (legacy conservative ceiling)", async () => { + const { result, logs } = await runPreflight(buildFixture(7_500), "usage"); + const raises = logs.filter((m) => m.includes("raising summarization budget")); + assert.ok(raises.length === 1, `exactly one budget-decision log expected, got: ${JSON.stringify(logs)}`); + assert.match(raises[0], new RegExp(`-> ${MAX_SUMMARY_CALLS_PER_PREFLIGHT * 2}\\b`), `a trusted 50M baseline caps the budgets at 2x base, got: ${raises[0]}`); + // The trusted floor keeps driving the walk past the fit point until the + // ranges run out — the conservative direction is preserved. + assert.equal(result.fitsWindow, true, JSON.stringify(result)); + assert.equal(result.failure?.kind, "exhausted", `floor-pinned walk ends in an honest exhaustion receipt, got: ${JSON.stringify(result.failure)}`); +}); + +test("#2313: a converged payload (folded view under the window) pays nothing despite a phantom baseline", async () => { + const { result, logs, summaryCalls } = await runPreflight(buildFixture(200), "estimate"); + assert.ok(!logs.some((m) => m.includes("raising summarization budget")), `no budget raise for a fitting payload:\n${logs.join("\n")}`); + assert.equal(summaryCalls, 0, "no summarization calls"); + assert.equal(result.compressedRanges, 0, "no folds"); + assert.equal(result.fitsWindow, true, JSON.stringify(result)); +}); From 1cf34e17189f5a1701523744bebb7949529ac62a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 7 Oct 2026 15:08:42 +0800 Subject: [PATCH 3/3] docs(configuration): document the stuck-preflight recovery levers (#2313) compress.modelContextLimit / outputHeadroomMaxPct as operator levers when a long session re-folds without converging before the client gives up; en+zh. Fact-checked: the headroom reservation applies to pinned windows too (reserveOutputHeadroom call site in src/server.ts), so both levers are documented rather than just the pin. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index b05982f8e9..fb970513d4 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1068,7 +1068,7 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Type:** `number | string` - **Default:** *(the model's native window)* - **Status:** ACTIVE -- **Description:** The context window size, in tokens. This is the **denominator** the engine uses for its usage ratio (`usage = tokens / modelContextLimit`) — it is **not** a truncation cap. Accepts an absolute number (`200000`) or a percent string (`"80%"` = 80% of the model's native window, resolved from the built-in table or models.dev registry). When omitted at every level, the native window is used. This is the highest-priority source for the model limit; it overrides the built-in table, the legacy per-model `context` field, and the top-level `modelContextLimit`. Note it also serves as the **hard preflight wall**: once a payload reaches this value the proxy proactively folds context before forwarding, and if folding cannot bring it under, the request fails fast instead of being sent upstream. To keep day-to-day context small while still letting large reads burst up to the native window, keep `modelContextLimit` at its native value and use `maxContextLimit` as the soft target instead (see [Soft target with elastic headroom](#soft-target-with-elastic-headroom-1122)). +- **Description:** The context window size, in tokens. This is the **denominator** the engine uses for its usage ratio (`usage = tokens / modelContextLimit`) — it is **not** a truncation cap. Accepts an absolute number (`200000`) or a percent string (`"80%"` = 80% of the model's native window, resolved from the built-in table or models.dev registry). When omitted at every level, the native window is used. This is the highest-priority source for the model limit; it overrides the built-in table, the legacy per-model `context` field, and the top-level `modelContextLimit`. Note it also serves as the **hard preflight wall**: once a payload reaches this value the proxy proactively folds context before forwarding, and if folding cannot bring it under, the request fails fast instead of being sent upstream. To keep day-to-day context small while still letting large reads burst up to the native window, keep `modelContextLimit` at its native value and use `maxContextLimit` as the soft target instead (see [Soft target with elastic headroom](#soft-target-with-elastic-headroom-1122)). **Recovery lever (#2313):** when a long session keeps re-folding without converging before the client gives up, first read the `[headroom]` log line to see which effective wall nudge/preflight actually judge against — it may sit well below the window your upstream serves (the output-headroom reservation) or below it because the native-window resolution picked a stale small value. The two levers: pin `compress.modelContextLimit` to the window your deployment truly serves (it outranks every other source), and/or set [`outputHeadroomMaxPct`](#outputheadroommaxpct) to `0` when the reservation is not earning its place. Restarting the session is the nuclear alternative. #### `outputHeadroomMaxPct` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index cd62accc59..800267d709 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -1071,7 +1071,7 @@ - **类型:** `number | string` - **默认值:** *(模型的原始窗口)* - **状态:** ACTIVE -- **说明:** 上下文窗口大小,以 token 为单位。它是引擎用于计算使用率比例的**分母**(`usage = tokens / modelContextLimit`)—— 它**不是**截断上限。接受绝对数值(`200000`)或百分比字符串(`"80%"` = 模型原始窗口的 80%,从内置表或 models.dev 注册表解析)。在每个层级都省略时,使用原始窗口。这是模型上限的最高优先级来源;它会覆盖内置表、旧版按模型的 `context` 字段以及顶层的 `modelContextLimit`。注意它同时也是**预检压缩的硬墙**:一旦载荷达到该值,代理会在转发前主动折叠上下文;若折叠后仍超出,请求会直接快速失败而不是发往上游。若希望日常上下文保持较小、同时允许大读取任务突发到原始窗口,请让 `modelContextLimit` 保持为原始窗口值,改用 `maxContextLimit` 作为软目标(见[软目标与弹性余量](#软目标与弹性余量-1122))。 +- **说明:** 上下文窗口大小,以 token 为单位。它是引擎用于计算使用率比例的**分母**(`usage = tokens / modelContextLimit`)—— 它**不是**截断上限。接受绝对数值(`200000`)或百分比字符串(`"80%"` = 模型原始窗口的 80%,从内置表或 models.dev 注册表解析)。在每个层级都省略时,使用原始窗口。这是模型上限的最高优先级来源;它会覆盖内置表、旧版按模型的 `context` 字段以及顶层的 `modelContextLimit`。注意它同时也是**预检压缩的硬墙**:一旦载荷达到该值,代理会在转发前主动折叠上下文;若折叠后仍超出,请求会直接快速失败而不是发往上游。若希望日常上下文保持较小、同时允许大读取任务突发到原始窗口,请让 `modelContextLimit` 保持为原始窗口值,改用 `maxContextLimit` 作为软目标(见[软目标与弹性余量](#软目标与弹性余量-1122))。**恢复杠杆(#2313):** 当长会话反复折叠却总赶不上客户端放弃的时机、无法收敛时,先看 `[headroom]` 日志行确认 nudge/preflight 实际判定的有效墙 —— 它可能远低于上游真实服务的窗口(输出余量预留所致),或因为原生窗口解析选中了过小的陈旧值。两个杠杆:把 `compress.modelContextLimit` 固定到你的部署真正服务的窗口(它优先于其他所有来源),以及/或者在预留没有实际价值时把 [`outputHeadroomMaxPct`](#outputheadroommaxpct) 设为 `0`。重启会话是核选项。 #### `outputHeadroomMaxPct`