Repository navigation
[PR] fix: detect and self-heal stale MCP session bindings (#4661) - #4691
ranxianglei wants to merge 17 commits into
Conversation
ZCode pins a static BILI_CONVERSATION_ID into its MCP shim; the pin goes stale on every new host session / restart and every tool then answers from the frozen old ledger with zero diagnostics (all-zero CONTEXT BREAKDOWN while the real session is healthy). Complements #4168's witness-conflict self-rebind with its missing half: the NO-witness shape, which never 409s. - Session.lastModelRequestAt (in-memory only): stamped by the request pipeline only, so it stays honest evidence of live model traffic - handlePluginTool: bound session quiet >15 min while another non-restored session has strictly newer traffic -> warning prefix on the result + additive staleBinding field naming the live candidate + rate-limited warn log; #4168's witness-conflict 409 unchanged - handlePluginStatus: same additive staleBinding field for direct-bound polls - mcp.ts shim: startup warning for static pins; adopts the proxy-named candidate on proxy-proven staleness (retries once when the answered call ran on the old session); #4168's 409 adoption now armed for static pins too - opt-out: BILI_MCP_NO_STALE_ADOPT=1 (mirrors BILI_MCP_NO_ORPHAN_ADOPT) Tests: tests/issue4661-stale-binding.test.ts (13 rows incl. the negative cases required by #3617); adjacent tool-ring / mcp-native-thread suites green.
…O_STALE_ADOPT - CLIENTS.md zcode section: session binding & stale pins bullet (pin mechanics, symptom signature, evidence-based auto-detection/recovery, manual rebind recipe, opt-out) - LIFECYCLE.md env table: BILI_MCP_NO_STALE_ADOPT row - env-only.yaml seed entry + regenerated CONFIGURATION.md / CONFIGURATION.zh-CN.md tables
📦 Built Package ArtifactBranch: Latest build — install this exact versionnpm install -g billion-context@0.0.10294-pr.4691.38b07fdThis exact version is immutable and reproducible. The rolling Recent builds (commit → version)
Download artifact
tar xzf billion-context-pr4691.tgz
npm install -g packageInstall instructions are refreshed on each push. |
(ai: opencode/qwen3.8-27b) 查重:不重复。本 PR 是 #4661(ZCode MCP 静态 pin 失步后工具调用静默答自冻结旧会话)的修复,与 #4168(witness-conflict 409 self-rebind)是同机制家族的互补面——#4168 管「有 witness 冲突」的 stale 形状,本 PR 管「无 witness、永不 409」的 no-witness 形状;两者症状同源但触发路径不同,PR 描述里已明确互补关系,不构成重复立项。检索 open+closed issue/PR 未发现同失败签名(MCP tool 答自冻结 ledger + all-zero breakdown)的其他条目。 开始按 PR Review 规范独立审查(原 issue 方向 → 回归清点 → 代码 → 测试有效性 → diff 整洁度),结论稍后按八问体例给出。 |
…4661) CI auto-fix lane for PR #4691 head cdd8731: the gate flags the PR's new type as INTERNAL_ONLY — it is referenced only inside src/plugin.ts (staleBindingDiagnosis() return type + the tool-route binding site), so drop the leading export. Type-only change, zero runtime impact. Local: gate clean (6 waived), typecheck clean, tests/issue4661-stale-binding.test.ts 13/13.
tests/issue4661-stale-binding.test.ts spawns real MCP shim children over stdio, so the #1248 SPAWN_RE tripwire in scripts/run-ci-tests.mjs aborts every shard at pretest until it is registered. Appended (not inserted — slot = index drives each file's zone port band); its mock proxy is listen(0), so no zone band is needed — the entry is for the tripwire.
Two pre-existing lines under 'Plugin-mode stamping' were re-indented from the file-wide 2-space continuation style to 3 spaces; renders identically but needlessly churns the diff.
(ai: opencode/qwen3.8-27b) Review update — found and fixed the CI blocker in-branch; final verdict follows the re-run. Why all 11 test shards were red (not inherited master reds): the new No test actually ran on head
Code review status: full independent pass done (stamp site, candidate invariant, #4168 byte-stability, #2024/#760 authority, shim retry bounds, all 13 test rows, docs/env-var surface). Local targeted verification green: the 5 adjacent suites incl. the new file = 76/76, typecheck clean. Expectation for the re-run: static gates green; residual test-shard failures, if any, should be exactly the known master born-red set tracked in #4599 (storage lane 7 + plugin-fork flake) — I'll verify shard-by-shard before issuing the structured verdict. |
(ai: vllm-qwen/qwen3.8-27b) 查重: 不重复 —— 本条是该 PR 自身的 CI 自动修复车道(attempt 1/2)。两处红均为 PR 自带的门禁缺陷,与既有 issue/PR 无关;残余测试红属 master born-red 名册,已在 #4599 留结论评论,未另开条目。 修复(最终 head
验证:CI 上 unused-exports 转绿、静态门全绿、测试分片真实执行;本地 typecheck、门禁双向复现脚本、 八问
判定:PR 专属的两处 CI 缺陷已闭环,本分支无需再动;残余红全部是 master 自带 born-red 名册,master 收敛后(#4599 存储车道裁决落地 + #4652 合并)预期转绿。 |
…conflict # Conflicts: # CLIENTS.md # CONFIGURATION.md # CONFIGURATION.zh-CN.md # LIFECYCLE.md # scripts/live-files.mjs # src/mcp.ts # src/plugin.ts # src/server/handle.ts
…t async Merging master into the #4691 branch brought in 8ba5c03 (#4942), which turned handlePluginStatus from a sync void function into an async Promise<void>. The #4661 status-route test called it without await and asserted on the mock response synchronously — the response is now written on a later tick, so the assertion saw status 0. Await the three call sites (the it() callbacks were already async). No production code change.
[bot] 🏷 (ai: vllm-qwen/qwen3.8-27b) Merge-conflict resolution done — branch pushed, CI will judge the new head. The PR branch
One merge-induced test break, fixed as a separate labeled commit (4dd44f9): master's #4942 (8ba5c03) turned Verification: 八问(中文结论)
判定:冲突已清零、基线已对齐,可合并性待 CI 在新 head(4dd44f9d70)上确认;CI 红则先查 #4599 的 master 继承红清单。 |
…conflict # Conflicts: # website/config-reference/env-only.yaml
[bot] 🏷 (ai: vllm-qwen/qwen3.8-27b) Second conflict sweep done — branch re-synced with the newest master and pushed. The blocker trigger arrived after my first merge; live check this run: master had moved on again (259cd87 → a007974, +53 commits, mostly the ja-translation parity pass over
Everything else auto-merged clean and I verified the PR content stayed intact: Verification on the new head: CI state: verified live against the mirror cache — it still shows the PREVIOUS head (4dd44f9, fetched 12:44 UTC) with no check entries yet; the poller refreshes ~60s, so the new head's checks are not readable yet and I am not asserting green/red. Full-suite verdict is the remote CI on 59e0053; if a shard goes red, #4599's master born-red roster (storage lane 7, plugin-fork #4652) is the first thing to check. 八问(中文结论)
判定:冲突已清零(对 a007974 基线),新 head 59e0053 已推送;CI 尚未出结果(镜像缓存还停在旧 head),可合并性待 CI 确认。 |
[ework] CI fix verified green ✓ |
The floor-19 merge added desc_ja to the BILI_MCP_NO_STALE_ADOPT seed entry in website/config-reference/env-only.yaml but did not regenerate the Japanese config doc, so the docs-sync gate (gen-config-docs generate + git diff --exit-code) failed and cascaded a skip to every test/static-gates leg. Applying the generator's own output closes the gap; EN/ZH docs and the seed already carried the row.
The PR's new process-global warnedStaleBindings Set was not cleared by the test-state reset, unlike its sibling warnedNoModelRequests. Tests use random conversation ids so this is latent, but the reset should clear every warn-Set it manages for isolation consistency.
(ai: vllm-qwen/qwen3.8-27b) CI engineer run (attempt 1/3) — outcome: no merge conflict exists (stale trigger); the real blocker was a red 1. The "merge conflict" trigger was stale — there is no conflict.
2. The real blocker was a red CI job —
Fix (committed + pushed):
3. CI status — I am NOT asserting green.
八问:
Conclusion: no merge conflict existed (stale trigger); the red CI was a PR-specific docs-sync gap, now fixed in-branch and pushed (head |
ranxianglei
left a comment
There was a problem hiding this comment.
Note: posted as a COMMENT review because GitHub forbids approving one's own PR. Verdict below is APPROVE.
(ai: vllm-qwen/qwen3.8-27b)
APPROVE — clean, correct, well-tested. No blocking issues, no kernel/ or pi-subagents/ touch (no authorization gate).
What I verified (independently of the issue text):
- Diagnosis (
src/plugin.ts:379staleBindingDiagnosis): bound session quiet >STALE_BINDING_QUIET_MS(15 min) while another non-restored session has strictly newerlastModelRequestAt→ suspected stale. Never-seen sessions measure quiet fromSTALE_BINDING_PROCESS_START_MS(evidence floor, not epoch); restored sessions never candidates; most-recent candidate picked. - Stamp placement (
src/server/handle.ts:1738):session.lastModelRequestAt = Date.now()sits in the model-request path (handleRequest) only — tool calls (handlePluginTool) and disk reloads don't reach it. In-memory only (type decl atsrc/session.ts:760; absent frombuildRecord/persistence). - #4168 409 byte-for-byte unchanged: only a comment added; the
forkReply(res, 409, …)body is untouched. The no-witness stale shape is diagnosed on the success path and never reaches the 409 branch. - Success path additive (
src/plugin.ts:2573–2590):⚠️ STALE BINDING SUSPECTEDprefix +staleBindingbody field (absent when fresh).staleis declared at function level (line 2291) so it is in scope at the success path — no scope bug. - Shim self-heal (
src/mcp.ts): adopts the proxy-named candidate (preferscandidateConversationIdovercandidateSessionId), retries once (if (attempt === 0) continue).resolveForkConversationresolves both session ids and conversation ids, so the candidate fallback is safe. Per-call routes (conversationIdOverride/nativeCaller) never consume the adoption (#760/#2024 preserved); #4168 409 adoption extended to static pins (STATIC_PIN && STALE_ADOPT). - Tests (
tests/issue4661-stale-binding.test.ts, 13 rows): 8 proxy rows (2 positive + 6 negative per #3617) + 5 shim rows driving the REALsrc/mcp.tsover stdio. Assertions have teeth (exact status codes, body fields, execution targets, retry counts, stderr logs). Ran the file locally: 13/13 pass. - Config surface: new env
BILI_MCP_NO_STALE_ADOPT(per-process spawn channel, mirrorsBILI_MCP_NO_ORPHAN_ADOPT); documented in docs/configuration.md en+zh, docs/lifecycle.md, docs/clients.md (zcode), website/config-reference/env-only.yaml (en/zh/ja).
已顺手修:_resetPluginStateForTest 补上 warnedStaleBindings.clear()(PR 新增的进程级 warn-Set 未随兄弟 warnedNoModelRequests 一起重置;测试用随机 id 故为潜伏项,但重置应覆盖它管理的每个 warn-Set)+ commit 00d61c5
八问
- 是什么问题:ZCode 宿主把静态 session id 钉进 MCP shim(
BILI_CONVERSATION_ID配置钉);宿主开新会话或重启后,所有 MCP 工具都从冻结的旧账本静默回答(全零 breakdown、idle nudge),而真实会话健康——零诊断。 - 什么原因导致的:静态绑定缺少运行时流量证据来检测失步。shim 钉的 id 在宿主开新会话/重启后失效,但 proxy 没有任何机制检测"所绑会话已静默而另一会话在活跃"。
- 影响范围与严重程度:影响 ZCode 用户(静态绑定 MCP shim 的宿主)。严重度:能用但体验毁灭——所有 MCP 工具从冻结旧账本回答,用户看到全零 breakdown 与 idle nudge,真实会话健康,且无从诊断。
- 怎么修复的:三层——(1) proxy 用运行时流量证据(
session.lastModelRequestAt,仅请求管道盖章)检测失步;(2) 工具路由:疑似失步仍按原样执行但大声(⚠️ 前缀 + 加性staleBinding字段 + 限流 warn 日志),#4168 409 字节级不变;(3) shim 自愈:采纳 proxy 命名候选、重试一次、静态钉启动 stderr 警告、#4168 409 采纳扩展到静态钉。 - 是否有回归问题:逐项审过既有行为——(a) #4168 409 路径字节级不变(仅加注释);(b) 成功路径加性(新前缀+新字段);(c) 状态路由加性;(d)
lastModelRequestAt仅内存、不持久化;(e) 每次调用路由不写回全局绑定(#760/#2024 保留);(f) nativeCaller 不被诊断(#2024 保留)。无回归。 - 是否破坏缓存:不涉及(不触碰缓存/重试/增量游标/去重键)。
- 是否改了设计方向:不涉及(#4168 的补充,不改架构/边界/数据流)。
- 是否引入了新的配置:是。新 env
BILI_MCP_NO_STALE_ADOPT(=1 禁用 shim 自动重绑;默认采纳)。类别:每进程 spawn 通道(镜像BILI_MCP_NO_ORPHAN_ADOPT先例)。已文档化(en+zh+ja)。
判定:APPROVE。 无阻断项;一处测试隔离小修已就地修掉(commit 00d61c5)。
[bot] 🏷 Reviewed PR #4691 (stale MCP session bindings, #4661): verdict APPROVE — posted as a COMMENT review since GitHub forbids approving one's own PR (verdict is in the review body). Independently verified the diagnosis logic, stamp placement ( |
[ework] auto-fix stalled: test (windows-latest, 22, 4), test (ubuntu-latest, 24, 1), test (windows-latest, 22, 2), test (windows-latest, 22, 3), test (ubuntu-latest, 22, 1) — stopping for human review |
…4661) The 5 red test shards were inherited from the stale base a007974 (~432 commits behind master), not caused by this PR: - visibleNotices x2 -> #6547 (8a082c2): BILI_STORAGE_UNIFIED=legacy baseline pin conflicts with sqlite-default announcement visibility - Windows EBUSY x3 -> 7c152dc: closeQuietly sidecar before rmrf teardown Master carries both fixes; merging brings them in. Single conflict in scripts/live-files.mjs resolved by union (kept the #4661 test entry plus master's web-logs-query + content-encoding-zstd entries). Verified locally: typecheck clean; notice-registry 5/5 (was red); issue4661-stale-binding 13/13.
(ai: vllm-qwen/qwen3.8-27b) Inherited red CI — cleared by merging master. The "merge state: dirty" trigger was stale — the live state was
Fix: merged Verified locally: typecheck clean; Current CI: new run in progress — 6 success / 0 failed / 10 running; 八问
收工判定:fix 已推送( |
ranxianglei
left a comment
There was a problem hiding this comment.
(ai: vllm-qwen/qwen3.8-27b)
Note: posted as a COMMENT review because GitHub forbids approving one's own PR. Verdict below is APPROVE.
Re-review of new head b773d1a54 — the only new commit since my last review (00d61c5a) is a merge of origin/master (e0d63bf8c8) to clear inherited red CI on a stale base. I verified the merge is clean and the PR's stale-binding fix is byte-identical to what I previously approved:
- No conflict resolution altered the PR logic. Across all 8 overlap files (touched by both master and the PR —
src/plugin.ts,src/server/handle.ts,src/session.ts,src/mcp.ts,scripts/live-files.mjs,website/config-reference/env-only.yaml,docs/configuration{,.zh-CN,.ja}.md), the diff00d61c5a → b773d1a54shows zero stale-binding-related line changes — only line-number shifts from master's unrelated additions. - Test file byte-identical (
tests/issue4661-stale-binding.test.ts, 452 lines, 0 diff). - All PR symbols intact at the new head:
staleBindingDiagnosis,STALE_BINDING_QUIET_MS,warnedStaleBindings,lastModelRequestAtstamp (src/server/handle.ts:1775), type decl (src/session.ts:764), shim adoption (src/mcp.ts:222/263), and my prior fixwarnedStaleBindings.clear()(src/plugin.ts:5497) all survived the merge. - No semantic conflict: master did not change any function the PR's logic depends on (
listSessions,resolveForkConversation, therestoredfield) —staleBindingDiagnosisstill readss.restored/listSessions()correctly.
The PR's content (diagnosis, loud-flag, shim self-heal, #4168 409 byte-stability, config surface) is unchanged from my prior review, which verified all of it end-to-end (13/13 tests pass locally). No kernel/ or pi-subagents/ touch → no authorization gate.
CI at this head: 0 failed, 8 test shards still in progress (mirror cache; the static-gates / mysql-contract / gate lanes already green).
已顺手修:无新增小修——本次仅 master 合并,PR 自身代码零改动,无新发现。
八问
- 是什么问题:ZCode 宿主把静态 session id 钉进 MCP shim(
BILI_CONVERSATION_ID配置钉);宿主开新会话或重启后,所有 MCP 工具都从冻结的旧账本静默回答(全零 breakdown、idle nudge),而真实会话健康——零诊断。 - 什么原因导致的:静态绑定缺少运行时流量证据来检测失步。shim 钉的 id 在宿主开新会话/重启后失效,但 proxy 没有任何机制检测"所绑会话已静默而另一会话在活跃"。
- 影响范围与严重程度:影响 ZCode 用户(静态绑定 MCP shim 的宿主)。严重度:能用但体验毁灭——所有 MCP 工具从冻结旧账本回答,用户看到全零 breakdown 与 idle nudge,真实会话健康,且无从诊断。
- 怎么修复的:三层——(1) proxy 用运行时流量证据(
session.lastModelRequestAt,仅请求管道盖章)检测失步;(2) 工具路由:疑似失步仍按原样执行但大声(⚠️ 前缀 + 加性staleBinding字段 + 限流 warn 日志),#4168 409 字节级不变;(3) shim 自愈:采纳 proxy 命名候选、重试一次、静态钉启动 stderr 警告、#4168 409 采纳扩展到静态钉。 - 是否有回归问题:逐项审过既有行为——(a) #4168 409 路径字节级不变(仅加注释);(b) 成功路径加性(新前缀+新字段);(c) 状态路由加性;(d)
lastModelRequestAt仅内存、不持久化;(e) 每次调用路由不写回全局绑定(#760/#2024 保留);(f) nativeCaller 不被诊断(#2024 保留)。本次 master 合并未触碰任何 PR 逻辑行(零改动),无新增回归。 - 是否破坏缓存:不涉及(不触碰缓存/重试/增量游标/去重键)。
- 是否改了设计方向:不涉及(#4168 的补充,不改架构/边界/数据流)。
- 是否引入了新的配置:是。新 env
BILI_MCP_NO_STALE_ADOPT(=1 禁用 shim 自动重绑;默认采纳)。类别:每进程 spawn 通道(镜像BILI_MCP_NO_ORPHAN_ADOPT先例)。已文档化(en+zh+ja)。
判定:APPROVE。 本次仅 master 合并(清继承红 CI),PR 自身代码零改动、逻辑与我上轮 APPROVE 时字节级一致,无新发现、无阻断项。
[bot] 🏷 Re-reviewed PR #4691 at new head b773d1a (the only new commit since my last review is a master merge to clear inherited red CI on a stale base): verdict APPROVE — posted as a COMMENT review since GitHub forbids approving one's own PR (verdict in body). Verified the merge is clean: zero stale-binding line changes across all 8 overlap files, test file byte-identical (452 lines), all PR symbols + my prior fix ( |
[ework] CI fix verified green ✓ |
Closes #4661. Complements #4168 (witness-conflict self-rebind) with its missing half: the no-witness stale shape, which never 409s and silently answers from the frozen old ledger.
Problem
ZCode injects no session id into its MCP child; the shim binds to the static
BILI_CONVERSATION_IDpin in~/.zcode/cli/config.json. The pin goes stale on every new host session / host restart, and every MCP tool then answers from the frozen old session — all-zeroCONTEXT BREAKDOWN,Nudge: idle— while the real session's ledger stays healthy inGET /__bili/sessions. Zero diagnostics anywhere made it look like a proxy fault or protocol incompatibility.Fix (evidence-based, no guessing)
The proxy proves staleness with runtime traffic evidence instead of recency guesses: a new in-memory-only
Session.lastModelRequestAtis stamped by the request pipeline only (tool calls and disk reloads cannot refresh it), so "bound session quiet >15 min while another non-restored session has strictly newer model traffic" is honest evidence of a stale pin.⚠️ STALE BINDING SUSPECTED (#4661)prefix naming the live candidate + an additivestaleBindingbody field + one rate-limited warn log. [Bug] Claude Code native compaction: compress/acp_status permanently broken after resumption — outbound tool witness doe | [Bug] Claude Code 原生 compaction 续接后 compress/acp_status 永久失效:outbound tool witness does not match conversationId,ref 空间为空 #4168's witness-conflict 409 is byte-for-byte unchanged.GET /__bili/plugin/statuscarries the same additive field for direct-bound polls (absent when fresh or when resolved viafallback=latest).conversation_id,_meta.threadId) never write back to the global binding — feat: per-call conversation_id for MCP tools — let the model supply its session id #760/Codex Code Mode 压缩失败:MCP shim 忽略每次调用的 _meta.threadId,错误使用过期 env ID #2024 authority preserved.Behavior changes (old → new)
staleBindingfield + warn logstaleBindingfieldFresh bindings, nativeCaller authority (#2024), fail-closed semantics, and
lastModelRequestAtnon-persistence are unchanged. After a proxy restart, no diagnosis fires until both sessions have in-process evidence (safe default).Config surface
New env var
BILI_MCP_NO_STALE_ADOPT(=1disables the shim auto-rebind):BILI_MCP_NO_ORPHAN_ADOPTprecedent it mirrors. No config-file key added.Tests
tests/issue4661-stale-binding.test.ts— 13 rows: in-process proxy rows (diagnosis positive + six negative rows per Test Blind Spot Retrospective: Reinforcing Negative Assertion Discipline, Tightening Fake Upstream Strictness, Thin Inst | 测试盲区复盘:补反向断言纪律、假上游严格化、薄安装冒烟、形态矩阵与生命周期覆盖 #3617: fresh binding keeps the 409, multi-witness refuses, nativeCaller unchanged, lonely bound session stays quiet, restored sessions never candidates, status-route absent-when-fresh/fallback) and spawned real-shim rows over stdio (adoption + retry, no double-retry, opt-out honored, identity-binding path,_meta-bound negative).Local: typecheck clean, build clean, targeted suites green.