Skip to content

fix(launcher): attach to late-publishing instance after fast child death (#1903) - #1907

Merged
ranxianglei merged 1 commit into
masterfrom
2026-10-02_claude-hook-attach-rediscovery
Oct 2, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-10-02_claude-hook-attach-rediscovery

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What & why

CI flake (#1903, found while analyzing PR #1896): hook e2e: manual bili start on the pinned port is attached, not refused failed once on an unrelated PR head (run 36973824451 / job 110733254556), then went green on the identical head with zero code change.

Mechanism, confirmed from the failing job log: the squatter daemon's TCP socket was accepting (the harness's TCP-only waitForPort gate passed) but its identity record — proxy-origin file + registry marker, written inside the server's listening callback — had not been published yet when the hook ran its one-shot discovery. Zero candidates → spawn path → strict-port child dies on EADDRINUSE → exit 1 → misleading "bring-up failed / NOT served by a session-managed proxy". The hook stderr in the failing run contains ONLY that bring-up line — no native-attach: drop/skip diagnostics — proving the discovery snapshot was empty (identity-publication lag), not a health-probe timeout.

Two sides contributed; this PR fixes both:

1. Launcher — mechanism owner (src/launcher.ts). Production analogue: a user starts a manual daemon and opens claude within milliseconds of boot. Previously a spawned child dying before becoming healthy threw immediately. Now: that fast death proves port occupancy, so ensureProxyRunning re-runs the SAME discovery+attach pipeline (probeLiveInstances + pickAttachable — all existing compatibility / code-fingerprint / #1335 / #1660 gates apply unchanged) on a bounded budget of POST_EXIT_REDISCOVERY_MS = 3000ms at the existing 200ms health-poll cadence. If a compatible instance publishes during the window, bring-up succeeds by attaching; otherwise the original error is thrown byte-identical.

2. Test harness (tests/claude-native.test.ts). The squatter gate was TCP-connect-only — strictly weaker than what the hook's discovery consumes. Added waitForProxyVisible(): the squatter must answer /__bili/health with ok:true AND have a parseable proxy-origin record before the hook runs. All pre-existing assertions untouched.

3. Deterministic regression tests (tests/launcher.test.ts). Two deps-injected cases under an injected clock: (a) child exits code 1 before healthy, instance appears on the first retry tick → resolves attached (with the #1322 refusedWatcher flag carried through); (b) nothing republishes within the budget → original exited before becoming healthy (code 1) error, exactly 1 initial + 15 budget probes.

Behavior change (disclosure)

  • Failure path only: where a spawned child used to die before becoming healthy, error latency now includes up to 3s of re-discovery (old: immediate throw). When no compatible instance appears, the thrown error text is unchanged.
  • Newly possible success: a compatible instance whose identity record lands during that window now yields an attach instead of a spurious failure — this IS the fix (CI flake and production analogue).
  • Success paths (attach or fresh spawn) are byte-identical. No wire, config, persistence, version, or acp-kernel changes.

Config surface

Not applicable — no new/renamed/re-semantics config fields, env vars, or CLI flags. POST_EXIT_REDISCOVERY_MS is a private module constant (no env knob; the window is bounded by design and 3s covers the publication lag with wide margin).

Pre-flight

  • npm run typecheck clean (src); full-project tsc diff vs master: zero new errors (991 pre-existing test-file errors identical before/after, verified via stash)
  • node --import tsx --test tests/launcher.test.ts: 255 pass, 1 skip, 1 pre-existing env-dependent dsh failure (runLaunch dsh: non-loopback upstreams ride proxy envs… #535 phase 4) — fails identically on clean master, unrelated to this diff
  • node --import tsx --test tests/claude-native.test.ts: 42 pass, 8 skipped (live-gated), 0 fail
  • npm run build clean
  • Targeted live run of the formerly flaky test (ACP_TEST_CLAUDE_NATIVE=1 … --test-name-pattern "pinned port is attached"): PASS, 15.8s

Fixes #1903

@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-02_claude-hook-attach-rediscovery (9a0f360)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.1901-pr.1907.67c7809

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

Install instructions are refreshed on each push.

@ranxianglei
ranxianglei force-pushed the 2026-10-02_claude-hook-attach-rediscovery branch from 1d5afcf to 9a0f360 Compare October 2, 2026 07:30
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR #1907 review 结论:可合并(请人工 merge)

已按 review 规范完整过审(方向关 → 回归清点 → 代码 → 测试有效性 → diff 整洁度),并把分支 rebase 到最新 master(2aad4dc6,含 #1906 kernel pin 0.0.100)后重新验证。rebase 零冲突(本 PR 三文件与 master 变动无交集),新 head 9a0f3607 已推回分支。

结构化七问:

  1. 是什么问题:claude hook e2e 偶发失败——手动 bili start 的 squatter 守护进程 TCP 端口已可连但身份记录(proxy-origin 文件 + registry marker)尚未落盘时,hook 的一次性 attach 发现拿到空快照,误判"无人服务",strict-port 子进程撞 EADDRINUSE 死后报出误导性的 "bring-up failed"。纯竞态窗口,非逻辑 bug(CI flake: claude hook e2e "manual bili start on the pinned port is attached, not refused" — attach-vs-spawn race when the squatter's health endpoint lags TCP accept (#1322/#1660) #1903)。

  2. 什么原因导致的:ensureProxyRunning 的 attach 判定是一次性快照(src/launcher.ts:3054-3061):候选只来自身份记录、且只在 spawn 决策前取一次。子进程快速死亡(恰恰证明端口被占)后直接 throw,丢弃了"占用者正在晚发布身份"这一最有力的现场证据。根因在决策点消费陈旧证据,不在探测本身。

  3. 怎么修复的:在 childExit 分支(且在 childError 检查之后——spawn 类错误仍 fail-fast 不延迟)加有界重发现:POST_EXIT_REDISCOVERY_MS=3000ms 预算内按既有 200ms 健康轮询节律重跑同一条 probeLiveInstances+pickAttachable 管线。窗口内出现兼容实例 → attach 成功;预算耗尽 → 抛逐字节相同的原错误。配套:harness 门从"TCP 可连"升级为"health ok + 身份文件可解析"才放 hook 跑(waitForProxyVisible,路径已对照 src/paths.ts:68 核实);两个注入时钟的确定性单测钉住行为。修在决策点用新鲜证据,不是堵症状。

  4. 是否回归问题:无意外回归。触碰路径的既有行为逐项清点:一次性 attach 初探 / strict-port squatter 快速失败 / bug: cross-process startup-window race — two concurrent launches each spawn a proxy (double writers over one sessions dir) #707 starting-marker 协调 / spawn+BILI_STRICT_PORT / SPAWN_WAIT_MS 超时 throw / child 'error' 事件立即 throw(fail-fast 保留,重发现刻意跳过)——全部保持;所有 attach 门禁(claude-native hooks must not attach to a lifecycle-less proxy — attach gate + self-managed fallback #1335 watchdog、[Design] 定死端口 lane(claude 48787 / zcode 48789)端口被占时的 0 配置解法 #1660 user-zone 豁免、codeFingerprint、lane 优先级)原样复用零旁路,refusedLog Set 共享不会重复拒登日志。有意变更(已披露):仅失败路径——childExit 错误延迟从立即变为最多 +3s;新增一种成功可能(attach 替代伪失败)= 修复本身;stderr 新增两行(附加式)。成功路径逐字节不变。wire/config/persistence/version/acp-kernel 均未动。一个已知边界:若窗口内恰好有兼容的 user-zone daemon 发布身份,attach 会掩盖我们子进程的真实死因——可接受(launcher 契约就是"该端口上有可用 proxy",子进程日志仍在 logPath,且会打印 rediscovery 提示)。

  5. 是否破坏缓存:不涉及。未触碰任何缓存/游标/去重键;重发现只是对同一身份记录源的有界重读。

  6. 是否改了设计方向:没有。完全沿用既有 discovery→attach 管线与候选来源不变量("候选必须来自身份记录,不裸信任 TCP",与 launcher: spawn 等待的 pre-handshake fallback 把首选端口上的健康外来实例当成自己 spawn 的 child,客户端被 export 到错误 origin(绕过 #1225 指纹门) #1753 squatter 谨慎一致),只加了一个时间窗。

  7. 是否引入了新的配置:没有。POST_EXIT_REDISCOVERY_MS 是私有模块常量,无 env/CLI/config 面变化。

测试有效性:有牙。reads===2 钉住"首探漏、重试中第一拍命中"(去掉重发现或 t=0 即跑都会挂);reads === 1+Math.round(3000/200) 在注入时钟下钉住预算边界(循环无界或节拍错都会挂);assert.rejects 正则钉住原错误文案(文案漂移即挂);refusedWatcher===true 钉住 #1322 标记经重试路径传递;registrations deepEqual 钉住 watcher 恰好注册一次。非恒真断言,能兜底。harness 门改动对原始 flake 有直接针对性(TCP-only 门放行而身份未发布正是 flake 触发条件)。

diff 整洁度:纯新增 150 行 / 0 删除,三个文件每行都与修复目的相关,干净。

本地验证(rebased head 9a0f3607 @ master 2aad4dc6):

  • npm run typecheck:clean
  • node --import tsx --test tests/launcher.test.ts(定向):257 例 = 255 pass / 1 skip / 1 fail。唯一失败是 runLaunch dsh … (#535 phase 4)——已在干净 master 上复现同样失败,系本地环境相关的既有失败(CI 矩阵全绿),与本 PR 无关,与 PR 描述声明一致。
  • 旧 head 511ec366 的 CI 全套 success(含曾 flake 的 test (ubuntu-latest, 24));新 head 9a0f3607 CI 进行中,首批已完成项(opencode/pi/codex lane、build-artifact、version-guard)均绿,测试矩阵跑完后我再跟一条确认。

判定:方向正确、修法打在根因、无回归、测试有牙、diff 干净——建议合并(merge 操作按规范由人工执行:https://github.com/ranxianglei/billion-context/pull/1907)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 跟进确认:rebase 后的新 head 9a0f3607(base = master 2aad4dc6,含 #1906 kernel pin 0.0.100)CI 13/13 全绿——测试矩阵四格(ubuntu/windows × 22/24,含曾 flake 的 test (ubuntu-latest, 24))、hermetic registry e2e ×2、real pi/codex/opencode/dsh lane、codex CODEX_HOME overlay、build-artifact、version-guard 全部 success。

结论不变:可合并,merge 按规范由人工执行:#1907

@ranxianglei
ranxianglei merged commit ea0a37e into master Oct 2, 2026
13 checks passed
@ranxianglei
ranxianglei deleted the 2026-10-02_claude-hook-attach-rediscovery 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

1 participant