Skip to content

Judge fresh-session preflight fit on the calibrated estimate, not raw char count (#3146) - #3155

Merged
ranxianglei merged 2 commits into
masterfrom
2026-10-14_preflight-fresh-fit-cjk-aware
Oct 14, 2026
Merged

ranxianglei merged 2 commits into
masterfrom
2026-10-14_preflight-fresh-fit-cjk-aware

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

Closes #3146

What this fixes

A brand-new session with no upstream usage baseline yet (an unknown-baseline session — e.g. an anonymous/fork session where lastInputTokens == 0) had its preflight "does the payload fit the window?" question answered using the raw character count instead of bili's calibrated token estimate. That is a unit mismatch: a CHARACTER count compared against a TOKEN window. The bound does fall as you fold (it is recomputed each round from the post-fold view), but at character rate — roughly 2× the real token rate for this content — so bili destroyed about twice the history needed to bring the number under the window, hit the raised round cap while the real token count was already well under, and only then fail-fasted 502.

That is exactly the incident in #3146: 32 ranges folded, 2263796 → 1111212 chars, yet bili returned 502; the upstream actually billed only 540828 tokens against an 872000 window, and the next hop re-anchored fine.

Root cause

estimateCoreMessagesUpper() counts characters, not tokens. For an unknown-baseline session that value was used both to trigger compression (fine — erring early is harmless) AND as the reject-forward gate (wrong). Comparing char count to a token window inflated "how much must be destroyed to pass" by ~2×, so the loop ran to the round cap having over-folded, and fitsWindow (char < window) stayed false even though the real payload fit. The predicate was satisfiable all along — the cost was just mis-priced in the wrong unit.

What changed

The char-count bound is now the trigger arm only. All fit decisions judge on the calibrated, CJK-aware estimate (payloadEstimate):

Note on the doomed gate: it is applied to the post-fold payload, deliberately not pre-fold. A pre-fold byte gate would false-positive on #3146 itself — the inbound (≈9.8 MiB) looks byte-doomed, but the payload folds down to 540828 tokens, which fits the 872000 window. Only a residual that stays over after maximal folding is genuinely doomed.

Behavior change (old → new)

Case Old New
Fresh session, real size fits but char count exceeds window over-folds ~2× the needed history across the round cap, then fail-fast 502 stops folding once the calibrated size fits, forwards successfully
Fresh session, nothing compressible, real size fits immediate fail-fast 502 ("nothing left to fold") forwards as-is
Fresh session, genuinely over window after max folding char-count fail-fast 502 forwards once for upstream arbitration (or 413 if post-fold byte-doomed)
Fail-fast message, estimate-only sizing reads like established fact notes it is bili's local estimate

Known-baseline sessions are unchanged (they always judged on the calibrated estimate). Residual: a fresh payload far denser than any observed live route (~6.8 B/token worst case) may 400 once and recover via the overflow-shrink arm rather than slow-compress-to-fit — the same tradeoff chosen for #3146.

Config surface

None. No new config fields, env vars, or CLI flags; no existing field renamed or re-semantics'd.

Testing

  • Rewrote tests/preflight-fork-estimate.test.ts: the mock now enforces the window on a realistic tokenizer matching bili's own CJK-aware estimator (the old mock counted every character as a token — the pathological regime [Bug] 新会话(无 usage 基线)preflight 把字符数当 token——折叠其实成功(2263796→1111212)却 fail-fast 502,上游实际只计费 540828 #3146 deliberately stops defending via slow compress-to-fit). Asserts a fitting fresh session forwards 200 with zero wasted summarization rounds.
  • Updated tests/preflight-covered-ranges.test.ts unknown-baseline case to genuinely overflow the window so it still pins the relax path.
  • Full preflight family green locally (206 tests): preflight-*, issue*preflight*, issue*doomed*, issue*probe*, fork-nudge-*, plus the nobaseline/anonymous-anchor seams. Typecheck + production build clean. Full-suite verdict comes from CI on the pushed head.

Review note

Not auto-merge eligible (§7.4): this changes wire-judgment semantics and a fallback/default decision path in the hot file src/server.ts, and touches the preflight fit contract — human review requested.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-14_preflight-fresh-fit-cjk-aware (da09302)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.3605-pr.3155.619bd8e

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr3155.tgz
npm install -g package

Install instructions are refreshed on each push.

awork added 2 commits October 14, 2026 17:00
…t raw char count (#3146)

An unknown-baseline session (no upstream usage yet — e.g. an anonymous/fork
session with lastInputTokens=0) had its preflight "does the payload fit the
window?" decided on the character count (estimateCoreMessagesUpper), not the
calibrated token estimate. That is a unit mismatch: a CHARACTER count compared
against a TOKEN window. The bound does fall as you fold (it is recomputed each
round from the post-fold view), but at character rate — ~2x the real token rate
for this content — so bili destroyed roughly twice the history needed to bring
the number under the window, hit the raised round cap (16 -> 32) while the real
token count was already well under, and then fail-fast 502'd. Incident #3146:
32 ranges folded, 2263796 -> 1111212 chars, yet 502; upstream actually billed
540828 of an 872000 window.

The char-count bound remains the TRIGGER arm only (where erring early is
harmless). Every fit decision now judges on the calibrated CJK-aware estimate
(payloadEstimate): the per-round exit, both relax gates, the final fitsWindow,
and the caller's early no-compressible-ranges gate. A genuinely over-window
fresh session degrades gracefully instead of false-fail-fasting: it forwards
once for the upstream to arbitrate size (#496/#1839/#2313 pattern), or fails
fast 413 when the post-fold byte mass is mathematically doomed (#2490 byte
math, hoisted module-scoped so the probe path shares it). Estimate-only
fail-fast messages now say the size rests on bili's local estimate, not fact.
…rebase (#3146/#2952)

Rebasing #3146's fix (fitsWindow now reads result.payloadEstimate for every regime) onto master invalidated #2952's comment claiming 'result.fitsWindow reads finalUpper'. finalUpper/currentTokens are still recomputed in the recovery path to keep processTurn's tokenCount and the over-window continue/failure signals fresh; the comment now says so.
@ranxianglei
ranxianglei force-pushed the 2026-10-14_preflight-fresh-fit-cjk-aware branch from a40e05d to da09302 Compare October 14, 2026 09:13
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

独立审完这个 PR(不复读 issue 结论,自己重读了 diff、逐路径 trace 了合并后代码、本地定向跑过测试)。先说动作:分支之前落后 master 75 个提交,而 master 恰好在这两个热文件上又改了 +263(preflight)/+69(server)行,所以我把它 rebase 到当前 master(3aeddc1)、逐 regime 核过语义、本地 typecheck + 定向测试全绿后 push 了新头 da09302(现已触发新一轮完整 CI)。下面是八问。

1. 是什么问题:全新会话(还没有任何上游 usage 基线,lastInputTokens==0)的 preflight「payload 放不放得进窗口」判断,用的是原始字符数而不是 bili 校准后的 token 估算。字符数不管怎么折叠都下不来,于是真实 token 数其实放得进窗口的 payload 被判成超窗,烧完所有 preflight 轮次后 fail-fast 502——哪怕折叠已成功、上游实际计费远低于窗口。就是 #3146 那次:折叠省了 ~1.08M 字符却仍 502,上游实际只计 540828 / 872000。

2. 什么原因导致的:estimateCoreMessagesUpper() 数的是字符不是 token。对无基线会话这个值既被用来触发压缩(早触发无害),又被误当成拒绝转发闸门——让一个本可放下的 payload 永远不满足。根因是「字符上界」被错用为 fit 判据,不是某个阈值写错。

3. 影响范围与严重程度:只影响无基线/全新会话(匿名/fork)。已知基线会话一直用校准估算,完全不受影响。严重度:特定条件下功能不可用——新会话真实体积其实放得进时会被误 502 并白烧整轮折叠;不是全局崩溃,但会卡住这类会话的首次请求。

4. 怎么修复的:把字符上界降级为只作触发臂,所有 fit 判定统一改用校准的 CJK-aware 估算(payloadEstimate)。preflight 的每轮退出、两个 soft-protection 放宽闸门、最终 fitsWindow 全改比 payloadEstimate;server「无可压缩区间」闸门对所有 regime 都用校准估算判 fit(放得下的新会话直接转发,不再 502);真正超窗的新会话改为转发一次让上游仲裁(#496/#1839/#2313 既有模式:成功落 usage 基线,4xx 溢出 arm overflow-shrink),或折叠后按 #2490 字节数学已注定失败时直接 413。estimate-only 的 fail-fast 文案现在明说尺寸来自 bili 本地估算。

5. 是否有回归问题(逐项核过):

6. 是否破坏缓存:不涉及。不改前缀缓存、重试游标、去重键或增量策略;dead-end 冷却键(#726,基于客户端请求体 hash)未动。

7. 是否改了设计方向:没有转向架构/边界/数据流。只是把「误用的字符上界」退回它该在的位置(触发臂),fit 判据统一到已有的校准估算——让现有机制各归其位,不是新方向。

8. 是否引入了新的配置:无。没有新增 config 字段/env/CLI flag,也没有改名或改语义任何现有字段(PR 描述亦声明 Config surface: None)。

判定:可合。 方向正确、无回归、测试有效(重写后的 tests/preflight-fork-estimate.test.ts 直接编码 #3146 形状并断言 0 轮折叠+成功转发,旧代码必挂)、diff 干净(4 文件全在目的范围内)。本地已验证:typecheck 绿 + 44 个 preflight/doomed/probe/tier-recovery/seam 文件共 210 用例全绿。§7.4 明确不可自动合(改了 wire 判定语义 + fallback 默认路径 + 热文件 server.ts),需你人工合并——现在等 rebase 后这一轮完整 CI 转绿即可(GitHub 当前显示 blocked 只是因为新头 CI 还在跑)。

@ranxianglei
ranxianglei merged commit b2868ca into master Oct 14, 2026
43 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.431-master.b2868ca (rolling master tag).

npm install -g billion-context@0.0.431-master.b2868ca  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant