Skip to content

fix(zcode): shared-store dead-port repair — exit handoff, watchdog drift fix, attach visibility - #1624

Closed
ranxianglei wants to merge 1 commit into
masterfrom
2026-09-29_zcode-store-drift-handoff
Closed

ranxianglei wants to merge 1 commit into
masterfrom
2026-09-29_zcode-store-drift-handoff

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Fixes #1623

问题

zcode 原生模式下共享 provider store 与代理实例生命周期脱钩:每个实例自举都无条件改写 store(last-writer-wins,attach/spawn 皆然),而实例死亡时没有任何交接——MCP 子进程无退出 handler,unrouteZcode 只在失败路径调用。结果:实例死后 store 残留死端口,之后所有新读取者(新会话/新查询)路由进 ECONNREFUSED;叠加 ZCode 客户端按会话缓存 baseURL,在途会话重试也打不到新端口。两次独立复现(issue 主链 + floor 1 补充证据)。

改动(单一根因,四处落点)

  1. 退出交接(src/zcode/mcp-entry.ts):MCP 子进程安装 SIGTERM/SIGINT/beforeExit handler,退出前在配置锁下检查共享 store——仍指向自己则优先改写到存活兼容实例(复用 probeLiveInstances+pickAttachable 判定),否则移除受管改写回退直连。5 s 超时兜底,绝不阻塞退出。
  2. 漂移修复(src/zcode/native.ts repairSharedStoreDrift + mcp-entry 看门狗):每 tick(30 s)额外检查 store——指向「非自己且已死」的端口时接管修复(自己存活→改到自己;否则找存活替代;都没有→回退直连)。覆盖硬杀场景(Windows TerminateProcess 跳过 JS handler,交接跑不成)。只在 store 指向死端口时动手,绝不从存活实例抢路由(双活写者不抖动;锁内串行,收敛到任一活端口)。
  3. attach 拒绝可见性(src/launcher.ts):probeLiveInstances/pickAttachable 的所有静默拒绝分支(pid 死亡/健康探测失败/instanceId 不符/code-fingerprint/lane/host-or-passthrough/mitm-domains/model-windows/model-max-outputs 不匹配/port mismatch/gate 拒绝)现在带 reason code 写入 bili.log;新增导出 findLiveAttachableInstance(只探测、不 spawn、不注册 watcher)供 zcode 侧复用同一套判定。顺带修了 squatter 检查的 boolean coercion bug(instanceCompatible(...) === undefined)。
  4. 日志通道(src/zcode/mcp-entry.ts):mcp-entry 事件从裸 stderr 改为经 configureLogger(defaultLogFile()) tee 进共享 bili.log(stderr 同时保留),时间戳可与其他实例对齐——zcode 不捕获该子进程 stderr,裸 stderr 等于黑洞。
  5. 文档(CLIENTS.md / CLIENTS.zh-CN.md):生命周期一节补交接/漂移修复语义与客户端缓存边界(ZCode 按会话缓存 baseURL,修复只对之后的新读取生效);推荐把 BILLION_CONTEXT_PROXY 钉到常驻代理做结构性规避。

行为变更声明(old → new)

  • store 语义:"最后写入者胜(含死者)" → "最后存活写入者胜;死端口 ~90 s 内自动修复(改到存活兼容实例,否则回退直连)"。这是恢复 CLIENTS 文档既有承诺("恢复失败时移除受管改写,让流量退回直连而不是打到死端口")到全部死亡路径,不是新策略。
  • mcp-entry 日志:裸 stderr [bili-zcode] ... → 带时间戳、tee 进共享 bili.log。单行文本不变,多了时间戳前缀。
  • bili.log 新增 info 行:每次 attach 候选被丢弃/跳过/拒绝一行(reason code)。量级 = 每会话自举一次,非每请求。
  • 退出时序:MCP 子进程收到 SIGTERM/SIGINT 后最多延迟 5 s(交接超时)再退出;正常路径 <100 ms(锁 + 一次 store 读)。
  • 无 config surface 变更;无 wire/消息格式变更;不动 src/update.ts、版本字段、acp-kernel pin。

