Skip to content

fix: bound the native fetch chain against coexisting re-wrapping plugins (#1662) - #1672

Merged
ranxianglei merged 2 commits into
masterfrom
2026-09-29_fetch-chain-depth
Sep 30, 2026
Merged

ranxianglei merged 2 commits into
masterfrom
2026-09-29_fetch-chain-depth

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #1662

Problem

With dsh-codex-subscription installed alongside bili plugin install dsh, the dsh web process dies with RangeError: Maximum call stack size exceeded (repro report: bili 0.1.164 / DSH 0.1.7-rc.2 / Windows; latent in current master too). The existing #1158 guard + #1410 re-anchor were both present in the failing version — this is a gap beyond #1410.

Root cause

dsh-codex-subscription repeatedly performs {read current globalThis.fetch → wrap it with its injection logic → write back}. The #1158 guard adopts every third-party install as downstream (top = makeChain(v)), so each cycle stacks one (wrapper, bili-link) pair onto the chain:

C_n → w_n → C_{n-1} → w_{n-1} → … → C_1 → nativeFetch

Every request then walks the ENTIRE accumulated history — each stacked bili link re-running the full dispatch (URL parse, routing decision, header stamping, gate waits). Stack depth grows with session lifetime. Measured on Node v22.23.2/Linux: 4K churn cycles still OK, 8K cycles → RangeError (the user's live crash). #1410's re-anchor only repairs links whose downstream DIES; it never prunes live-but-redundant stacked pairs. Worse, past REARM_LIMIT = 16 the setter surrendered the top slot (top = v) and stopped logging entirely — so growth continued silently with zero visibility after the first 16 evict-attempt lines.

Reproduced deterministically before the fix (probe: N churn cycles of read-top/wrap/write-back, then one model request): N=8000 → RangeError: Maximum call stack size exceeded; after the fix N=50000 → OK, request routed correctly, single one-time warning.

Fix (src/agent/native-intercept.ts, shared by all native lanes)

  1. Re-entry termination. Per-request dispatch depth is tracked in an AsyncLocalStorage (not a global counter — concurrent top-level requests must not see each other). A bili link called from within our own dispatch can only be reached through a foreign wrapper that captured one of our older tops — that is the proof of accumulated nesting. At that point everything below is redundant (the top link already rewrote/stamped model URLs; everything else passes through unchanged), so the descent terminates at the oldest still-live anchor (the host baseline that survived every prior teardown) instead of walking the history. Request depth becomes constant no matter how many times the coexisting plugin re-wraps. Depth ≥ 2 falls back to the plain walk so the termination itself can never loop (degenerate multi-plugin nesting).
  2. Past-cap semantics. After REARM_LIMIT the warning stops (log spam) but adoption CONTINUES instead of surrendering the top slot. With (1), each further adopt costs O(1) per request regardless of history length, so the cap now bounds logging only; routing authority never leaves the guard.

The newest foreign wrapper's behavior (e.g. ChatGPT auth injection) is preserved: it sits below the top link and its hook still runs exactly once per request (pinned by test).

Behavior changes (disclosure)

  • Past REARM_LIMIT (16 third-party installs): old = guard surrenders the top slot to the foreign wrapper (top = v), routing continued only via the orphaned stale chain, no further logging. new = guard keeps adopting every further install as downstream and stays active forever; warnings suppressed after 16. WHY: the surrender left unbounded silent chain growth (this bug); with re-entry termination continued adoption is O(1) per request.
  • New one-time log line when nested re-entry is detected: [bili-native] nested re-entry into the bili fetch chain detected (#1662) — … terminating the descent at the oldest live anchor…. Purely additive visibility.
  • Rare degradation: with TWO concurrently-LIVE foreign wrappers both wrapping the chain, the older wrapper's injection is skipped for affected requests (same class as the documented BILI_RECLAIM_FETCH_PATCH=0 escape hatch). The real-world churn case (one live wrapper) is fully preserved.
  • No config surface change, no wire/message-shape change, no persistence change.

Tests

tests/native-intercept-selfheal.test.ts (+96 lines):

Pre-flight

  • npm run typecheck ✅
  • npm test: 3177 pass / 0 fail / 16 skipped (by design) ✅
  • npm run build ✅
  • Repro probe: pre-fix N=8000 → RangeError; post-fix N=50000 → OK ✅

Note: #1666 (same reporter, follow-up after upgrading everything) describes a DIFFERENT symptom — connect timeout to chatgpt.com through the proxy, not a crash — and is handled in its own thread.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-29_fetch-chain-depth (0486bdc)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.1676-pr.1672.5c39bb8

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-pr1672.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始 review PR #1672(fix: bound the native fetch chain against coexisting re-wrapping plugins)。按规范走:审原 issue #1662 → 回归审查 → 代码审查 → 测试有效性 → diff 整洁度。先拉分支核对代码与 CI 状态,稍后给结论。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review 完成:可以合并(人工合并)

按规范五关走完,逐项结论如下。本地验证分支 review-1672-rebase(已 rebase 到当前 master c0e9e65f,干净无冲突,未推远端——仓库惯例是 merge commit,GitHub 可直接合 behind 的分支)。

① 原 issue 方向关 ✅
#1662 是真 bug:根因定位正确(churn 型第三方包装使链线性增长 C_n → w_n → C_{n-1} → …,每请求全量遍历历史,非模型 URL 路径全程同步派发 → 栈深度随会话时长无界增长;且 REARM_LIMIT=16 之后静默交出顶层放大问题)。修复打在根因层(把单请求遍历深度钉死为常数 + 路由权永不离开守卫),不是症状层打补丁。我独立复核了「回归测试能复现原 bug」:把新测试跑在 master 旧源码上,churn 用例精确失败于 RangeError: Maximum call stack size exceeded(与用户线上崩溃一致);换回 PR 源码全过。

② 回归审查(diff 触碰路径的既有行为清单)

既有行为 结论
#1158 第三方安装检测/采纳为下游 保持
超过 REARM_LIMIT=16 后的语义 有意变更(已披露):旧=交出顶层槽位+停止日志 → 新=持续采纳、上限只管日志。代码注释写明原因(旧语义正是本 bug 静默放大阶段)
#1410 dead-closure 自愈(send() 重锚循环) 正常路径保持;见下方发现 (a) 的一个边角例外
wire 字节/消息形状 不变。逐条核对过所有 send() 调用点:顶层派发前 URL 已定稿(改写为 /bili/… 或原样),下层链接对已定稿 URL 的再评估是幂等空转(/bili/… 因 segments[0]==="bili" 判非模型直接透传)——跳过下层 dispatch body 不丢任何线上行为
第三方包装器注入(ChatGPT 鉴权等) 保持:最新包装器仍在顶层链接之下、每请求恰好执行一次(测试 3 钉住)。已披露降级:两个同时存活的第三方包装层时旧层注入被跳过
日志量 减少(属修复的一部分):churn 形态下每请求 onUnroutedModelUrl/onDispatch 触发从 N 次降为 1 次——用户日志里刷屏的 "request sent DIRECT" 正是 N 次重复;另新增一次性重入警告
BILI_RECLAIM_FETCH_PATCH=0 逃生门 不变
并发 ALS 按异步上下文隔离深度,并发顶层请求互不可见(测试 2 钉住);残留窄向量见下方发现 (b)

③ 代码审查 ✅

  • ALS 选型正确(全局计数器会在并发下互相污染);depth≥2 回退 plain walk 保证终止逻辑自身不会成环;anchor !== ds 时走受保护的 send() 回退,合理;_resetForTest 补了 warnedReentry 复位;无 console.error 违规(本 agent 侧模块沿用 console.warn 惯例);无配置面/持久化/version 变更。
  • 发现 (a)(不阻塞,供合并前决策):重入跳转直调 anchor(input, init),绕过了 send() 里喂给 knownDeadFetches 的 dead-closure 捕获。若最老存活锚点本身是个后来被宿主弄死的第三方包装器(要求它先于 bili 模块加载 + 后续 churn,三重罕见条件),则 TypeError 上抛且无人记死 → 后续请求持续失败直到重启(旧代码会经 nextLiveAnchor 自愈)。后果是可见失败而非静默损坏或崩溃。可选加固:跳转处改为 ds = anchor 后走 run(2, () => send(input, init)),一行保留 bili-native 安装/re-arm globalThis.fetch 不校验所有权,与网络 scope 类插件交错后全局 fetch 悬空 → 全进程 "baseFetch is not a function" #1410 自愈。因为这是改动所审机制的核心选择且本 PR 本就需人工合并,我没有擅自补 commit。
  • 发现 (b)(记录在案,无需处理):长会话 churn 下链的内存仍随历史增长(每次 re-arm 留一对闭包)——修复钉的是每请求遍历成本 O(1),不是分配历史;这是「保留每个存活包装器可达」设计的固有代价,可接受。

④ 测试有效性 ✅ 三个新用例都有牙:churn 用例断言 sink 收到精确 URL(模型 URL 恰好改写一次/非模型原样一次),且我实测它在旧代码上复现崩溃;并发用例钉住双请求全量派发+顺序;稳态用例钉住外置 hook 恰好一次且看到改写后 URL。既有 10 个 #1158/#1410 用例全部原样通过。小缺口:双存活包装器降级与发现 (a) 边角无用例钉住(与 (a) 同源,若决定加固可顺手补一个)。

⑤ diff 整洁度 ✅ 2 文件 +159/-10,每一行都服务于本 PR 目的;唯一附带改动是改名行顺带修正了 master 上既有的缩进错位。无空白重排、无锁文件/生成物、version 未动。

CI:head 277d9682 除 codex accepts CODEX_HOME overlay + registers bili MCP(windows-latest)外全绿,含四条真实客户端原生 lane e2e(opencode/dsh/pi/codex vs 确定性假上游)、hermetic registry e2e、四平台单测。该失败 job 42 秒即挂(早期环境性失败),且同一 job 在 master 上也有过失败记录(25fd53df)、最近 5 次 master 提交中 4 次成功 → 判定为 flaky 的 Windows 环境 job,与本 diff 无关(未触碰 launcher/codex/MCP 任何代码)。

本地复验(rebase 后):typecheck ✅;npm test 3243 例 / 3231 pass / 0 fail / 12 skip ✅;build ✅。

合并注意:按 §7.4 不可 auto-merge——REARM_LIMIT 超限语义变更属 fallback/默认值的产品决策,且模块是所有原生 lane 共用的基础设施,需人工合并。发布说明请带上两条已披露变更(超 16 次后持续采纳而非交出顶层;新增一次性重入日志)。master 已在 v0.1.172,本修复将随 0.1.173+ 生效。

一句话总结:修复了共存插件反复包装 globalThis.fetch 导致拦截链无界增长、最终栈溢出打崩宿主进程的问题(根因:重入遍历无深度上限 + 超限后静默交出顶层),回归测试经我独立验证可在旧代码上复现原崩溃,代码与测试均通过审查,可以合并(人工合并)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 状态更新:此前唯一红的 job(codex accepts CODEX_HOME overlay + registers bili MCP,Windows)失败原因是外部瞬时故障 —— ci-windows-codex.yml:35 未钉版本安装 @openai/codex,撞上 OpenAI 刚发布 0.159.0(08:10:59 UTC)的发布窗口,tarball 暂不可用(E404)。与本 PR diff(仅 src/agent/native-intercept.ts + tests/native-intercept-selfheal.test.ts)无关;master 最新提交上同一 job 为绿。已重跑该 job → success,现在全部检查通过。详见 issue #1662 线程。

@ranxianglei
ranxianglei merged commit d27dc34 into master Sep 30, 2026
13 checks passed
@ranxianglei
ranxianglei deleted the 2026-09-29_fetch-chain-depth 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.

DSH0.1.7-rc.2中billion-context与dsh-codex-subscription的冲突?

1 participant