Repository navigation
[PR] fix: root-cause batch for preflight compression (persist folds, wall budget, terminal frame, truncate estimate-hold, shared summary pot) - #6926
Conversation
A hard process death mid-preflight (crash / OOM / restart on multi-million-token sessions) skipped every post-loop persistence path, so rounds already compressed lived only in memory; a client retry under a new session id found no parent state worth inheriting and re-compressed from zero — the permanent unavailability loop reported in #3978. commitFold now marks the session dirty as each fold lands; the persist debounce coalesces the calls into one write per quiet window, so durable progress accumulates regardless of how the request ends. A clean client abort already persists via the post-loop rebuild (src/server.ts:3554 runs before the :3607 fail-fast return); this closes the death-mid-request gap that path cannot cover. tests/issue3978-preflight-abort-persistence.test.ts pins it end-to-end: T1 guards the clean-abort ordering, T2 is the negative control (no fold committed => nothing fold-like persisted), T3 SIGKILLs a real child proxy mid-marathon and asserts a fresh instance's new-id retry inherits the persisted blocks instead of starting fresh. Without the fix the red run fails T3 exactly at the adopted-block count. (cherry picked from commit 775d622)
…3978) The 60s READY deadline lost the race on ubu22-1/win22-1 at head 9be2ec6: the child cold-transforms the whole src tree via tsx, which exceeds 60s under parallel-shard load. Raise the deadline to 180s, fail fast when the child exits before READY (diedP), and capture its stderr in-memory so a future crash surfaces in the assertion message instead of getting lost in interleaved shard logs. (cherry picked from commit dbcc6c8)
…ts resolve (#3978) On CI the per-test tmp dir sits outside the repo tree, so Node finds no package.json walking up from the generated child script and defaults it to CJS. Its bare import of acp-kernel then resolves under the require condition, which acp-kernel's exports map does not define, killing the child at boot with ERR_PACKAGE_PATH_NOT_EXPORTED on every leg. Locally the tmp dir lives inside the repo (inheriting its type:module), which is why this only failed on CI. Writing a minimal {"type":"module"} package.json beside the child script pins the module format explicitly. Verified with an out-of-repo TMPDIR reproduction (red before, green after). (cherry picked from commit 5722ac7)
… T3 child The blind sleep(1000) settle raced the store's trailing-debounce write under loaded CI runners: windows 22-1 at head 5722ac7 found NO parent record at all when the retry booted (T3 red; signature distinct from #4049's two #3769 flakes). Replace the fixed sleep with a wait on '[durable] N' — the child's own codec-aware store.loadSync disk read (envelopes are BILIENC1- framed at rest, so the test process cannot scan the file for the summary mark) — so the SIGKILL can never race an unwritten save. Failure messages now carry the child stderr tail and the store dir listing. (cherry picked from commit 12de55b)
…78 T3 child win22-1 @ a46fd0d: [durable] was observed yet the retry still started fresh (resume lines empty) — findResumeParent (#1486) matches on the parent's affinity-chain entry, which a fresh instance hydrates from the machine-shared state-dir snapshot (prefix-affinity.json), a SEPARATE artifact from the session record with its own 500ms-debounced single-shot persist whose write can lose a rename race or starve under event-loop pressure and never re-arms. The child now proves the FILE carries the t3978-p entry (re-arming the persist while it does not) and the test waits for that proof before SIGKILL; the final assertion also surfaces the child stderr tail. (cherry picked from commit 683d90b)
… EBUSY observation Minor fix found while fixing this lane's CI (labeled per the small-fix rule): the #2771 corrupt-index proof spent the full ~9.6s retry ladder on EBUSY unlinking index.db (transient Windows AV/indexer lock, #2799 family) — extend the flat tail by two 3200ms rungs (~16s total) and align the budget unit test. (cherry picked from commit 2b8c26d)
…ence wall clock (#3573) A summarization round costs 25-44s against a real upstream regardless of range size (#2682), while the common client timeout class (dsh ~60s) only fits ONE such round. An over-window preflight kept admitting rounds until the client disconnected mid-round: the attempt died, the in-flight summary call was wasted, and the user saw an opaque 60s hang-retry loop (#3573). Rounds that make upstream calls are now admitted only while the wall clock leaves room for the next one (estimate: 2x the last round's measured time, first round always admitted, digest regime exempt — CPU-only by design). A stopped attempt keeps its completed folds (they are persisted), so the client's retry resumes from the smaller view and the marathon converges across attempts; the fail-fast stays a plain 502 with no dead-end cooldown, and the tier-recovery funnel is suppressed for the stopped attempt so it cannot sneak extra upstream calls past the budget. Fixes #3573 (companion to #3586 — same issue, independent half). (cherry picked from commit 2f00ba6)
…rdict (#3573 review) When the client-patience wall budget stops the marathon while the payload still overflows the window, the post-loop verdict fell through to the generic branches: 'the compress budget was exhausted after N rounds' (citing a round cap that was never reached), or — in the relaxed-regime subcase — a deterministic exhaustion that server.ts maps to 413, a terminal verdict headless hosts honor by giving up. That kills exactly the retry-convergence story this fix exists for: the folds ARE persisted and the next request resumes from a smaller view. Give the wall-budget stop its own first-in-cascade verdict: kind exhausted with retryable true and an honest detail (rounds run, folds persisted, retry resumes). No deterministic flag -> stays 502; the dead-end cooldown gate (compressedRanges === 0) is untouched because a wall-budget stop always has at least one landed fold. The issue3573 test now pins the honest wording in every stopped attempt's body. (cherry picked from commit 7e40615)
(cherry picked from commit 7d915c5)
…ame (#3978) Once #568 has committed early headers (200 + SSE/JSON keep-alive), every no-forward exit left the client holding a 200 and an open stream that never completes: respond:false writes nothing, and a later status code cannot be written after the 200 — so clients could not distinguish 'bili gave up' from a dead network and waited out their own watchdog (#3978 floor 17/18). All four preflight no-forward exits now emit one terminal frame before returning when headers are already committed: SSE gets an 'event: error' frame, non-streaming JSON gets the error object appended after the whitespace padding (still one valid JSON document), then end(). Body reuses the native fail-fast shape {ok:false,error:{message,retryable}}. Uncommitted exits keep their normal status-code path byte-for-byte, and the abort branch logs its outcome (terminal frame sent / socket gone / not committed). (cherry picked from commit 4bcbcf9)
Review alignment for the terminal-frame fix: the first commit introduced a
new {ok:false,error:{message,retryable}} frame for committed no-forward
exits, which would have silently replaced the in-band contract master
already emits on this path (protocol-native preflight_compress_failed
frames per #568/#1455 - client SDKs parse those natively; the {ok:false}
shape exists only on /__bili/* admin endpoints).
- commitPreflightTerminalFrame now delegates to emitPreflightError (SSE)
and appends preflightFailFastBody (non-streaming): byte-identical to
what the consumer's committed branch already emits, so no wire-shape
change anywhere.
- preflightFailFastBody extracted into src/stream-error.ts as the single
source of truth, shared with handle.ts's status-code bodies.
- The genuinely new terminations are unchanged: the abort exit (respond:
false used to skip all writes) and the overflow-refold re-run
(respondFailFast=false suppressed the consumer) now terminate with the
same established frames instead of dangling / hitting
ERR_HTTP_HEADERS_SENT.
- Tests assert the native shapes; uncommitted negative control unchanged.
Targeted local: issue3978 suite 4/4, adjacent preflight suites 24/24,
tsc clean. Full-suite verdict: CI.
(cherry picked from commit 34020b6)
…allowing them The executor discarded every candidate rejection, so a context-budget guard or a post-fetch parse failure left only a bare tN:error with no warn line, and the compress failure text blamed maxSummaryLength for every failure. Capture the safe cause for our own fixed error strings (unknown provider errors stay opaque), log it once, and branch the failure advice by the batch's own stop reason: budget on deadline, maxSummaryLength only for over-cap replies. Fixes #6885 (cherry picked from commit f0867d7)
… readings (#6882) An ESTIMATE-grade reading (no billing sample landed this cycle — stream interruption, cache-TTL expiry) structurally overstates what will be billed (observed 1.75-1.87x), so a truncate-watermark crossing on such a reading latched clips the bill never saw: content destroyed plus a burned prefix cache (16.3% hit vs 100% control). The pressure band already uses the estimate-hold guard (nudge.requireUsageSampleForPressure + the nudge.maxEstimateHoldRounds backstop); the truncate watermark now honors the same guard: while the backstop allows, the crossing is held one round for the usage-grade reading the next request carries. Already-latched clips still replay byte-for-byte; the round is unjudged, so terminalStreak rides through untouched. Billed readings (usage, incl. the overflow arm), legacy callers (source omitted), and requireUsageSampleForPressure=false keep byte-identical behavior. kernel-change: #6882 option A — the truncate watermark is the same phantom-pressure surface as the pressure band, so it reuses the guard the band already uses rather than a new knob. No new config field; the two existing nudge fields' semantics now cover the truncate watermark too (docs updated in kernel/src/types.ts and the host docs in a follow-up commit).
…dates (#6885) The per-target window was a fresh targetTimeoutMs for every candidate, so early candidates ate the whole pot: with the 25s/50s defaults, t0 ran 25s, t1 was killed at the 50s batch deadline, and t2 never got a request out — the chain failed 100% on long payloads no matter how fast the later candidates were (558 target-timeouts / 258 batch-deadlines / 5 successes in the incident log). The batch deadline is now a shared pot: each candidate gets min(targetTimeoutMs, remaining-pot / remaining-candidates), so a slow early candidate times out at its fair share and the next candidate gets the remaining budget (fast failures return their share to the pot). The configured targetTimeoutMs stays the per-candidate cap; the 600s/180s workaround keeps its full 180s windows (600s/3 > 180s). The timeout detail now reports the ACTUAL window the attempt had (the shrunk target window, or the range's real remaining total) instead of the nominal configured value — the attempts list is model-visible in the compress tool result, so the number the model reads now matches what the attempt actually had. Fixes #6885 (issue 1: default budget + serial attempts fail long-payload chains 100%).
…d config reload (#6882, #6885) - compress.requireUsageSampleForPressure / maxEstimateHoldRounds now cover the emergency-truncate watermark as well as the pressure band (#6882): table rows, the detail section (the stale 'truncate stays armed regardless' line is replaced), and the host config.ts doc comments. - external-summary deadline semantics: the batch deadline is a shared pot — each target gets min(targetTimeoutMs, remaining pot / remaining targets) (#6885); the stale 'each target gets a fresh window' sentence and the sizing advice are updated accordingly. - external-summary: a direct config-file edit is not watched — it applies on POST /__bili/config/reload or restart (Web-UI saves hot-apply); reasoning targets need a large outputTokens or they end in finish_reason=length with an empty body (#6885). - en + zh kept in parity.
📦 Built Package ArtifactBranch: Latest build — install this exact versionnpm install -g billion-context@0.0.12488-pr.6926.ba4a729This exact version is immutable and reproducible. The rolling Recent builds (commit → version)
Download artifact
tar xzf billion-context-pr6926.tgz
npm install -g packageInstall instructions are refreshed on each push. |
…le text The PR body's docs commit edited the GENERATED table rows in docs/configuration.md / .zh-CN.md directly, without updating the website/config-reference/compress.yaml seed they are generated from (#2107 drift guard A). docs-sync went red and, via the test job's !failure() needs gate, skipped the whole test matrix. This commit moves the PR's exact table text (en+zh) into the seed's desc_en/desc_zh for compress.requireUsageSampleForPressure and compress.maxEstimateHoldRounds; regenerating now reproduces the committed docs byte-for-byte (verified: gen-config-docs generate + git diff --exit-code clean). desc_ja and the site_* website fields are untouched, matching the PR's en+zh-only docs scope.
The kernel-change commit bumped kernel/package.json 0.0.198 -> 0.0.199 but left both lockfiles at 0.0.198, so the #3782 lock-sync drift guard went red (and, like docs-sync, skipped the test matrix via the !failure() needs gate). Regenerated with npm install --package-lock-only (root + kernel); the diff is exactly the version line in each file.
[bot] 🏷 (ai: vllm-qwen/qwen3.8-27b) PR #6926 审核结论(preflight 根因批)独立审完:逐段读了全 diff(22 文件 +1555/−106)、核对了三个源 issue 的方向、在本地跑过定向测试、live 查了 CI 并修掉了两条 PR 自身漂移(见下)。 ① 方向关(原 issue):三个 issue 的根因判定都成立,PR 修的是生产者不是症状——
② 回归关(既有行为清点):逐路径过过——
③ 代码关:无 ④ 测试关:全是真测试——kernel 10 例逐字节/ latch / streak / 兜底/ guard-off / cap-0 / legacy 各有断言;共享池测试把旧断言反向钉住(backup 候选从"饿死"变"成功");issue3573 真 server e2e(慢轮:wall stop→502→无 cooldown 污染→fold 持久→重试收敛 200;快轮:单 attempt 完成、零 stop 行);terminal-frame e2e 用 deadline race 把修复前的静默悬挂变红;abort-persistence e2e 的 T3 是真 SIGKILL 子进程中途死亡,新 id 重试经 affinity 链继承持久 fold——这是唯一能覆盖「进程硬死跳过 post-loop 重建」的形状。 CI 状态(live 核实 + 已修):原 head 963ed72 上 docs-sync + lock-sync 红(PR 自身漂移:直接改生成物未更种子;kernel bump 漏 lockfile),test 矩阵被 八问
收工判定:代码与测试层面 ready;kernel 变更留人审档(§7.4 不可 auto-merge)。等 head 3319d46 的 CI 转绿后由 owner 合并;合并后四个被取代的在途 PR(#4046 / #3590 / #5057 / #6890)请 owner 关闭(按政策我不代关)。 |
Resolve kernel version collision: PR 0.0.199 vs master 0.0.200 -> 0.0.201 (kernel/package.json + kernel/package-lock.json + root package-lock.json). Precedent 889493b: master's version + this PR's own kernel step (#6882 truncate estimate-hold). All 9 both-sides host files auto-merged; each verified byte-identical to an independent git merge-file 3-way. Lockfiles stable under npm install; typecheck + build + targeted tests green.
(ai: vllm-qwen/qwen3.8-27b) PR #6926 merge conflict resolved and pushed. What was done this run:
八问(结构化结论):
判定: 冲突已解决并以最终头 |
|
(ai: codex/gpt-6.2-sol) 已合并最新
我不会用删断言或放宽测试的方式让 CI 变绿。修完会再跑定向测试和 |
🔶 需要决策 问题:#1137 fork-nudge 测试(tests/fork-nudge-trigger.test.ts:342)在 PR head 上红。这是 PR 侧既有 bug(PR head 362878d 失败,纯 master a60cd5a 通过,二分法在独立 worktree + 各自 build kernel 确认),非本次合并引入。修复非小机械修复(涉及 preflight↔nudge 状态交互,kernel/host 边界),需 owner 拍板。 根因(已完全定位,含 stack trace 级证据):
选项:
推荐:A——无论文本估计偏高是 bug 还是 intentional,preflight 的 processTurn 破坏 nudge 状态本身就是 bug(同一轮第二次 processTurn 不应重置 streak),A 是最小且正确的修复。 默认(若未决策):A(应用 targeted 修复)。 已打 |
(ai: vllm-qwen/qwen3.8-27b) CI-engineer run (attempt 1/6). Re-verified the live state before acting: the current run (45014158095) on head What I confirmed this run
Two independent gates block a green CI — neither is mine to clear alone
I pushed nothing this run (no verified fix to push) and did not touch the pending 🔶 decision. 八问
判定:停手等待两个前置条件——① owner 对 #1137 拍板(确认默认 A 即可);② 作者以可获取形式提供 |
|
按最新留言,附上 这个补丁在 host 侧保留内部 preflight 探测与重建前的估计轮次计数,供 #1137 的方案 A 审查。它也修复了超限和 relay 错误后的恢复,以及服务启动时的 prefix affinity 加载时序,并为 #6885 使用受控时钟。Windows Node 22.18.0 上 69 项定向测试与 24 项补充回归均通过, Patch SHA-256 From ce47520f1f9246cb4282453f574a712c085b41d7 Mon Sep 17 00:00:00 2001
From: Beyfish <beyfish@users.noreply.github.com>
Date: Sun, 22 Nov 2026 18:47:31 +0800
Subject: [PATCH] fix(preflight): honor recovery evidence and preserve pressure
streaks
---
src/preflight.ts | 11 +++++----
src/server.ts | 24 +++++++++++--------
src/server/handle.ts | 18 +++++++++------
tests/external-summary.test.ts | 42 ++++++++++++++++++++++------------
4 files changed, 60 insertions(+), 35 deletions(-)
diff --git a/src/preflight.ts b/src/preflight.ts
index 2d5855c5..80e6fe25 100644
--- a/src/preflight.ts
+++ b/src/preflight.ts
@@ -1830,6 +1830,11 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
return Math.max(0, imageReserve - deps.measureImageReserve(view.filter(message => !removed.has(message.id))));
};
const result: PreflightResult = { compressedRanges: 0, savedTokens: 0, payloadEstimate: applyEstimateCalibration(estimateCoreMessages(messages) + wireOverhead, kFactor, kOrigin, deps.upstreamOrigin) + imageReserve, rangesRemaining: 0, fitsWindow: true, hadFoldableCandidates: false };
+ const adoptMeasuredTurn = (turn: ReturnType<CompressionCore["processTurn"]>): void => {
+ turn.state.nudge.estimateHoldStreak = deps.session.state.nudge.estimateHoldStreak;
+ deps.session.state = turn.state;
+ adoptContentStore(deps.session, turn.contentStore);
+ };
// #4288: set when the round-top fit exit fired — the walk ended in a
// forward decision, and no later verdict may override it (see the final
// failure stamp below).
@@ -2038,8 +2043,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
tokenCount: currentTokens, renderTags: "text-only", contentStore: contentStoreOf(deps.session),
});
measuredNudge = turn.nudge;
- deps.session.state = turn.state;
- adoptContentStore(deps.session, turn.contentStore);
+ adoptMeasuredTurn(turn);
const view = applyAbsorbView(turn.messages, turn.state, activeConfig, currentTokens);
refreshImages(view);
const est = applyEstimateCalibration(estimateCoreMessages(view) + wireOverhead, kFactor, kOrigin, deps.upstreamOrigin) + imageReserve;
@@ -2280,8 +2284,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
renderTags: "text-only",
contentStore: contentStoreOf(deps.session),
});
- deps.session.state = turn.state;
- adoptContentStore(deps.session, turn.contentStore);
+ adoptMeasuredTurn(turn);
// Absorbed pairs are hidden on the wire, so the fit check must see the
// same reduced payload prepare* will actually forward.
turn.messages = applyAbsorbView(turn.messages, turn.state, activeConfig, currentTokens);
diff --git a/src/server.ts b/src/server.ts
index 19cd75e7..2c36f8cb 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -1315,7 +1315,6 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
// — on by default; affinitySimhash: false / BILI_AFFINITY_SIMHASH=0
// restores the pre-#2265 exact-hash-only resolution (hot kill-switch).
setSimhashAdoptionEnabled(opts.affinitySimhash ?? true);
- hydratePrefixAffinity();
hydrateOrderSkeletons();
// #2941: never clobber a live pointer on this port — a foreign
// instance health-verified as serving here keeps it; our registry
@@ -1573,6 +1572,7 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
server.on("listening", installProcessHandlers);
server.listen(port, opts.host, claimOrAnnounce);
};
+ hydratePrefixAffinity();
attemptListen(opts.port);
// Listen errors (EADDRINUSE port taken, EACCES privileged port, EAFNOSUPPORT
// bad host) surface as an 'error' event on the server. Without a listener
@@ -3837,7 +3837,7 @@ export function measuredOutbound(prepared: { body: string | Buffer; parsedBody?:
export async function preflightCompressIfNeeded(
prepared: Prepared,
- runPrepare: () => Promise<Prepared>,
+ runPrepare: (recoverOverflow: boolean) => Promise<Prepared>,
req: http.IncomingMessage,
inboundBody: Buffer,
res: http.ServerResponse,
@@ -4358,14 +4358,23 @@ export async function preflightCompressIfNeeded(
streamSummaryOff,
};
let result: PreflightResult;
+ const rebuildAfterFold = async (): Promise<Prepared> => {
+ const estimateHoldStreak = session.state.nudge.estimateHoldStreak;
+ try {
+ const rebuilt = await runPrepare(!payloadFitsWindow && !imageArbitration);
+ session.stats.requests -= 1;
+ return rebuilt;
+ } finally {
+ session.state.nudge.estimateHoldStreak = estimateHoldStreak;
+ }
+ };
// #5974: when the corrective pass below folds nothing, its probe rebuild IS the final outbound — reuse it instead of paying for another prepare over a multi-MB body.
let pendingRebuild: Prepared | undefined;
try {
result = await preflightCompress(preflightDeps, prepared.originalMessages);
// #5974 (#4543-①): view-vs-reconstruction convergence. The walk's fit exit judges on its own blind processTurn(originalMessages) view, which can undershoot the full-pipeline reconstruction — fold-reconcile id churn re-enters unfolded mass the two pipelines disagree about. When the fresh rebuild measures over the window while the view exited early-fit with foldable mass left, run ONE corrective second pass seeded with the measured divergence as its exit bar: the fit judgment is forced through the post-reconstruction single source of truth (issue expectation clause ②). Bounded: the divergence must clear max(10K tok, 2% of window), unknown-baseline sessions keep their legacy upper-bound regime (#553), and a corrective pass that folds nothing falls through unchanged to the arms below.
if (result.compressedRanges > 0 && !unknownBaseline && result.failure === undefined && result.rangesRemaining > 0) {
- const probe = await runPrepare();
- session.stats.requests -= 1;
+ const probe = await rebuildAfterFold();
pendingRebuild = probe;
const probeMsgs = probe.processedMessages.length > 0 ? probe.processedMessages : probe.originalMessages;
const probeTextSize = estimateCoreMessages(probeMsgs) + overheadEstimate;
@@ -4421,12 +4430,7 @@ export async function preflightCompressIfNeeded(
if (result.compressedRanges > 0) {
// #5974: the corrective probe above may already hold the final rebuild —
// reuse it (a prepare pass over a multi-MB CJK body is not free).
- const rebuilt = pendingRebuild ?? await runPrepare();
- if (pendingRebuild === undefined) {
- // runPrepare re-incremented stats.requests; the rebuild is internal
- // to this single client request.
- session.stats.requests -= 1;
- }
+ const rebuilt = pendingRebuild ?? await rebuildAfterFold();
pendingRebuild = undefined;
outbound = rebuilt;
// #1987: anchor the usage baseline to what ACTUALLY ships — the rebuilt
diff --git a/src/server/handle.ts b/src/server/handle.ts
index 13ed4ebf..1bc726cf 100644
--- a/src/server/handle.ts
+++ b/src/server/handle.ts
@@ -3185,7 +3185,11 @@ async function handleRequest(
respondFailFast: boolean,
overflowWindow?: number,
) => Promise<{ body: string | Buffer; prepared: Prepared | null } | null>) | undefined = async (respondFailFast, overflowWindow) => {
- const runPrepareInner = async (): Promise<Prepared> => {
+ const runPrepareInner = async (recoverOverflow: boolean): Promise<Prepared> => {
+ const failureShrinkArmed = session.stats.lastInputTokensSource === "estimate" && session.stats.emergencyShrinkAt !== undefined;
+ const prepareConfig = recoverOverflow || failureShrinkArmed
+ ? { ...reqConfig, nudge: { ...reqConfig.nudge, requireUsageSampleForPressure: false } }
+ : reqConfig;
// #1820: this prepare consumes one unit of post-rebuild anchor
// validity (the last one deletes it — see session.ts).
tickPostRebuildAnchor(session);
@@ -3286,18 +3290,18 @@ async function handleRequest(
// v1internal dialect the model rides in the envelope meta
// instead of the path — fall back to it so Prepared carries
// a real model (the loop's synthetic frames read it back).
- return await prepareGoogle(work as GoogleRequestBody, opts, core, reqConfig, reqPrompts, reqSurface, log, session, pluginMode, nativeWindow, googleModel ?? v1Model, googlePathKind(urlPath) === "stream-generate", visibilityMarkers, upstreamOrigin, req, decide);
+ return await prepareGoogle(work as GoogleRequestBody, opts, core, prepareConfig, reqPrompts, reqSurface, log, session, pluginMode, nativeWindow, googleModel ?? v1Model, googlePathKind(urlPath) === "stream-generate", visibilityMarkers, upstreamOrigin, req, decide);
}
const preparedOut = protocol === "anthropic"
- ? await prepareAnthropic(work as AnthropicRequestBody, req, opts, core, reqConfig, reqPrompts, reqSurface, log, session, pluginMode, upstreamOrigin, reasoningCfg, visibilityMarkers, requestModel, decide)
+ ? await prepareAnthropic(work as AnthropicRequestBody, req, opts, core, prepareConfig, reqPrompts, reqSurface, log, session, pluginMode, upstreamOrigin, reasoningCfg, visibilityMarkers, requestModel, decide)
: protocol === "openai"
- ? await prepareOpenai(work as OpenAIRequestBody, req, opts, core, reqConfig, reqPrompts, reqSurface, log, session, pluginMode, upstreamOrigin, nativeWindow, reasoningCfg, visibilityMarkers, route?.rewrittenUrl, decide, bodyText)
+ ? await prepareOpenai(work as OpenAIRequestBody, req, opts, core, prepareConfig, reqPrompts, reqSurface, log, session, pluginMode, upstreamOrigin, nativeWindow, reasoningCfg, visibilityMarkers, route?.rewrittenUrl, decide, bodyText)
: responsesCompact
// #618: when no bili compaction item is present,
// prepareResponsesCompact falls back to the raw bodyBuffer —
// forward it unchanged (byte-identical passthrough).
? prepareResponsesCompact(bodyBuffer, work as ResponsesRequestBody, session, req, core, reqConfig, log)
- : await prepareResponses(work as ResponsesRequestBody, req, opts, core, reqConfig, reqPrompts, reqSurface, log, session, responsesIdentity!, pluginMode, upstreamOrigin, nativeWindow, reasoningCfg, visibilityMarkers, route?.rewrittenUrl, decide);
+ : await prepareResponses(work as ResponsesRequestBody, req, opts, core, prepareConfig, reqPrompts, reqSurface, log, session, responsesIdentity!, pluginMode, upstreamOrigin, nativeWindow, reasoningCfg, visibilityMarkers, route?.rewrittenUrl, decide);
// The resolved model rides with the prepared request: on the
// Anthropic-on-Vertex wire the body carries none, and the
// relay's compress-loop rebuild reads it from here.
@@ -3306,8 +3310,8 @@ async function handleRequest(
};
// #1295: stamp the envelope meta onto every Prepared for this
// request (initial AND preflight re-prepares both flow through).
- const runPrepare = async (): Promise<Prepared> => {
- const p = await runPrepareInner();
+ const runPrepare = async (recoverOverflow = false): Promise<Prepared> => {
+ const p = await runPrepareInner(recoverOverflow);
if (ccMeta !== undefined) p.commandcode = { meta: ccMeta };
return p;
};
diff --git a/tests/external-summary.test.ts b/tests/external-summary.test.ts
index b4ec99a7..57f73a9e 100644
--- a/tests/external-summary.test.ts
+++ b/tests/external-summary.test.ts
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
-import { test } from "node:test";
+import { test, type TestContext } from "node:test";
import { ExternalSummaryExecutor, externalSummaryFailureAdvice, type SummaryBudget, type SummaryCandidate, type SummaryWork } from "../src/external-summary.ts";
import { setLogCapture } from "../src/logger.ts";
@@ -109,37 +109,51 @@ test("external summary: a target timeout aborts transport and tries the next can
assert.equal(result.status, "success");
});
-test("external summary: the batch deadline is a shared pot — the next candidate gets the remaining budget instead of starving (#6885)", async () => {
+function summaryClock(t: TestContext): (ms: number) => Promise<void> {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: 0 });
+ t.mock.method(performance, "now", () => Date.now());
+ return async (ms) => {
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ t.mock.timers.tick(ms);
+ };
+}
+
+test("external summary: the batch deadline is a shared pot — the next candidate gets the remaining budget instead of starving (#6885)", async (t) => {
+ const advance = summaryClock(t);
let backup = 0;
- const result = await new ExternalSummaryExecutor(1).execute(work, [{ summarize: async (_request, signal) => new Promise<string>((_resolve, reject) => {
+ const job = new ExternalSummaryExecutor(1).execute(work, [{ summarize: async (_request, signal) => new Promise<string>((_resolve, reject) => {
signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
}) }, { summarize: async () => { backup++; return "backup"; } }], { ...budget, totalTimeoutMs: 15 });
+ await advance(7);
+ const result = await job;
assert.equal(result.status, "success");
assert.equal(backup, 1, "the remaining candidate gets the remaining budget instead of starving to zero");
assert.deepEqual(result.attempts.map((item) => item.outcome), ["timeout", "success"]);
});
-test("external summary: a shrunk target window reports the actual budget, not the nominal one (#6885)", async () => {
- const result = await new ExternalSummaryExecutor(1).execute(work, [{ summarize: async (_request, signal) => new Promise<string>((_resolve, reject) => {
+test("external summary: a shrunk target window reports the actual budget, not the nominal one (#6885)", async (t) => {
+ const advance = summaryClock(t);
+ const job = new ExternalSummaryExecutor(1).execute(work, [{ summarize: async (_request, signal) => new Promise<string>((_resolve, reject) => {
signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
}) }, successful("backup")], { ...budget, totalTimeoutMs: 15 });
+ await advance(7);
+ const result = await job;
assert.equal(result.status, "success");
const reported = Number((result.attempts[0].detail ?? "").match(/^target-timeout (\d+)ms/)?.[1]);
- assert.ok(Number.isFinite(reported) && reported < 500, `the reported budget is the shrunk window (${reported}ms), not the nominal 500ms`);
+ assert.equal(reported, 7, "the reported budget is the shrunk window");
});
-test("external summary: the total deadline still bounds the chain when every candidate is slow (#6885)", async () => {
+test("external summary: the total deadline still bounds the chain when every candidate is slow (#6885)", async (t) => {
+ const advance = summaryClock(t);
const hang: SummaryCandidate = { summarize: async (_request, signal) => new Promise<string>((_resolve, reject) => {
signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
}) };
- const started = performance.now();
- const result = await new ExternalSummaryExecutor(1).execute(work, [hang, { ...hang }], { ...budget, totalTimeoutMs: 15 });
- assert.ok(performance.now() - started < 150, "the chain stops at the total deadline, not after both nominal windows");
+ const job = new ExternalSummaryExecutor(1).execute(work, [hang, { ...hang }], { ...budget, totalTimeoutMs: 15 });
+ await advance(7);
+ await advance(8);
+ const result = await job;
assert.deepEqual(result.attempts.map((item) => item.outcome), ["timeout", "timeout"], "every candidate got a real share of the pot");
- // The last target's timer and the total deadline land on the same mark, so
- // the verdict is whichever clock the loop observes first.
- assert.ok(result.status === "deadline" || result.status === "failed");
- if (result.status === "failed") assert.equal(result.reason, "exhausted");
+ assert.equal(result.status, "deadline");
});
test("external summary: aggregate concurrency bounds distinct operations", async () => {
--
2.56.1.windows.1
|
Applies Beyfish's fix (ce47520f, SHA-256 verified) for the PR #6926 CI failures: - preflight: adoptMeasuredTurn preserves nudge.estimateHoldStreak across both preflight processTurn sites, so the #5865 estimate-hold window is not reset to 0 every round and the nudge can inject (#1137, option A from the pending needs-decision comment). - server: hydratePrefixAffinity moves to immediately before attemptListen so durable folds are visible to a new-ID retry after the previous process died (startup race); rebuildAfterFold saves/restores estimateHoldStreak around the rebuild so a corrective pass does not clobber the live streak. - handle: runPrepareInner takes recoverOverflow; when recovering a confirmed overflow or a failure-armed shrink, requireUsageSampleForPressure is disabled so the preflight can act on estimate evidence instead of waiting for a usage sample that the very overflow it is recovering from will not produce. - tests: external-summary #6885 shared-summary-budget tests use a controlled mock clock (summaryClock) so the deadline/timeout assertions are deterministic instead of racing the real timer.
…kernel/src changes) The PR's kernel/src changes (compress.ts, types.ts) require a kernel version bump per the Kernel Boundary version discipline. The previous merge resolved the version to 0.0.203, but master has since moved to 0.0.203, so the PR head's version no longer exceeds master's. Bump to 0.0.204 to satisfy kernel-guard.
Resolve the merge conflict with master (PR branch was dirty). The only conflicts were kernel version fields (both sides bumped from 0.0.202: master to 0.0.203, this branch to 0.0.204). Resolved to 0.0.204 (the higher version, which includes both sets of kernel/src changes: master's hide-consumed.ts and this branch's compress.ts/types.ts). Typecheck clean; targeted tests (fork-nudge-trigger, issue5631-restart- survival, external-summary) 30/30 pass.
(ai: vllm-qwen/qwen3.8-27b) CI fix run — PR #6926 (new head 94830cf) This run resolved two blockers on the PR branch: 1. kernel-guard failure (was red on head 7b061e4): The PR's kernel/src changes ( 2. Merge conflict with master (merge state: dirty): master moved to Verification: typecheck clean; targeted tests ( CI status: the mirror cache has not yet refreshed to the new head (still showing 八问(中文)
判定:两个阻塞均已修复并推送最终 head |
Re-verified the live state before touching anything — the reported blocker is already resolved, so no fix work was needed this run. What the event reported: Why it failed: kernel-guard rule 2 (version discipline) — the PR modified Already fixed (by an earlier wake, not this run):
Verified live this run (not from memory):
No pushes made this run — local and remote head were already in sync at |
…ts numbers (#7569) The pre-dispatch context-budget guard (src/external-summary-http.ts) threw 'External summary input exceeds the target context budget' before any fetch with no log line, so an oversized range left only attempts=[t0:error] in the receipt and nothing in bili.log — the operator could not tell a budget rejection from a network failure, nor which knob to change (contextWindow / outputTokens / range size). Repro on master 15f06c6: a provider model entry without contextWindow defaults to 128000 (outputTokens default min(8192, window/4)), so ranges above ~119.5K input tokens were silently rejected before dispatch (#6885 problem 2, #7569). - The HTTP candidate now warns once at the guard site with the numbers that produced the rejection (input/window/output tokens + the standard #4833 diagnostics), then throws the same message. - The executor records the same message in the attempt detail but no longer re-warns it (warnedByCandidate — the numbers only exist in the HTTP candidate), consistent with the upstream-rejection case. - Tests: guard rejection warns exactly once with the numbers and the request never reaches the upstream (the core repro); the guard does not fire when the input fits the window; the executor keeps the detail without a second warn. The receipt half of #7569 expectation 1 (attempt detail + advice branching) already ships in PR #6926; this commit closes the log half.
…eflight-compress Conflict resolutions (master 328fdeb into PR head cb8d623): - kernel version -> 0.0.207 (master 0.0.206 + PR #6882 kernel/src changes; Rule2 satisfied) - server.ts: order-persist retired (master); hydratePrefixAffinity kept at its pre-attemptListen site (PR startup-race fix, 7b061e4); both doom-math gates -> master #7537 always-forward (no local estimate-refusal) - handle.ts: prepareOpenai combines PR prepareConfig + master bodyParseDeferred + pureChainContinuation branch - src/order-persist.ts deleted (master retirement)
(ai: vllm-qwen/qwen3.8-27b) Merged Note on status: the mirror check-cache still reports the pre-push head (cb8d623, mergeable Conflict resolutions (master into PR head):
结构化八问
判定: 合并冲突已全部解决并推送,PR 分支 head 现为 8890f4a,可进入 CI 与评审。 |
[ework] auto-fix stalled: test (windows-latest, 22, 5), test (windows-latest, 22, 3), test (ubuntu-latest, 24, 2), test (ubuntu-latest, 22, 2) — stopping for human review |
🔶 需要决策 #3573 wall-budget feature conflicts with master's one-shot fold gate (#7545) — my merge resolution broke the PR's #3573 test. What happened: I merged const compressionCommitted = !epochReplaced && (session.state.stats?.compressionCount ?? 0) > 0;
const preflightSpent = (session.stats.preflightRuns ?? 0) > 0;
if (compressionCommitted || preflightSpent) { log; return prepared; }The PR's #3573 wall-budget feature (src/preflight.ts:2380-2383, 3792-3800) relies on multi-attempt convergence: each attempt stops at the client-patience wall budget, persists its folds (shrinks the view), returns 502 retryable, and the client retry re-folds from the smaller view. But the one-shot gate blocks the 2nd+ fold (preflightRuns > 0 after attempt 1, incremented at src/server.ts:4750), so the payload never shrinks below the window → 400 forever → the #3573 test fails ( This is a cross-branch semantic conflict: both features solve the SAME problem (slow-self-summarizer livelock, 2026-11-22 incident: 9 preflight runs of the same ~77K payload) with DIFFERENT mechanisms. The one-shot gate over-blocks: it blocks on Options:
Recommendation: C (most faithful to both features' intent). The one-shot gate's purpose is to prevent the slow-self-summarizer livelock (a payload that does NOT shrink across retries). The #3573 wall-budget stop ensures the payload SHRINKS (persists folds). So the gate should block only when the payload did NOT shrink, not when it did. This requires tracking the payload size (or fold count) across retries in the session. Default if undecided: B (simpler — exempt the wall-budget stop from the one-shot gate; the wall-budget stop is retryable by design and persists folds, so it is safe to retry). Other failing checks (NOT caused by my merge, not small mechanical fixes):
Next: awaiting owner decision on the #3573 conflict (A/B/C). The other failures need separate investigation (not small mechanical fixes). |
Correction to my previous comment: the default-if-undecided should be C, not B. Option B (exempt all wall-budget stops from the one-shot gate) is not safe in the case where the wall budget is hit but no progress was made (0 folds persisted) — the view would not shrink and the slow-self-summarizer livelock would be reintroduced. Option C (the one-shot gate blocks only when the payload did NOT shrink across retries) is the safe default: it preserves both features' intent (the livelock is still blocked, and the wall-budget convergence is allowed when the payload actually shrinks). |
[ework] auto-fix stalled: test (windows-latest, 22, 5), test (windows-latest, 22, 3), test (ubuntu-latest, 24, 2), test (ubuntu-latest, 22, 2) — stopping for human review |
…flict batch Conflict resolutions (master 25c8d8a into PR head 8890f4a): - kernel version -> 0.0.211 (master 0.0.210 + PR #6882 kernel/src changes; Rule2 satisfied; root + kernel lockfiles synced, lock-sync idempotency checks pass) - src/preflight.ts: import union — master's UPSTREAM_FIRST_BYTE_TIMEOUT_CODE (upstream-fail.js) + PR's markDirty (session.js); both symbols verified used - src/external-summary.ts: keep PR #7569 — the context-budget guard rejection carries warnedByCandidate: true (the HTTP candidate owns the warn with input/window/output numbers, src/external-summary-http.ts:276-280; the executor must not re-warn), superseding master #6885's generic-list entry - src/external-summary-compress.ts: keep master #6905 — the all-candidates-failed line carries the consecutive-failure guard (recordExternalSummaryFailure); both sides had already converged on externalSummaryFailureAdvice() - tests/external-summary.test.ts: keep PR — TestContext import (used by summaryClock), the #6885 non-fetch test re-pinned to the 'response did not complete' message, plus the new #7569 test pinning zero executor warns for the context-budget rejection - scratch dotfiles (.ci6785-final.txt, .comment-7439.md, .pr-body.md, .reply-7439.md): deleted per master (they no longer exist upstream) Verified locally: typecheck + build green; kernel suite 1688/1688; external-summary + external-summary-http + issue3978 (persistence/terminal-frame) + wire-contract-go-session + tmp-rm + preflight-compress suites green. Pre-existing red (NOT introduced by this merge): tests/issue3573-preflight-client-patience.test.ts 'slow summary rounds' fails identically at the pre-merge head 8890f4a — the one-shot fold gate (#7545, merged to master 2026-11-22) blocks the PR's cross-attempt retry convergence after the first stopped attempt commits its folds.
🔶 需要决策 (ai: vllm-qwen/qwen3.8-27b) This run: merge conflict resolved and pushedMerged Conflict resolutions (full notes in the merge commit):
Local verification on the merged tree: typecheck + build green; kernel suite 1688/1688; external-summary, external-summary-http, issue3978 (persistence + terminal-frame), wire-contract-go-session, tmp-rm, preflight-compress suites all green. Red CI found (pre-existing — NOT introduced by this merge)
Proven pre-existing: I ran it at the pre-merge head 8890f4a in a clean worktree — identical failure. This matches the stale CI cache (2026-11-23, same head): 4 red test shards. Root cause (design clash, not a mechanical bug): the one-shot fold gate (#7545,
The gate's incident protection is about no-progress loops (payload identical on every retry); the PR's design persists progress every round (folds commit before the 502). The gate cannot tell the two apart — it only checks the committed count. Options
Recommendation: A — the cross-attempt convergence IS the point of the wall-budget feature, and the gate's incident protection targets no-progress loops, which A structurally excludes (every re-armed round must persist a fold). Default if undecided: B — changing a safety gate's semantics is the higher-risk move; re-pinning the PR's test to post-gate behavior is the conservative path. Applied the 结构化八问
判定:冲突已解决、PR 已可合并(等新 head CI);红测试为合并前既有的设计冲突,已打 needs-decision 标签,等 owner 在 A/B/C 中拍板。 |
(ai: vllm-qwen/qwen3.8-27b) Re-verified live: all 3 red shards are the same already-reported design clashFetched the three failing job logs (ubuntu 24/1, ubuntu 22/1, windows 22/3) and checked each one:
All three fail with the identical assertion: This is exactly the design clash diagnosed in my previous comment: the one-shot fold gate (#7545, merged to master 2026-11-22 — after this PR branched) marks the session compression-managed once the first wall-budget stop commits its folds, so every subsequent retry is forwarded as-is → 400 loop. There is no mechanical fix — this IS the design clash, and the options are already posted:
The Note: master moved 13 commits ahead since my merge (mergeable state "behind", no conflict). I will merge master into the branch and push the final head in one shot once the decision lands and the fix is implemented — merging now would only burn a CI pass on the same red. 结构化八问
判定:红 CI 已完全归因于已报告的设计冲突(3 shard = 同一测试 = 同一断言);needs-decision 标签在位;等 owner 在 A/B/C 中拍板后继续。 |
[ework] auto-fix stalled: test (ubuntu-latest, 24, 1), test (ubuntu-latest, 22, 1), test (windows-latest, 22, 3) — stopping for human review |
…flict batch Conflicts: kernel/package.json + kernel/package-lock.json + root package-lock.json (kernel version) + src/server/handle.ts (runPrepare). Kernel version resolved at 0.0.215 = master's 0.0.214 + this PR's own kernel step (#6882 truncate estimate-hold, not on master) — satisfies kernel-guard (version line must differ from master whenever kernel/src differs; no bump-without-src-change). handle.ts runPrepare = union of the PR's recoverOverflow recovery param and master's #7684 noteSessionLaneSwitch logging call (orthogonal; the lane-switch call is purely additive logging). Local: typecheck clean, build clean, kernel issue6882 10/10, external-summary 25/25, preflight terminal-frame 4/4. The #3573 slow-summary convergence failure is PRE-EXISTING on the PR head (464c24b) — reproduced identically on a clean PR-head worktree, not introduced by this merge.
(ai: vllm-qwen/qwen3.8-27b) PR #6926 merge conflict resolved and pushed. What was done this run:
八问(结构化结论):
判定: 冲突已解决并以最终头 |
[ework] CI fix verified green ✓ |
…flict batch Conflicts: kernel/package.json + kernel/package-lock.json + root package-lock.json (kernel version only). Kernel version resolved at 0.0.218 = master's 0.0.217 + this PR's own kernel step (#6882 truncate estimate-hold, not on master) — satisfies kernel-guard (version line must differ from master whenever kernel/src differs; no bump-without-src-change). All 7 both-sides host files auto-merged byte-identically to an independent git merge-file 3-way (base 24ba3ad, ours c2b168e, theirs 5bb3eb2): docs/configuration.md/.zh-CN.md, kernel/src/compress.ts, kernel/src/types.ts, src/config.ts, src/server.ts, src/server/handle.ts. Local: typecheck clean, build clean, lockfiles byte-stable after full install; kernel issue6882 10/10, external-summary 25/25, preflight terminal-frame 4/4.
(ai: vllm-qwen/qwen3.8-27b) PR #6926 merge conflict resolved and pushed (second conflict batch since master advanced again). What was done this run:
八问(结构化结论):
判定: 冲突已解决并以最终头 |
[ework] CI fix verified green ✓ |
compress.maxSummaryLength; named error → "the attempts below name the failing cause"; otherwise → "see the attempt outcomes") instead of always pointing atmaxSummaryLength(cherry-picked from [PR] fix(compress): name non-fetch external-summary failures instead of swallowing them #6890).What this PR does
One root-cause PR for the
preflight-compressbatch (rcagg #6896): preflight compression on large contexts either ran for hours, or failed 100% on long payloads, or latched truncation off meter readings the bill never saw.Fixes #3978
Fixes #6882
Fixes #6885
Fixes #7569
The four prior PRs on these issues (#4046, #3590, #5057, #6890) are all direction-aligned with the root cause; their commits are cherry-picked below with
-x(authorship preserved) instead of shipping four overlapping PRs.#3978 — the preflight marathon (three halves)
commitFoldmarks the session dirty as each fold lands, so a client disconnect/abort mid-marathon no longer loses the attempt's progress — the retry resumes from the smaller view instead of re-compressing from zero.#6882 — the truncate watermark acts on estimate-grade reads (kernel, option A)
kernel-change: #6882 option A — the emergency-truncate watermark now honors the SAME estimate-hold guard the pressure band already uses: a watermark crossing on an estimate-grade reading (1.75–1.87× overstated after a stream interruption) is held for up to
compress.maxEstimateHoldRoundsestimate rounds (default 2) instead of latching clips the bill never saw. Already-latched clips still replay byte-for-byte; the held round is unjudged (the terminal streak rides through untouched). Billed readings (incl. the overflow arm), hosts omitting the source marker, and the guard-off / backstop-elapsed cases keep byte-identical behavior. New kernel suitekernel/tests/issue6882-truncate-estimate-hold.test.ts(10 cases); kernel 0.0.198 → 0.0.199. Per the Kernel Boundary this stays in the human-only review tier; it implements the option requested in #6882 via the rcagg pipeline.#6885 — the external-summary serial budget starves later candidates
min(targetTimeoutMs, remaining pot / remaining targets). Before, every target got a freshtargetTimeoutMswindow, so t0 (25s) + t1 (25s) ate the 50s total and t2 never got a request out — the chain failed 100% on long payloads (558 target-timeouts / 258 batch-deadlines / 5 successes in the incident log). The configuredtargetTimeoutMsstays the per-candidate cap; the 600s/180s workaround keeps its full 180s windows (600s/3 > 180s).POST /__bili/config/reloador restart applies it; Web-UI saves hot-apply), and the reasoning-targetoutputTokenspitfall (finish_reason=length+ empty body).Behavior changes (old → new)
Preflight abort ([Bug] Excessive preflight compression time on ultra-large contexts; client mid-disconnect causes repeated request forwar | [Bug] 超大上下文 preflight 压缩耗时过长,客户端中途断开导致请求反复无法转发 #3978): old — a client disconnect mid-marathon lost every fold of that attempt; the retry re-compressed from zero. New — each committed fold is persisted as it lands; the retry resumes from the smaller view.
Preflight wall clock ([Bug] Excessive preflight compression time on ultra-large contexts; client mid-disconnect causes repeated request forwar | [Bug] 超大上下文 preflight 压缩耗时过长,客户端中途断开导致请求反复无法转发 #3978): old — preflight ran until the round cap (16) or budget regardless of wall time (observed 320s+/range, 288s/8 rounds, 864s/32 ranges). New — it stops at a 50s wall budget (elapsed + estimated next round), persisting the folds so far; the retry resumes from the smaller view.
Preflight failure on a committed response ([Bug] Excessive preflight compression time on ultra-large contexts; client mid-disconnect causes repeated request forwar | [Bug] 超大上下文 preflight 压缩耗时过长,客户端中途断开导致请求反复无法转发 #3978): old — a failure after headers were sent could leave the connection hanging. New — the response is terminated with a protocol error frame (SSE event or JSON body).
Emergency truncate on estimate readings (Kernel authorization request: emergency-truncate — does not check the reading level; after a stream interruption, it wil | Kernel authorization request: emergency-truncate 不看读数等级,流中断后按估计值也会截断并锁住;建议沿用 requireUsageSampleForPressure 的守卫和 maxEstimateHoldRoun… #6882): old — a watermark crossing on an estimate-grade reading truncated + latched immediately. New — held under the same estimate-hold guard as the pressure band (default: up to 2 estimate rounds), then acts on the estimate anyway (backstop). Billed readings and guard-off are byte-identical. Old behavior:
compress.requireUsageSampleForPressure: false.External-summary per-target window ([Bug][compress][externalSummary] Serial 25s/50s default budget makes long-payload chains fail 100%; non-fetch failures a | [Bug][compress][externalSummary] Serial 25s/50s default budget makes long-payload chains fail 100%; non-fetch failures are swallowe… #6885): old — each candidate got a fresh
targetTimeoutMswindow drawn from the shared total (early candidates could eat the whole pot). New — each candidate getsmin(targetTimeoutMs, remaining pot / remaining targets); the total deadline still bounds the chain.External-summary timeout detail ([Bug][compress][externalSummary] Serial 25s/50s default budget makes long-payload chains fail 100%; non-fetch failures a | [Bug][compress][externalSummary] Serial 25s/50s default budget makes long-payload chains fail 100%; non-fetch failures are swallowe… #6885): old — the attempt detail reported the nominal configured budget. New — it reports the actual window the attempt had. (Model-visible, see top.)
External-summary guard rejection log ([Bug][externalSummary] Intervals exceeding the target window are rejected before emission; only t0:error remains in the | [Bug][externalSummary] 超出目标窗口的区间在发出前被拒,日志只剩 t0:error(master 15f06c6 仍复现) #7569): old — the context-budget guard rejection produced NO log line (the receipt showed only ). New — one warn at the guard site with the numbers (input≈Ntok, window=Wtok, outputTokens=O + budget/protocol/payload diagnostics); the executor no longer emits its second warn for this error (the detail stays in the attempt). Log-only; no wire/model/config change.
Config surface
No new config fields. Two EXISTING fields gain coverage (semantics extend, no migration):
compress.requireUsageSampleForPressure(defaulttrue): was "the pressure band waits for a usage sample on estimate readings"; now also covers the emergency-truncate watermark (Kernel authorization request: emergency-truncate — does not check the reading level; after a stream interruption, it wil | Kernel authorization request: emergency-truncate 不看读数等级,流中断后按估计值也会截断并锁住;建议沿用 requireUsageSampleForPressure 的守卫和 maxEstimateHoldRoun… #6882).falserestores the legacy estimate-driven pressure injection AND estimate-driven truncation.compress.maxEstimateHoldRounds(default2): was the backstop for the pressure band; now also bounds how many estimate rounds the truncate watermark may wait.0disables the hold for both.Both keep their existing per-field merge (global → provider → model) and kernel mapping (
nudge.*). The existingcompress.externalSummary.budgetfields are unchanged — only howtotalTimeoutMsis divided across targets changed (behavior change 5).Tests
kernel/tests/issue6882-truncate-estimate-hold.test.ts— 10 new cases: held round (no clip, no latch,truncationSkippednames the estimate grade), held round byte-identical to a below-threshold round, latch replays byte-identically on the held round, backstop elapse (streak > cap → truncates), usage reading truncates, no source marker truncates,requireUsageSampleForPressure: falsetruncates,maxEstimateHoldRounds: 0truncates, terminalStreak rides through, held-after-stuck keeps the streak. Kernel suite 1650/1650;verif-subset-guard+ the compress.ts verif bug/generic/induction suites green.tests/issue3978-preflight-abort-persistence.test.ts(from [PR] fix: persist each committed preflight fold so a dead marathon leaves durable progress (#3978) #4046) — clean-abort durability, negative control, SIGKILLed-child retry inherits via the affinity chain.tests/issue3573-preflight-client-patience.test.ts(from [PR] fix: stop preflight marathon rounds that would blow the client's patience wall clock (#3573) #3590) — slow-summary retry converges to 200; fast marathon is a single attempt.tests/issue3978-preflight-terminal-frame.test.ts(from [PR] fix: terminate committed preflight responses with a protocol error frame (#3978) #5057) — SSE frame / JSON frame / uncommitted negative control / abort log outcome.tests/external-summary.test.ts— 3 new shared-pot tests (fair share, actual-budget reporting, total still bounds the chain); 96/96 with the http suite; plus the [Bug][externalSummary] Intervals exceeding the target window are rejected before emission; only t0:error remains in the | [Bug][externalSummary] 超出目标窗口的区间在发出前被拒,日志只剩 t0:error(master 15f06c6 仍复现) #7569 guard tests (warn with numbers + request never dispatched, negative control when the input fits the window, executor keeps the detail without a second warn).Local verdict (rebased head)
typecheck clean, build clean, targeted suites green (listed above). Full-suite verdict = remote CI on this head.