From e98be94a72089c5991645bb49908bc6fecd374ca Mon Sep 17 00:00:00 2001 From: anuzzolilli-oss Date: Sat, 14 Nov 2026 10:29:02 -0500 Subject: [PATCH 1/2] fix: zcode exit handoff covers a route written by an in-flight watchdog replacement A watchdog replacement tick writes the new route, awaits plugin activation, and only then updates state.origin. A signal in that interval ran the exit handoff with the old origin, got "not-ours", and exited leaving the store pointed at the replacement. A tick still blocked in ensure could also write its route after the handoff had finished. The tick now records the origin it is routing to before it writes, and the exit handoff tries that origin when the adopted one is not the store's owner. Starting the handoff marks the watchdog stopped, and a tick that finds itself stopped after ensure no longer re-routes. The signal path still does not wait for the tick; exit codes 130/143 and the 5000 ms deadline are unchanged. Refs #14 Assisted-by: Cindy (https://cindy.app) --- src/zcode/mcp-entry.ts | 27 +++++++++++---- tests/zcode-mcp-eof.test.ts | 65 ++++++++++++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 7 deletions(-) diff --git a/src/zcode/mcp-entry.ts b/src/zcode/mcp-entry.ts index aca638b8d1..742965f9fd 100644 --- a/src/zcode/mcp-entry.ts +++ b/src/zcode/mcp-entry.ts @@ -52,6 +52,9 @@ export interface MutableZcodeWatchdogState extends ZcodeWatchdogState { origin: string; failures: number; stopped?: boolean; + /** Origin a replacement tick has started routing the store to but has not + * adopted as `origin` yet; the exit handoff owns that route too (#14). */ + routing?: string; } function buildEnsureOpts(): Parameters[0] { @@ -94,7 +97,12 @@ export async function zcodeWatchdogTick(state: MutableZcodeWatchdogState, extern } else { const ensure = deps.ensure ?? defaultEnsure; const { origin } = await ensure(buildEnsureOpts()); - if (origin !== state.origin) { + if (origin === state.origin) { + log(`proxy ${origin} recovered without a re-route`); + } else if (state.stopped) { + log(`proxy respawned at ${origin} during shutdown — routing left to the exit handoff`); + } else { + state.routing = origin; process.env.BILI_MCP_PROXY = origin; const route = deps.route ?? routeZcodeConfig; const routed = await route({ origin, log, policy: state.policy }); @@ -102,9 +110,8 @@ export async function zcodeWatchdogTick(state: MutableZcodeWatchdogState, extern const activate = deps.activate ?? activateZcodePluginMode; await activate(routed, { log }); state.origin = origin; + state.routing = undefined; log(`proxy respawned at ${origin} — config re-routed`); - } else { - log(`proxy ${origin} recovered without a re-route`); } state.failures = 0; } @@ -129,16 +136,24 @@ export function startWatchdog( return async () => { state.stopped = true; clearInterval(timer); await pending; }; } -export function installExitHandoff(state: { origin: string }, log: (msg: string) => void, deps: { +export function installExitHandoff(state: { origin: string; routing?: string; stopped?: boolean }, log: (msg: string) => void, deps: { events?: { once(event: string, listener: () => void): unknown }; - handoff?: () => Promise; + handoff?: (ownOrigin: string) => Promise; exit?: (code: number) => void; timeoutMs?: number; } = {}): () => Promise { let pending: Promise | undefined; const finish = () => pending ??= (async () => { + state.stopped = true; try { - await (deps.handoff ? deps.handoff() : handoffZcodeRoutingOnExit({ ownOrigin: state.origin, log })); + const tried = new Set(); + for (;;) { + const ownOrigin = [state.origin, state.routing].find((o): o is string => o !== undefined && !tried.has(o)); + if (ownOrigin === undefined) break; + tried.add(ownOrigin); + const outcome = await (deps.handoff ? deps.handoff(ownOrigin) : handoffZcodeRoutingOnExit({ ownOrigin, log })); + if (outcome !== "not-ours") break; + } } catch (err) { log(`exit handoff failed: ${err instanceof Error ? err.message : String(err)}`); } finally { diff --git a/tests/zcode-mcp-eof.test.ts b/tests/zcode-mcp-eof.test.ts index 54851b9eb2..d60c6601af 100644 --- a/tests/zcode-mcp-eof.test.ts +++ b/tests/zcode-mcp-eof.test.ts @@ -2,7 +2,12 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { EventEmitter } from "node:events"; import * as entry from "../src/zcode/mcp-entry.ts"; -import { defaultZcodeRoutePolicy } from "../src/zcode/json-edit.ts"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { defaultZcodeRoutePolicy, detectCurrentZcodeOrigin, zcodeStoreCandidates } from "../src/zcode/json-edit.ts"; +import { handoffZcodeRoutingOnExit, routeZcodeConfig } from "../src/zcode/native.ts"; +import { rmrf } from "./tmp-rm.ts"; function deferred() { let resolve!: () => void; @@ -106,6 +111,64 @@ for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]] as const) { }); } +const OLD = "http://127.0.0.1:18787"; +const NEW = "http://127.0.0.1:28787"; + +function routedStore(): string { + const dir = mkdtempSync(path.join(tmpdir(), "zcode-eof-")); + mkdirSync(path.join(dir, "v2"), { recursive: true }); + writeFileSync( + zcodeStoreCandidates(dir, "legacy", {})[0], + JSON.stringify({ provider: { "builtin:bigmodel-coding-plan": { options: { baseURL: "https://open.bigmodel.cn/api/anthropic" } } } }) + "\n", + ); + return dir; +} + +for (const blockedAt of ["activate", "ensure"] as const) { + test(`signal during a watchdog replacement hands off the route the replacement wrote (blocked in ${blockedAt})`, { timeout: 5000 }, async () => { + const dir = routedStore(); + const blocked = deferred(); + const entered = deferred(); + const exited = deferred(); + const emitter = new EventEmitter(); + const exits: number[] = []; + let routes = 0; + const state = { origin: OLD, failures: 2, policy: defaultZcodeRoutePolicy() }; + await routeZcodeConfig({ origin: OLD, dataDir: dir, log: () => {} }); + const stop = entry.startWatchdog(state, false, () => {}, { + intervalMs: 1, + probe: async () => false, + ensure: async () => { + if (blockedAt === "ensure") { entered.resolve(); await blocked.promise; } + return { origin: NEW }; + }, + route: async (opts) => { routes++; return routeZcodeConfig({ ...opts, dataDir: dir, log: () => {} }); }, + activate: async () => { + if (blockedAt === "activate") { entered.resolve(); await blocked.promise; } + }, + repair: async () => {}, + }); + entry.installExitHandoff(state, () => {}, { + events: emitter, + handoff: (ownOrigin) => handoffZcodeRoutingOnExit({ ownOrigin, dataDir: dir, log: () => {}, findReplacement: async () => undefined }), + exit: (code) => { exits.push(code); exited.resolve(); }, + }); + const hold = setTimeout(() => {}, 5000); + try { + await entered.promise; + assert.equal(detectCurrentZcodeOrigin(dir), blockedAt === "activate" ? NEW : OLD); + emitter.emit("SIGTERM"); + await exited.promise; + assert.deepEqual(exits, [143]); + assert.equal(detectCurrentZcodeOrigin(dir), undefined); + blocked.resolve(); + await stop(); + assert.equal(detectCurrentZcodeOrigin(dir), undefined); + assert.equal(routes, blockedAt === "activate" ? 1 : 0); + } finally { clearTimeout(hold); blocked.resolve(); await stop(); rmrf(dir); } + }); +} + test("signal deadline forces the original code while overlapping handoff runs once", async () => { const work = deferred(); const emitter = new EventEmitter(); From 250dc9e43ff6a9e0d72ea572ff20f5e59fd6443c Mon Sep 17 00:00:00 2001 From: anuzzolilli-oss Date: Sat, 14 Nov 2026 10:43:20 -0500 Subject: [PATCH 2/2] test: isolate the signal-handoff tests and cover both sides of the fallback Review of #64: the real-store tests now pass an isolated env to every routing, handoff and read call, so an ambient personal-store override cannot redirect them. Two new cases pin the fallback to the in-flight routing origin: it runs when the adopted origin is not the owner, and does not run after a successful handoff. Refs #14 Assisted-by: Cindy (https://cindy.app) --- tests/zcode-mcp-eof.test.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/tests/zcode-mcp-eof.test.ts b/tests/zcode-mcp-eof.test.ts index d60c6601af..e18bcebf2c 100644 --- a/tests/zcode-mcp-eof.test.ts +++ b/tests/zcode-mcp-eof.test.ts @@ -134,7 +134,7 @@ for (const blockedAt of ["activate", "ensure"] as const) { const exits: number[] = []; let routes = 0; const state = { origin: OLD, failures: 2, policy: defaultZcodeRoutePolicy() }; - await routeZcodeConfig({ origin: OLD, dataDir: dir, log: () => {} }); + await routeZcodeConfig({ origin: OLD, dataDir: dir, env: {}, log: () => {} }); const stop = entry.startWatchdog(state, false, () => {}, { intervalMs: 1, probe: async () => false, @@ -142,7 +142,7 @@ for (const blockedAt of ["activate", "ensure"] as const) { if (blockedAt === "ensure") { entered.resolve(); await blocked.promise; } return { origin: NEW }; }, - route: async (opts) => { routes++; return routeZcodeConfig({ ...opts, dataDir: dir, log: () => {} }); }, + route: async (opts) => { routes++; return routeZcodeConfig({ ...opts, dataDir: dir, env: {}, log: () => {} }); }, activate: async () => { if (blockedAt === "activate") { entered.resolve(); await blocked.promise; } }, @@ -150,25 +150,38 @@ for (const blockedAt of ["activate", "ensure"] as const) { }); entry.installExitHandoff(state, () => {}, { events: emitter, - handoff: (ownOrigin) => handoffZcodeRoutingOnExit({ ownOrigin, dataDir: dir, log: () => {}, findReplacement: async () => undefined }), + handoff: (ownOrigin) => handoffZcodeRoutingOnExit({ ownOrigin, dataDir: dir, env: {}, log: () => {}, findReplacement: async () => undefined }), exit: (code) => { exits.push(code); exited.resolve(); }, }); const hold = setTimeout(() => {}, 5000); try { await entered.promise; - assert.equal(detectCurrentZcodeOrigin(dir), blockedAt === "activate" ? NEW : OLD); + assert.equal(detectCurrentZcodeOrigin(dir, {}), blockedAt === "activate" ? NEW : OLD); emitter.emit("SIGTERM"); await exited.promise; assert.deepEqual(exits, [143]); - assert.equal(detectCurrentZcodeOrigin(dir), undefined); + assert.equal(detectCurrentZcodeOrigin(dir, {}), undefined); blocked.resolve(); await stop(); - assert.equal(detectCurrentZcodeOrigin(dir), undefined); + assert.equal(detectCurrentZcodeOrigin(dir, {}), undefined); assert.equal(routes, blockedAt === "activate" ? 1 : 0); } finally { clearTimeout(hold); blocked.resolve(); await stop(); rmrf(dir); } }); } +for (const first of ["reverted-direct", "not-ours"] as const) { + test(`exit handoff tries the in-flight routing origin only when the adopted origin is not the owner (first=${first})`, async () => { + const asked: string[] = []; + const handoff = entry.installExitHandoff({ origin: OLD, routing: NEW }, () => {}, { + events: new EventEmitter(), + handoff: async (ownOrigin) => { asked.push(ownOrigin); return ownOrigin === OLD ? first : "reverted-direct"; }, + exit: () => { assert.fail("EOF must not force exit"); }, + }); + await handoff(); + assert.deepEqual(asked, first === "not-ours" ? [OLD, NEW] : [OLD]); + }); +} + test("signal deadline forces the original code while overlapping handoff runs once", async () => { const work = deferred(); const emitter = new EventEmitter();