验证

  • typecheck 干净;全量测试 3119 pass / 0 fail(16 skipped = e2e 默认门控);build 成功(dist-import-annotations OK)。
  • 新增回归测试 13 个:detectCurrentZcodeOrigin 往返;漂移修复六分支(unmanaged/self/foreign-live/repointed-self/repointed-replacement/reverted-direct);退出交接三分支(not-ours/handed-off/reverted-direct);findLiveAttachableInstance 只探测不 spawn + 三类 reason code 诊断(owner process gone / code-fingerprint-mismatch / refusing to attach)。
  • 本 diff 不碰请求管线(server.ts/src/loop/adapters/stream/persist);CI e2e hot-file 列表不含 launcher.ts/src/zcode,如需 e2e-codex 请手动 dispatch。

已知边界(不在本 PR)

  • ZCode 客户端缓存(issue 第 4 层,zcode 产品行为):在途会话不重读配置,任何 store 改写都救不了它——文档已标注边界;向 z.ai 报告需 owner 批准(跨仓提交政策),本 PR 不擅自投递。
  • 硬杀无交接窗口:TerminateProcess 场景靠漂移修复兜底(~90 s 收敛),非零窗口但有限且自愈。

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-29_zcode-store-drift-handoff (007ead4)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.1564-pr.1624.b43d60a

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-pr1624.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] 🏷 收到——这是已完成的工作(带 ework-agent-pr 标记),我不重做,按 PR Review 规范走完整审查:① 对照 #1623 四层根因审方向、② 回归清点触碰路径的既有行为、③ 代码审查、④ 测试有效性、⑤ diff 整洁度,并核对 CI 状态。分支当前 behind master(mergeable_state: behind),会先 rebase 到最新 master 复跑 typecheck/test/build 再下结论。结论稍后回帖。

