Skip to content
Closed
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: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
52 changes: 38 additions & 14 deletions src/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 —
Expand All @@ -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
Expand Down
Loading
Loading