Skip to content

fix: preflight tries all viable ranges before declaring exhaustion - #575

Merged
ranxianglei merged 1 commit into
masterfrom
2026-09-06_preflight-all-viable-ranges
Sep 6, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-09-06_preflight-all-viable-ranges

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Preflight fail-fast returned 502 retryable=false ("no range could be compressed") while later spans of the same history were still compressible — minutes later the session owner's in-band compress shrank it 88% (#569).

Root cause

preflightCompress (src/preflight.ts) picked exactly one range per round — the oldest viable one — and when that single range yielded no applied chunk (sub-minCompressRange chunk, empty content, unusable summary, or kernel apply rejection) it declared global exhaustion and broke out of the round loop. Remaining viable ranges were never tried, so one bad leading edge produced a false terminal verdict on a still-recoverable session. In block-dense histories this is likely: the kernel's min-gate sums only non-summary message text, while preflight's char precheck counts all view text including block summaries — so a leading range can pass preflight yet be rejected at apply time.

Fix (src/preflight.ts)

  • Iterate all viable ranges (oldest-first, prefix-cache-stable) within a round until one yields an applied chunk; declare exhausted only after every range has been tried and nothing applied.
  • A range whose summary was unusable / apply failed / refs unresolvable is added to a skip-set (refs are content-fingerprinted → stable across folds) so it is never retried within the invocation — no wasted upstream calls, no infinite churn.
  • New cost cap MAX_SUMMARY_CALLS_PER_PREFLIGHT = 8 bounds summarization calls per invocation (legacy worst case was also 8); hitting it reports a distinct budget-exhausted detail instead of the generic one.
  • Exhaustion detail now names how many ranges were tried, making the 502 truthful and diagnosable.
  • Upstream-error (429→503 retryable), abort, and credit-math semantics unchanged. No wire-shape change: mode-agnostic core only (both plugin and proxy modes affected identically, per AGENTS.md §6).

Tests (tests/preflight-multi-range.test.ts, new)

E2E through the real proxy with a mock Anthropic upstream whose summarization responses are usable/unusable per call:

  1. Regression: oldest range's summary unusable → now 200 with a later range folded (legacy: 502).
  2. Truthful exhaustion: every summary unusable → 502 only after all ranges tried (summaryCalls ≥ 2; legacy made exactly 1), no forward, no blocks.
  3. Budget cap: 48-message history, all summaries unusable → exactly MAX_SUMMARY_CALLS_PER_PREFLIGHT summarization calls, budget variant in the error.

Pre-flight

  • npm run typecheck: pass
  • New suite: 3/3 pass; RED confirmed on legacy (test 1: expected 200, actual 502; test 2: summaryCalls ≥ 2; test 3: budget variant + exact count)
  • Full npm test: 1050/1051 — the single failure (launcher.test.ts resolveClientCommand codex) is pre-existing and environment-specific (this sandbox resolves codex to /usr/bin/codex); unrelated to this change
  • npm run build: success

Fixes #574. Source incident: #569.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · qwen3.8-27b

[bot] 🏷 Review complete — verified, rebased onto master, ready for your merge.

