Skip to content

fix(#1753): verify responder identity in spawn-wait pre-handshake fallback - #1758

Closed
ranxianglei wants to merge 1 commit into
masterfrom
2026-09-30_spawn-fallback-pid-check
Closed

ranxianglei wants to merge 1 commit into
masterfrom
2026-09-30_spawn-fallback-pid-check

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #1753

What changed

ensureProxyRunning's spawn-wait pre-handshake fallback (src/launcher.ts) trusted any healthy HTTP response on the preferred port once the instance record went stale (stale && probeHealth(preferred) — a bare {ok} probe). When a foreign healthy instance squatted on the preferred port — exactly why our child laddered off it — the wrapper exported the client to the squatter's origin within ~200ms and orphaned our own child on its laddered port. This bypassed the #1225 code-fingerprint gate, which had just refused the same instance on the attach path.

The fallback now verifies responder identity: /__bili/health already returns the responder's pid, and the wrapper holds child.pid. The fallback only accepts the preferred origin when health.pid === child.pid. Anything else (foreign squatter, non-bili listener with no pid) keeps waiting for the child's launch-token handshake record (its real origin/port), and announces the foreign occupant once via attachDiag:

bili: preferred port N is held by a healthy foreign instance (pid X) — waiting for our child to report its real origin via the launch-token handshake (#1753)

Changes:

  • HealthInfo gains pid?: number; fetchHealthInfoDefault parses it (the server already returns pid: process.pid — no server change)
  • Fallback: stale && typeof child.pid === "number" → fetchHealthInfo(preferred) → accept only if info.pid === child.pid (then settleZonePort as before); otherwise one-time announce + keep waiting
  • New regression suite tests/fix-1753-spawn-fallback-squatter.test.ts (3 tests: squatter rejected + announced, no-pid responder rejected, our-child fast path settles immediately)
  • Existing success-path tests updated mechanically: inject fetchHealthInfo with the fake proxy child's pid. No assertions changed or weakened; rejection tests untouched.

Behavior changes (intended)

Scenario Old New
Stale record + healthy FOREIGN bili instance on preferred port Client silently exported to squatter's origin; own child orphaned on laddered port; sticky settled on squatter's port Waits up to SPAWN_WAIT_MS (20s) for launch-token handshake; exports the child's real (laddered) origin; one-time diagnostic line names the squatter's pid
Stale/broken state dir + healthy NON-BILI listener on preferred port Exported to it Rejected (no pid to match); waits for handshake; fails loudly at the deadline if the child cannot report
Our child bound the preferred port (health pid === child.pid), record present or not Immediate export + sticky settle Unchanged — immediate export + sticky settle
Launch-token handshake record present Immediate export of recorded origin Unchanged (still first priority in the loop)

Degenerate-case trade-off: broken state dir + laddered child now fails loudly at the 20s deadline instead of being silently misdirected — the old "success" there was never a success (client pointed at a process we did not spawn).

Regression audit (existing behaviors touched by the diff)

Pre-flight

  • npm run typecheck: clean
  • npm test: 3361 tests, 3342 pass, 0 fail, 19 skipped
  • npm run build: success

…lback

The fallback trusted any healthy response on the preferred port once the
instance record went stale, exporting clients to a foreign squatter
instance (e.g. an older build holding the lane zone) while our own child
laddered off to another port and was orphaned — bypassing the #1225
fingerprint gate that had just refused the same instance on the attach
path. The fallback now only accepts a /__bili/health response whose pid
equals child.pid; anything else keeps waiting for the launch-token
handshake record and announces the foreign occupant once via attachDiag.

- HealthInfo gains pid, parsed from /__bili/health (server already returns it)
- success-path tests updated mechanically to inject fetchHealthInfo with
  the fake proxy child's pid; no assertions changed
- new regression suite tests/fix-1753-spawn-fallback-squatter.test.ts pins
  squatter rejection, no-pid rejection, and the fast path
@github-actions

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-30_spawn-fallback-pid-check (c84247c)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.1710-pr.1758.9eb86d3

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-pr1758.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] 🏷 PR review — fix(#1753): verify responder identity in spawn-wait pre-handshake fallback

Reviewed head c84247c2 (branch 2026-09-30_spawn-fallback-pid-check, single commit, fresh base off current master, 0 behind). Verdict: mergeable. Details below.

① Issue direction — correct

#1753 names the right root cause: the spawn-wait pre-handshake fallback had its OWN trust channel (stale && probeHealth(preferred) — bare {ok}) that bypassed the #1225 code-fingerprint gate which had just refused the same instance on the attach path. This fix moves the decision to the trust point itself — proving who answers on the preferred port via the health endpoint's pid, matched against child.pid — rather than filtering symptoms downstream. Root cause, not symptom.

Verified the load-bearing premise: /__bili/health does return pid: process.pid on master (src/server.ts:1149-1155) — no server change needed, and none made. Notably, pid entered the health contract only in e14d7d25 (#1232, 2026-09-24) — six days before the incident — so the v0.1.172 squatter from the field repro answered health without a pid. The fix handles exactly that: info.pid === child.pid is false when pid is absent → reject and wait for the handshake. Both squatter shapes (foreign build with pid, ancient build without) are covered.

② Regression audit — existing behaviors touched by the diff

Existing behavior Verdict
Attach path (probeLiveInstances / pickAttachable, #1225 fingerprint gate, #1330/#1335 watchdog gate) Untouched (diff scope verified file-wide)
Launch-token handshake branch of the spawn-wait loop Untouched, still first priority in the loop
strictPort fail-fast (#964/#1232), #707 starting-marker coordination, spawn-error / child-exit rejection paths Untouched — rejection tests pass unmodified
settleZonePort semantics Unchanged; now reachable only for identity-verified origins
Wire/compression paths (both modes) Not touched (launcher-only)
Deadline failure after the loop Unchanged — still throws proxy did not become healthy within ${SPAWN_WAIT_MS}ms; the degenerate case (broken state dir + laddered child) now lands here instead of being silently misdirected, as disclosed in the PR body

One edge I checked beyond the PR's list: the old fallback comment covered "an old pre-handshake binary". Under the new code such a child (health without a usable pid) times out instead of being accepted. That's safe: the wrapper spawns the same script build it runs (process.argv[1] / deps.scriptPath), so any wrapper new enough to execute this code spawns a child whose health carries pid; the only divergence (deps.scriptPath pointing at an older dist) failing loudly at the deadline is the correct outcome — identity can't be proven there anyway.

Behavior changes match the disclosure table in the PR body (foreign squatter → wait ≤20s + export child's real laddered origin + one-time diag naming the squatter pid; non-bili listener → rejected; our-child fast path → unchanged immediate settle; handshake record → still first priority). Old→new stated with rationale; no silent drift.

③ Code — clean

Minimal, follows the file's existing injection pattern (deps.fetchHealthInfo ?? fetchHealthInfoDefault, attachDiag defaulting to tee-log info — same seams the attach path uses). info?.ok guards the undefined probe result; squatterAnnounced makes the diagnostic exactly-once; requiring typeof child.pid === "number" is safe (spawn assigns pid synchronously; a failed spawn surfaces via the error event and breaks the loop first). No console.error, no config surface touched, no version bump.

④ Test effectiveness — real teeth, verified by bite-check

  • New suite tests/fix-1753-spawn-fallback-squatter.test.ts: test 1 replays the incident sequence exactly (dead-pid stale record lingers, foreign pid answers health on the preferred port, child's launchToken record arrives ~5 ticks later) and asserts the exported origin is the child's laddered port plus exactly-one announce naming the squatter pid. Test 2 covers the no-pid responder (announced as "unknown"). Test 3 pins the own-child fast path (settles tick 1, sticky settles ["pi", 18787]).
  • Bite-check (local): ran the new suite against origin/master's launcher.ts — tests 1 and 2 FAIL on the unfixed code (squatter trusted, exactly the bug), test 3 passes (fast path pre-existed). All 3 pass on the PR head. These are genuine regressions, not tautologies.
  • Existing-test changes are mechanical dep-injection only (fetchHealthInfo: async () => ({ ok: true, pid: <fake-child-pid> })) so the old success paths keep exercising the fallback under the new identity gate. I went through every hunk: no assertion changed or weakened; rejection tests untouched.

⑤ Diff cleanliness — good

5 files, every line related to the fix; no whitespace churn, no generated/lock-file churn, no unrelated files.

Pre-flight & CI

Local (on PR head): npm run typecheck clean; new suite 3/3; modified suites (launcher.test.ts, fix-1292-windows-claude-settings.test.ts, pi-native.test.ts) 255 tests / 254 pass / 0 fail / 1 skip. CI on head c84247c2: all green — full test matrix (ubuntu+windows × node 22/24), hermetic registry e2e, build-artifact, version-guard, and the real-client zero-token lanes (pi package-native, codex CODEX_HOME overlay, dsh headless, real codex, opencode native). No local full-suite re-run needed given the green matrix.


中文摘要:修复了 spawn-wait 预握手回退把首选端口上任意健康响应都当成自己子进程、导致客户端被静默导出到占用端口的陌生实例(#1753)的问题——现在用 /__bili/health 返回的 pid 与 child.pid 比对来验证响应者身份,陌生人(含无 pid 的老版本)一律拒绝并等待子进程上报真实端口;已本地验证回归测试在旧代码上确实失败、CI 全绿,可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

Closing as superseded: merged PR #1756 landed the same root-cause fix for #1753's defect 1 (spawn-wait fallback must verify pid identity before exporting the preferred port, ecb9571 — identical mechanism: HealthInfo.pid, accept only when health.pid === child.pid, one-time announce, keep waiting for the launch-token record), plus defect 2 (stopProxyGuarded, 84a1459). This PR's remaining delta vs master is only divergent rewrites of the same regions (different announce wording, separate regression file vs in-file tests) — no unique behavior to preserve. Per duplicate policy: identical root cause + identical fix approach, the merged side also carries the extra shutdown-side fix and host+VM live verification.

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