…ift fix, attach visibility (#1623)

A zcode native instance that dies leaves the shared provider store pointing at its dead port (last-writer-wins rewrite, no handoff); fresh readers then route into ECONNREFUSED until the next bootstrap happens to rewrite it.

- mcp-entry: SIGTERM/SIGINT/beforeExit handoff under the config lock — re-point the store at a live compatible instance, or revert to direct
- watchdog: every tick also repairs a dead store pointer left by ANY instance (covers hard kills whose JS handlers never run)
- launcher: reason-coded diagnostics for every attach drop/skip/refusal (previously silent); findLiveAttachableInstance probe-only export; fix boolean-coercion bug in the squatter check
- mcp-entry logs now tee into the shared bili.log (zcode drops stderr)
- docs: lifecycle section updated in CLIENTS.md / CLIENTS.zh-CN.md incl. the client-cache boundary (repairs help fresh reads only)

Behavior change: store semantics move from 'last writer wins (incl. dead)' to 'last LIVE writer wins; dead pointers auto-repair within ~90s'.
@ranxianglei
ranxianglei force-pushed the 2026-09-29_zcode-store-drift-handoff branch from 44a21e3 to 007ead4 Compare September 28, 2026 23:33
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review complete — mergeable (human merge; not auto-merge eligible per §7.4: shared multi-client launcher.ts path + lifecycle-semantics change + new export surface). I rebased the branch onto current master and force-pushed it (lease-guarded): 44a21e30 → 007ead44, so the PR is no longer "behind". Rebase was conflict-free (zero file overlap with the 13 new master commits).

① Direction (vs #1623) — correct, root-cause level, not symptom masking. All four verified layers of #1623 get a fix at the right decision point: death-without-handoff → exit handoff under lock; watchdog-only-watches-self → per-tick drift repair (covers hard kill); silent attach rejections → reason-coded diagnostics; client baseURL cache → documented boundary + structural workaround (pinned BILLION_CONTEXT_PROXY). Matches the triage plan in #1623 floor 4 exactly. The store-semantics change ("last writer wins incl. dead" → "last live writer wins, dead ports self-repair ≤~90 s") is disclosed old→new in the body and framed correctly: it restores the invariant CLIENTS.md already promised, doesn't invent a new policy.

② Regression inventory — existing behaviors on every touched path:

Touched behavior Verdict
Attach compatibility classification (instanceCompatible) Preserved. Return type boolean→reason-string; both call sites updated; squatter check now === undefined which is required (a reason string is truthy — naive reuse would have misclassified every incompatible same-port instance as a squatter). Verified these are the only two call sites repo-wide.
probeLiveInstances/pickAttachable selection order & outcomes Unchanged — pure additive diag logging.
ensureProxyRunning spawn/attach/wait flow for ALL clients Flow unchanged; new bili.log info lines per dropped/skipped/refused candidate (declared; bounded per bring-up).
zcode bootstrap/route/unroute/stamp functions Byte-identical (diff only adds new exports + fixes the misleading "never rewrites" comment at native.ts:30-33 that #1623 triage flagged).
Watchdog respawn logic Preserved verbatim (re-indented). One undeclared-but-benign nuance: the attached-mode "waiting for it to recover" line now fires once per 3-tick cycle instead of every tick (failures counter resets after the log branch) — less spam, no semantic change.
Store write locking (#1002 snapshot discipline) Unchanged. Note two pre-existing properties the new code inherits (not introduced): unrouteZcode is a lock-less RMW and snapshotAndWrite writes non-atomically — worst-case interleaving degrades to direct fallback, never a dead port; SIGKILL mid-write corruption window is pre-existing and negligible.
Config surface / wire format / update.ts / version / kernel pin Untouched — verified against the file list; dist-import-annotations OK.

Declared behavior changes all match what the code actually does (verified each against the diff): ≤5 s exit delay on SIGTERM/SIGINT (hard-bounded — process.exit(143/130) forced even if the handoff promise dangles; probes are 2 s-timeout, lock 5 s-timeout, so nothing hangs unbounded); timestamped tee into shared bili.log with unchanged line text + prefix. Minor disclosure gap: the beforeExit path also delays up to 5 s (same mechanism, natural-drain scenario only) — worth knowing, not a problem.

③ Code — clean throughout. Type-safe, proper test seams (probe/findReplacement/attachDiag injection), started guard makes the exit handler re-entry safe, timer .unref()'d so it can't hold the process open. Read/write symmetry of new detectCurrentZcodeOrigin verified against both store kinds' write paths (json-edit.ts:156 / :219) and WRAPPED_URL_RE (:54) — user-written or unwrapped URLs fail the regex → treated unmanaged → never touched. No import cycle from the new native.ts→launcher.js edge (launcher imports nothing from zcode/*). Fingerprint consistency holds: defaultFindReplacement passes nativeProxyScriptPath() explicitly, matching what spawned instances registered.

Known boundary (not a defect): in attach mode with BILLION_CONTEXT_PROXY pinned to a user-managed resident proxy, if that proxy dies, drift repair sees current === selfOrigin and returns "self" without probing — no auto-repair until it recovers. Consistent with pre-existing attach semantics (must never spawn; reverting would clobber the explicit pin).

④ Tests — the 13 claimed are all there and real: 9 in tests/zcode-native.test.ts (detect round-trip through actual files; all six drift outcomes incl. byte-equality assertions proving the no-op branches truly don't touch the store; all three handoff outcomes), 4 in tests/launcher.test.ts (probe-only contract pinned via a spawn-flag trap; three reason-code diagnostics). Assertions have teeth — exact outcome enums, store-content checks (includes(UPSTREAM) + doesNotMatch(/\/bili\//)), one test drives the default probeProxyHealth against a real ephemeral-port HTTP server rather than mocking it. Deterministic (injected fakes elsewhere). The original bug class (dead foreign pointer left in the shared store) has regression coverage on both repair paths.

⑤ Diff cleanliness — 8 files, single commit, every line on-purpose, no lockfile/whitespace churn. One cosmetic nit I'm leaving alone: a continuation line in CLIENTS.md gained one space of indent (2→3, zero rendering impact).

Gates: full local gate green on rebased head 007ead44 — typecheck clean, 3151 tests / 3135 pass / 0 fail (16 skipped = gated e2e; count grew vs the PR's 3119 because master added cache-seam tests since), build + dist-import-annotations OK. GitHub CI on the pre-rebase head had 8/12 runs already green (all e2e lanes: codex zero-token, hermetic registry, pi/opencode/dsh lanes, build-artifact, version-guard) with the 4 test-matrix jobs still running; the push triggers a fresh run on 007ead44.

中文摘要:修复了 zcode 共享 provider store 在实例死亡后残留死端口导致 ECONNREFUSED 的问题(退出交接 + 看门狗漂移修复 + attach 拒绝可见性),方向正确、四处落点均针对根因、回归清点无意外行为漂移,已在 PR 分支上 rebase 到最新 master 并全量验证通过,可以合并。

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