Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions src/zcode/mcp-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,21 @@ export async function zcodeWatchdogTick(state: MutableZcodeWatchdogState, extern
state.routing = origin;
process.env.BILI_MCP_PROXY = origin;
const route = deps.route ?? routeZcodeConfig;
const routed = await route({ origin, log, policy: state.policy });
if (!routed) throw new Error("proxy respawned but the zcode config rewrite failed");
const activate = deps.activate ?? activateZcodePluginMode;
await activate(routed, { log });
state.origin = origin;
state.routing = undefined;
log(`proxy respawned at ${origin} — config re-routed`);
// The write waits for the config lock; a shutdown that begins
// meanwhile runs the exit handoff, and a route written after
// it would be left pointing at a proxy no session owns.
const routed = await route({ origin, log, policy: state.policy, shouldWrite: () => !state.stopped });
if (!routed && state.stopped) {
state.routing = undefined;
log(`proxy respawned at ${origin} during shutdown — route not written, routing left to the exit handoff`);
} else {
if (!routed) throw new Error("proxy respawned but the zcode config rewrite failed");
const activate = deps.activate ?? activateZcodePluginMode;
await activate(routed, { log });
state.origin = origin;
state.routing = undefined;
log(`proxy respawned at ${origin} — config re-routed`);
}
}
state.failures = 0;
}
Expand Down
13 changes: 12 additions & 1 deletion src/zcode/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ interface RouteZcodeOptions {
* exemptions — call sites that resolve config themselves (bootstrap,
* watchdog, handoff) pass their resolved policy through. */
readonly policy?: ZcodeRoutePolicy;
/** Asked while holding the config lock, immediately before the write.
* Returning false leaves the store untouched and the call returns
* undefined. For callers whose right to write can lapse while they wait
* for the lock (the watchdog once shutdown has begun). */
readonly shouldWrite?: () => boolean;
}