What I verified (all on the rebased head, not just the PR's self-report):

  • Root cause confirmed in legacy code: the round loop picked exactly one range (oldest) and a single failed chunk set a global exhaustion verdict and broke out — remaining viable ranges never tried.
  • RED check: ran the new suite against the legacy src/preflight.ts (restored from the fork point) — 3/3 fail exactly as claimed (test 1: expected 200 got 502; test 2: <2 summary calls; test 3: no budget variant). With the fix: 3/3 green.
  • Full pre-flight on rebased head (master a184ff9, acp-kernel 0.0.54): typecheck ✅ · new suite 3/3 ✅ · npm test 1066/1067 — the single failure is the known environment-specific launcher.test.ts codex-resolution case (fails identically on pristine master) · npm run build ✅. version untouched; diff is exactly the two claimed files.
  • Rebase pushed: the branch sat 15 commits behind master; I rebased it (no conflicts) and pushed 8ecca23 to 2026-09-06_preflight-all-viable-ranges. A local test-merge into master is clean (only src/preflight.ts + tests/preflight-multi-range.test.ts). Note: GitHub's API still reports mergeable: false/dirty moments after the force-push — that's its async recomputation lagging; the local merge proof stands. If the badge hasn't flipped by merge time, refreshing the PR page forces a recompute.

Design review (beyond running the tests):

  • Skip-set soundness holds. I checked acp-kernel's assignRefs: refs are assigned exactly once per message id (if (map.byRaw[message.id]) continue) and never renumbered across folds, so startRef:endRef keys stay valid for the whole invocation. Worst case is bounded anyway (≤8 rounds, ≤8 summary calls) — no churn, no wasted-call loops.
  • One fold per round + full processTurn re-run per round is actually safer than legacy, whose multi-chunk-per-round path kept deriving refs from index maps after applyRanges had mutated session state mid-loop.
  • Semantics preserved: upstream-error mapping (429→retryable), abort handling, credit math, and wire shape are all untouched; the change is in the mode-agnostic core, so plugin and proxy modes are affected identically (§6).
  • Non-blocking nits: (a) the comment says refs are "content-fingerprinted" — more precisely, message ids are content-hashed and refs are allocated sticky from them (the stability claim itself is correct); (b) test 3 hardcodes 8 instead of importing MAX_SUMMARY_CALLS_PER_PREFLIGHT (now deliberately non-exported) — fine, just brittle if the cap ever changes; (c) the exhaustion detail can read "across 0 viable ranges" in the edge where every kernel-reported range fails ref resolution — cosmetic.

Duplicate handling: I closed PR #574 as a duplicate/superseded (labelled duplicate, explanation posted in its thread) — same fix, and this PR is the refined iteration (start+end-keyed skips, no summary calls burned on remaining chunks of a failed range, non-exported constant, rewritten tests). Reopen it if you'd rather keep that variant.

E2E note: tests/e2e/e2e-codex.test.ts needs a real Responses-compatible upstream (manual CI dispatch) and can't run in this sandbox; the new suite drives the real proxy request pipeline end-to-end (real startServer + kernel + mock Anthropic upstream), which covers the changed preflight path.

Merge is yours — agents don't merge: #575

@ranxianglei

Copy link
Copy Markdown
Owner Author

语义合并完成(1f89386) — master 在 15:01 合入了 #544(dsh phase4),给 preflightCompress 引入了 relaxed 软保护区机制,与本 PR 的多 range 遍历在同一循环语义重叠,已手工合并:

  1. 保留双方机制:walk 的 skipSet / rangesTried / 8-call budget + master 的 activeConfig/relaxed 升级门、noEmergencyTruncate、imageFloor+wireOverhead 估算
  2. budget 按 regime 重置:relaxation 时 summaryCalls=0 — 否则正常保护下烧掉的坏摘要预算会饿死 relaxed 阶段,preflight fail-fast × soft-protection livelock: over-window payload with nothing foldable outside the protected zone 502s forever #330 的不可恢复卡死会回归
  3. applyRanges ctx 跟随 activeConfig(relaxed 后压缩在放开配置下执行)
  4. exhaustion 优先级:budget → relaxed(relaxedExhaustedDetail)→ 全 range 失败(N-range 文案)→ rounds
  5. skipSet 跨 relaxation 保留:坏 range 不重试,relaxation 放开的是新 ref

验证:npm ci + typecheck ✅ + 全量 1141/1141 ✅(含 #544 全部测试 + 本 PR 3 个新 e2e + #330 relaxed 回归 + #470 wire 开销回归)+ build ✅

已推送到本分支,对 master 应为干净合并。@ranxianglei 人工合并即可。

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-06_preflight-all-viable-ranges (c1daf6a)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-575

Each push to this PR publishes a new version under the pr-575 npm tag.

Option B — Download artifact

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

This comment is automatically updated on each push.

Multi-range walk merged with the relaxed-mode preflight (dsh phase4):
skipSet/budget walk semantics kept; the soft-protection relaxation resets
the summarization budget per regime so bad summaries under normal
protection cannot starve the relaxed walk (#330 stall); the applyRanges
ctx follows activeConfig; exhaustion reporting distinguishes budget /
relaxed / all-ranges-bad / rounds.
@ranxianglei
ranxianglei force-pushed the 2026-09-06_preflight-all-viable-ranges branch from 1f89386 to c1daf6a Compare September 6, 2026 15:22
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · qwen3.8-27b

[bot] 🏷 语义合并已独立复核 — 全部通过,可以人工合并。

我没有只信报告,在 1f89386 上完整重跑并逐行审计了合并结果:

分支结构(已核实)

  • API 确认 feat(#535): dsh phase 4 — split by destination (last overlay shrinks to loopback) #544 merged_at: 2026-09-06T15:01:11Z,当前 master = 95b1c08。
  • 1f89386 是真正的 merge commit:parents = [95b1c08(新 master), 8ecca23(我此前 rebase 并验证过的 PR head)],即"新 master + 本 PR 线"的手工语义合并。GitHub 现在报告 mergeable: true / mergeable_state: clean。
  • diff vs master 仍只有两个文件:src/preflight.ts + tests/preflight-multi-range.test.ts;测试文件与我之前验证过的版本字节级一致(当时 3/3 绿、legacy 上 RED 确认过);version 未动(0.1.87),kernel 仍 0.0.54。

五个整合点逐一对照 diff,全部属实:

  1. 双方机制都在:skipSet / rangesTried / 8-call budget + master 的 activeConfig/relaxed 门、noEmergencyTruncate、imageFloor+wireOverhead(后者不在 diff 内 = 原样保留)。
  2. relaxation 时 summaryCalls = 0; budgetHit = false — 位置正确(在 continue 回 round 顶之前)。这个重置是必要的:否则正常保护下烧光的预算会让 relaxed 阶段在 range 循环第一行就 break,preflight fail-fast × soft-protection livelock: over-window payload with nothing foldable outside the protected zone 502s forever #330 的不可恢复卡死会回归。代价说明:最坏情况从每次调用 ≤8 次 summary 变为 ≤16(每 regime 8 × 2 regime),仍然有界,可接受。
  3. applyRanges 的 ctx config: activeConfig — 与 master 既有行为一致,只是移进了 range 循环。
  4. exhaustion 优先级 budget → relaxed → N-range 文案 → rounds,与描述一致;且 relaxed 分支带 result.compressedRanges > 0 条件是对的——什么都没折进去时落到 N-range 文案更真实(relaxedExhaustedDetail 预设了"已折完所有可压区")。
  5. skipSet 跨 relaxation 保留——成立:我此前已在 acp-kernel assignRefs 里核实 ref 按 message id 只分配一次、永不重排,旧 skip key 在新 regime 下依然有效。一个边界值得记录(非阻塞):正常保护下 apply 失败的 range 在 relaxed 后也不会重试;实践中内核在正常配置下报告的 range 本就不含软保护区,apply 失败多为 min-gate/块重叠这类与 protection 无关的原因,relaxation 不改变它们——最坏只是少折一点,活性不受影响(新 range 有新 key + 新鲜预算)。

独立运行结果(1f89386,干净 worktree):

  • npm ci ✅ · npm run typecheck ✅ · npm run build ✅
  • npm test: 1140/1141 —— 唯一失败是已知的环境相关用例 tests/launcher.test.ts "resolveClientCommand: codex/claude resolve to themselves"(本沙箱把 codex 解析成 /usr/bin/codex,期望值是裸 codex;在干净 master 上同样失败,与本改动无关)。报告中 1141/1141 应该是在没有该 PATH 解析差异的环境跑的,两边不矛盾。
  • 本 PR 的 3 个新 e2e 在其中全绿。

结论:语义合并正确、验证齐备、对 master 干净(GitHub clean)。@ranxianglei 合并即可:#575

@ranxianglei
ranxianglei merged commit 62d7248 into master Sep 6, 2026
6 checks passed
@ranxianglei ranxianglei mentioned this pull request Sep 6, 2026
ranxianglei pushed a commit that referenced this pull request Sep 6, 2026
#553)

Semantic merge onto current master. The fork-predate relax walk (#544/
#575), wire overhead (#470), image floors (#488), side-request isolation
(#388) and pi host-usage (#590) all landed after this PR's fork point
(09ef208). Resolution:
- preflight.ts: char regime (unknownBaseline / estimateCoreMessagesUpper /
  char-based splitChunks + netting / fitsWindow) grafted onto the multi-
  range walk; the upper bound also carries the image+wire floors.
- server.ts: effectiveTokenCount feeds all three prepare branches; the
  trigger's tokenCount uses upper+floors only for anonymous zero-baseline
  sessions; unknown-baseline keeps the loop's fitsWindow judgment, known
  keeps master's rebuilt-payload re-estimate (#330).
- unknown-baseline + nothing-compressible fails fast (PR semantics);
  known-baseline falls through to preflightCompress so the #330 relax
  path still runs.
- Tests adapted to current master/kernel: fork conversation reshaped for
  the kernel's minPressureBenefit (5k) band and main-request shape
  (max_tokens>200) since #388 now routes the old shape to passthrough.
@ranxianglei
ranxianglei deleted the 2026-09-06_preflight-all-viable-ranges branch October 15, 2026 05:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant