Skip to content

fix(dsh-native): threw gate attribution gets a bounded settle-retry; provably-oversized bodies fail locally - #2940

Merged
ranxianglei merged 10 commits into
ranxianglei:masterfrom
YunzhouLi-hub:2026-10-12_threw-gate-recovery
Oct 13, 2026
Merged

ranxianglei merged 10 commits into
ranxianglei:masterfrom
YunzhouLi-hub:2026-10-12_threw-gate-recovery

Conversation

@YunzhouLi-hub

Copy link
Copy Markdown
Contributor

What changed

Implements the fix directions the owner's triage on #2924 recommended (direction 2 for recovery + direction 1 for honest failure), scoped strictly to the threw attribution state. none (legitimate agentless lanes) keeps today's #1117 DIRECT semantics byte-for-byte.

Direction 2 — threw gets a bounded settle-retry (the only path that can RESTORE a session)

src/agent/dsh-native.ts — attributionOf() returning threw (an internal error in the host's lookup, e.g. cannot get required service "agents" in inactive context) no longer collapses into the same return false as none. The gate now retries attribution on a bounded schedule (default 3 attempts × 250 ms, so a dying turn pays at most ~500 ms) before deciding:

  • scope settles within the window → request is claimed — bili stays in control, the session is recovered;
  • resolves to none meanwhile → today's refusal (state-transition log, unchanged);
  • still threw → direction 1's size check below.

Rationale (from the triage): once a local transcript exceeds the window, ACP compression is the only path that can shrink it — the host's own compaction and the #1117 direct fallback must both ship the full history upstream and 400. So the instant the gate lets go, all recovery paths vanish simultaneously; retrying attribution is the only way back.

Direction 1 — provably-oversized bodies fail LOCALLY (422), not upstream (400)

When threw persists and the body provably cannot fit the effective window, the fetch lane now answers with a protocol-shaped 422 (#2709 precedent: not credential-class, not transient-class — hosts treat it as a policy refusal of this ONE request) instead of handing upstream a request that can only 400. On a >window history that 400 is fatal — every later request carries the same history, so the session dies.

Conservatism is deliberate: the size arm refuses only when the floor estimate (bytes / 4) already exceeds the window, so the guard cannot false-refuse — the reporter's own session ledger shows real bodies run above the byte estimate on this host (calibratedEstimate ≈ 1.14), and that bias cuts toward more headroom, not less. Unknown window, stream/FormData body, or absent body ⇒ the size arm disarms and #1117 direct semantics apply (never a false refusal from missing data).

Window resolution reuses exactly the headersFor path (#2381: the session's live model first, host global default as fallback, cached model info only) — no new lookup, no new source of truth.

Interface widening (the one mechanical cost flagged in the proposal)

takeoverGate widens from (url) => boolean to (url, body?) => GateVerdict | Promise<GateVerdict> with GateVerdict = boolean | "refuse-oversized". Both fetch call sites await (a sync boolean is unchanged — await false is false, so every other host's gate keeps working untouched). The WS lane's state.takeoverGate(target) === false check needed no change: a Promise is never === false, so a mid-retry WS connection is claimed rather than refused — consistent with direction 2 and irrelevant in practice (the dsh gate never meets the codex-WS lane).

Config surface

None. No new config field, env var, or CLI flag. Retry cadence and the size arm derive entirely from existing in-process state; the retry constants are module-level with a _setThrewRetryForTest hook (same discipline as BILI_MODEL_INFO_RETRY_MS), not a user knob. If the owner wants the cadence configurable it can be routed through src/knobs.ts later — deliberately not done here (Configuration Surface Discipline).

Kernel

No changes under kernel/ — everything lives in src/agent/ (dsh-native, native-intercept) plus tests.

Pre-flight (rebased on master @ c76650f)

Tests

New (regression: the original bug + the new outcomes):

  1. #2924 gate threw attribution: bounded settle-retry recovers and CLAIMS the request — the field-report shape: initiator throws twice (disposed scope), settles on the third read; the gate returns true and the recovery is durably logged.
  2. #2924 gate threw persists: provably-oversized body refuses LOCALLY, everything else keeps #1117 semantics — 4004 B / 4 = 1001 tok > 1000 window → "refuse-oversized" + durable LOCAL-refusal line; boundary 4000 B (== window) → false; unreadable body → false; no resolvable window → false.
  3. #2924 takeoverGate refuse-oversized: local protocol-shaped 422, upstream never called — both wire shapes (anthropic + openai envelopes), sink empty, onDispatch "refused".
  4. #2924 takeoverGate may return a Promise (+ an async-refusal companion) — the widened contract flows through the same branches.

Updated: the #1158 L2 three-state test now awaits its two threw verdicts and injects a fast retry cadence (its assertions are otherwise untouched).

Deliberately NOT in this PR

Fixes #2924. Review focus per §7.5: both call-site semantics under each verdict, and the retry's bounded-deadline behavior on a closing scope.

…provably-oversized bodies fail locally (ranxianglei#2924)

Direction 2 (recovery, owner triage priority): a `threw` attribution is an
internal error in the host's lookup (disposed agent scope), never a legitimate
agentless lane. The gate now settle-retries (default 3 attempts x 250ms) before
deciding; a scope that settles within the window gets its request CLAIMED —
the only path that restores an over-window session, since the host's own
compaction and the direct fallback must both ship the full history upstream.

Direction 1 (honest failure): when `threw` persists and the body provably
cannot fit the effective window (floor estimate bytes/4, so the guard cannot
false-refuse), the fetch lane fails this ONE request locally with a
protocol-shaped 422 (ranxianglei#2709 precedent) instead of handing upstream a guaranteed
400 that kills the session. Unknown window or unreadable body keeps ranxianglei#1117
direct semantics; `none` (legitimate agentless lanes) is unchanged.

The gate signature widens to (url, body?) => GateVerdict | Promise<GateVerdict>;
the sync contract is preserved (awaiting a boolean is a boolean), and the WS
lane's `=== false` check is unaffected. Fixes ranxianglei#2924.
…ne too

The direction-1 local 422 was only wired into the raw-URL branch; an
already-routed (settings overlay) request whose gate verdict was
"refuse-oversized" fell into the ranxianglei#1117 unattributed bucket and rode the
x-bili-passthrough marker through the proxy verbatim — the same
guaranteed upstream 400 the raw lane now refuses. Check the verdict in
the routed lane as well: provably-oversized fails LOCALLY (422,
x-bili-gate: oversize-refusal), everything else keeps ranxianglei#1117 semantics.
@ranxianglei

Copy link
Copy Markdown
Owner

Review follow-up (pushed as e915b00, credit for the base fix stays with @YunzhouLi-hub):

Independent review found one non-blocking gap in direction 1 — the refuse-oversized verdict was only honored in the raw-URL branch. An already-routed (settings overlay) request whose gate verdict came back "refuse-oversized" fell into the #1117 unattributed bucket and rode the x-bili-passthrough marker through the proxy verbatim — the very same guaranteed upstream 400 the raw lane now refuses. The #2924 incident itself rode the raw lane, so the base PR fixes the reported failure either way; the routed lane was a residual copy of the same cliff.

e915b00e checks the verdict in the routed lane as well: provably-oversized → local 422 (x-bili-gate: oversize-refusal), never reaches the network; everything else (true / false / promise forms) keeps #1117 semantics byte-for-byte. New test pins it (#2924 takeoverGate refuse-oversized on an already-routed /bili/ URL fails locally (no passthrough ride)); suites 111/111 + ws-intercept + apig-resign green, typecheck clean.

Everything else in the review came back clean: the oversize arm cannot false-refuse (bytes/4 floor, window resolution is all try/catch → arm disarms on any miss), the settle-retry latency is bounded at ~500ms, none lanes are unchanged, and the WS lane's === false check is unaffected (a pending promise biases toward claimed, the safe direction).

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

Verification complete — e915b00e confirmed correct and green (checked out current head d108acd52 locally):

  • Diff audit: the routed lane now branches on the explicit verdict — "refuse-oversized" → oversizeRefusal() (local 422, x-bili-gate: oversize-refusal, protocol-shaped envelope per wire family, src/agent/native-intercept.ts:645-653), never reaches the network; false → 「BUG」native-intercept 进程级 globalThis.fetch 补丁按 URL 形状接管所有模型流量,无关调用者(如 MemOS)被卷入宿主压缩流程 #1117 passthrough stamp + direct send, byte-for-byte unchanged; true → attributed path; undefined gate → the whole block is skipped, identical fall-through to the old code. Promise form is awaited.
  • Lane consistency: raw-URL lane (src/agent/native-intercept.ts:804-832) untouched; WS lane (src/agent/native-ws-intercept.ts:372) still === false — a pending promise there biases toward claimed, the safe direction, as stated.
  • New test runs and passes (ok 33): asserts 422 + header + zero network calls + ["refused"] dispatch — real teeth, pins exactly this regression.
  • Targeted suites: native-intercept 58/58; combined with ws-intercept + apig-resign → 117/117 pass, 0 fail.
  • Typecheck: tsc --noEmit exit 0, zero errors — the 8 pre-existing master errors the base PR noted are gone after the rebase onto current master.
  • CI on head: 24 passed / 0 failed / 8 pending (long e2e lanes still running); no red anywhere.

结构化八问(验证结论)

  1. 是什么问题:基础 PR 的 direction-1 本地 422 只接在 raw-URL 分支;已被路由(settings overlay)的请求若 gate 判 refuse-oversized,会落进 「BUG」native-intercept 进程级 globalThis.fetch 补丁按 URL 形状接管所有模型流量,无关调用者(如 MemOS)被卷入宿主压缩流程 #1117 unattributed 桶、带 x-bili-passthrough 标记原样穿代理——正是 raw lane 现在拒绝的那种必然上游 400。
  2. 什么原因导致的:同一机制家族的第二条调用路径漏接——新裁决值引入后,routed 分支仍用旧 !== true 单条件判断,把 refuse-oversized 误归入 unattributed。
  3. 影响范围与严重程度:窄面——需 dsh-native 宿主 + 请求已被 overlay 路由 + 中途归属失败(threw)+ body 证明确超窗,四者同时成立才触发;后果是浪费一次必然失败的上游行、暴露 provider 400 而非清晰本地策略拒答。非阻塞级,与评估一致([dsh-native] takeover-gate refusal (threw state) fails open with the FULL uncompressed transcript; a >window local history dies upstream with 400 (maximum context length) #2924 事故本身走 raw lane,基础 PR 已覆盖报告故障)。
  4. 怎么修复的:routed lane 显式分支裁决值——provably-oversized 本地 422(x-bili-gate: oversize-refusal,按 wire 家族给协议形状信封),永不触网;其余所有形态(true/false/promise)逐字节保持 「BUG」native-intercept 进程级 globalThis.fetch 补丁按 URL 形状接管所有模型流量,无关调用者(如 MemOS)被卷入宿主压缩流程 #1117 语义。
  5. 是否有回归问题:无。逐项过:gate=undefined 时新代码整块跳过,与旧 unattributed=false 落点相同;false→passthrough 打标+direct 发送路径未动;raw lane、WS lane(=== false)均未改动;promise 形态被 await,WS 侧 pending promise 偏向 claimed(安全方向)。唯一行为变化即本修复本身(旧:必然上游 400 → 新:本地 422,已在评论披露)。无 fail-fast 变吞错、无阈值/时序漂移、无输出格式变化。
  6. 是否破坏缓存:不涉及——纯传输层逐请求决策,不触碰会话状态/压缩游标/去重键/重试策略。
  7. 是否改了设计方向:不涉及——只是把既有 GateVerdict 决策面接到第二个调用点,无架构/边界/数据流变化。
  8. 是否引入了新的配置:无——零新增 env/config/默认值。

判定:代码与测试全部核实通过,PR 就绪。CI 剩余 8 个长 e2e lane 跑完即全绿(当前 0 红);merge 按规矩留给人来执行。

@ranxianglei
ranxianglei merged commit 35591c3 into ranxianglei:master Oct 13, 2026
33 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.373-master.35591c3 (rolling master tag).

npm install -g billion-context@0.0.373-master.35591c3  # 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

Projects

None yet

2 participants