// #1002 snapshot discipline: .bili-bak holds the state before bili's LATEST
Expand Down Expand Up @@ -264,9 +269,15 @@ export async function routeZcodeConfig(opts: RouteZcodeOptions): Promise<ZcodeRo
logNoRouteNextSteps({ kind, dataDir, env, origin: opts.origin, policy, skipped: applied.skipped, log });
return undefined;
}
await withConfigLock(dataDir, () => {
const written = await withConfigLock(dataDir, () => {
if (opts.shouldWrite && !opts.shouldWrite()) return false;
snapshotAndWrite(file, applied.text);
return true;
});
if (!written) {
log("route write declined by the caller — leaving the config untouched");
return undefined;
}
// Re-apply against the written text to catch self-apply corruption early
// (must be a fixed point: same wrapped set, byte-stable output).
const check = applyZcodeRouting(fs.readFileSync(file, "utf8"), kind, opts.origin, policy);
Expand Down
138 changes: 137 additions & 1 deletion tests/zcode-mcp-eof.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ 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 { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { defaultZcodeRoutePolicy, detectCurrentZcodeOrigin, zcodeStoreCandidates } from "../src/zcode/json-edit.ts";
Expand Down Expand Up @@ -169,6 +169,142 @@ for (const blockedAt of ["activate", "ensure"] as const) {
});
}

for (const signalled of [true, false]) {
test(`watchdog replacement waiting on the config lock writes its route only if shutdown has not begun (signalled=${signalled})`, { timeout: 8000 }, async () => {
const dir = routedStore();
const lockDir = path.join(dir, "v2", ".bili-config.lock");
const entered = deferred();
const exited = deferred();
const emitter = new EventEmitter();
const exits: number[] = [];
const logs: string[] = [];
let storeAtExit: string | undefined = "unset";
const state = { origin: OLD, failures: 2, policy: defaultZcodeRoutePolicy() };
await routeZcodeConfig({ origin: OLD, dataDir: dir, env: {}, log: () => {} });
// Another live process holds the config lock, so the replacement's
// write waits inside routeZcodeConfig.
const holdLock = () => { mkdirSync(lockDir); writeFileSync(path.join(lockDir, "pid"), String(process.pid)); };
const releaseLock = () => rmSync(lockDir, { recursive: true, force: true });
holdLock();
const stop = entry.startWatchdog(state, false, (msg) => logs.push(msg), {
intervalMs: 1,
probe: async () => false,
ensure: async () => ({ origin: NEW }),
route: (opts) => { entered.resolve(); return routeZcodeConfig({ ...opts, dataDir: dir, env: {}, log: () => {} }); },
activate: async () => {},
repair: async () => {},
});
entry.installExitHandoff(state, () => {}, {
events: emitter,
handoff: async (ownOrigin) => {
const outcome = await handoffZcodeRoutingOnExit({ ownOrigin, dataDir: dir, env: {}, log: () => {}, findReplacement: async () => undefined });
// The lock frees after the handoff finished but before the
// process exits; the waiting replacement gets its turn.
releaseLock();
await delay(300);
return outcome;
},
exit: (code) => { exits.push(code); storeAtExit = detectCurrentZcodeOrigin(dir, {}); exited.resolve(); },
});
const hold = setTimeout(() => {}, 8000);
try {
await entered.promise;
assert.equal(detectCurrentZcodeOrigin(dir, {}), OLD);
if (signalled) {
emitter.emit("SIGTERM");
await exited.promise;
assert.deepEqual(exits, [143]);
assert.equal(storeAtExit, undefined, "no route may be written after the exit handoff reverted the store");
await stop();
assert.equal(detectCurrentZcodeOrigin(dir, {}), undefined);
assert.equal(state.origin, OLD);
assert.doesNotMatch(logs.join("\n"), /watchdog error/);
} else {
releaseLock();
for (let i = 0; i < 50 && state.origin !== NEW; i++) await delay(20);
assert.equal(state.origin, NEW);
assert.equal(detectCurrentZcodeOrigin(dir, {}), NEW);
await stop();
}
} finally { clearTimeout(hold); releaseLock(); await stop(); rmrf(dir); }
});
}

for (const allow of [true, false]) {
test(`routeZcodeConfig asks shouldWrite under the config lock and writes only on true (allow=${allow})`, async () => {
const dir = routedStore();
const file = zcodeStoreCandidates(dir, "legacy", {})[0];
const lockDir = path.join(dir, "v2", ".bili-config.lock");
const logs: string[] = [];
const lockHeld: boolean[] = [];
try {
const before = readFileSync(file, "utf8");
const routed = await routeZcodeConfig({
origin: NEW, dataDir: dir, env: {}, log: (msg) => logs.push(msg),
shouldWrite: () => { lockHeld.push(existsSync(lockDir)); return allow; },
});
assert.deepEqual(lockHeld, [true]);
assert.equal(existsSync(lockDir), false);
if (allow) {
assert.equal(routed?.origin, NEW);
assert.equal(detectCurrentZcodeOrigin(dir, {}), NEW);
assert.doesNotMatch(logs.join("\n"), /declined/);
} else {
assert.equal(routed, undefined);
assert.equal(readFileSync(file, "utf8"), before);
assert.match(logs.join("\n"), /route write declined/);
}
} finally { rmrf(dir); }
});
}

for (const attachable of [true, false]) {
test(`EOF during a watchdog respawn leaves routing to the exit handoff (respawned proxy attachable=${attachable})`, { timeout: 5000 }, async (t) => {
// The handoff reports runtime-info to the replacement it routes to;
// answer it here so the test never contacts a port it does not own.
const posted: string[] = [];
t.mock.method(globalThis, "fetch", async (input: Parameters<typeof fetch>[0]) => {
posted.push(String(input));
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
});
const dir = routedStore();
const blocked = deferred();
const entered = deferred();
let routes = 0;
const state = { origin: OLD, failures: 2, policy: defaultZcodeRoutePolicy() };
await routeZcodeConfig({ origin: OLD, dataDir: dir, env: {}, log: () => {} });
const stop = entry.startWatchdog(state, false, () => {}, {
intervalMs: 1,
probe: async () => false,
ensure: async () => { entered.resolve(); await blocked.promise; return { origin: NEW }; },
route: async (opts) => { routes++; return routeZcodeConfig({ ...opts, dataDir: dir, env: {}, log: () => {} }); },
activate: async () => {},
repair: async () => {},
});
const handoff = entry.installExitHandoff(state, () => {}, {
events: new EventEmitter(),
handoff: (ownOrigin) => handoffZcodeRoutingOnExit({
ownOrigin, dataDir: dir, env: {}, log: () => {},
findReplacement: async () => (attachable ? { origin: NEW } : undefined),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ai: openai/gpt-6-astra)

WARNING: Isolate the handoff's runtime-info request from the fixed port

With attachable=true, this replacement invokes the real activateZcodePluginMode through handoffZcodeRoutingOnExit (src/zcode/native.ts:616-618), which POSTs runtime-info to NEW, http://127.0.0.1:28787. The activate stub above only covers the watchdog, and neither test preload mocks fetch. If another listener accepts the connection without responding, the request's own 5,000 ms timeout (src/agent/shared.ts:24,298-303) starts after the test's 5,000 ms deadline has begun, so this routing test fails despite correct shutdown behavior. Stub the runtime-info fetch with a test-scoped, automatically restored mock so the test does not contact an unowned fixed port.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ai: anthropic/claude-fable-5-2)

Valid. Fixed in 914c0f3: the test now answers the runtime-info request with a test-scoped fetch mock, restored automatically, and asserts the request goes to the replacement origin only when one is reported.

}),
exit: () => { assert.fail("EOF must not force exit"); },
});
const hold = setTimeout(() => {}, 5000);
try {
await entered.promise;
const drained = stop().then(handoff);
blocked.resolve();
await drained;
// The tick never routes to the proxy it spawned during shutdown;
// the handoff routes to it only when discovery reports it live.
assert.equal(routes, 0);
assert.equal(state.origin, OLD);
assert.equal(detectCurrentZcodeOrigin(dir, {}), attachable ? NEW : undefined);
assert.deepEqual(posted, attachable ? [`${NEW}/__bili/plugin/runtime-info`] : []);
} 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[] = [];
Expand Down
Loading