Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(mcp): end session and team records before exiting on SIGTERM

Jack Rudenko6a710686177a
diff --git a/packages/cli/src/mcp-shutdown.e2e.test.ts b/packages/cli/src/mcp-shutdown.e2e.test.ts
new file mode 100644
index 00000000..aef4ed7d
--- /dev/null
+++ b/packages/cli/src/mcp-shutdown.e2e.test.ts
@@ -0,0 +1,173 @@
+/**
+ * MCP server shutdown leaves nothing behind (architecture D15 layer 3, §20.3 item 8).
+ *
+ * A real claudish MCP server over stdio holds a live channel session and a live team run,
+ * both panes of the pane fake (`@@HANG@@`: the prompt is accepted and never answered) in
+ * real headless magmux under the test's own CLAUDISH_PANE_ROOT. Then:
+ *
+ * - stdin EOF (the host closed the transport) → the server settles the team run and the
+ * session CANCELLED, so both records end (`meta.json` status `cancelled`, no wait left
+ * open), reaps every pane and exits 0;
+ * - SIGTERM → the same, exit 143;
+ * - SIGKILL → no record ends, but the per-pane watchers remove every process and file.
+ *
+ * After each: no process whose argv names the pane root, and no socket, record or
+ * launcher dir in it.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import {
+ MAGMUX_AVAILABLE,
+ McpServer,
+ NO_MAGMUX_MESSAGE,
+ findField,
+ paneOrphans,
+ serverEnv,
+} from "./test-helpers/contract-mcp.js";
+import {
+ type TempLayout,
+ makeTempLayout,
+ readJson,
+ readWaitLines,
+ waitFor,
+ waitPairingViolations,
+} from "./test-helpers/contract-records.js";
+
+const T_TEST = 60_000;
+
+type Json = Record<string, unknown>;
+
+let layout: TempLayout;
+let server: McpServer;
+
+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);
+
+beforeEach(async () => {
+ layout = makeTempLayout("mcpshutdown");
+ server = await McpServer.start({
+ // the fake's safety exit must not end a @@HANG@@ pane before the shutdown does
+ env: serverEnv(layout, { CONTRACT_FAKE_MAX_MS: "60000" }),
+ cwd: layout.cwd,
+ });
+});
+afterEach(async () => {
+ await server.close(2_000);
+ const report = await paneOrphans(layout, 12_000);
+ layout.cleanup();
+ expect(report).toEqual({ processes: [], files: [] });
+});
+
+interface Live {
+ sessionId: string;
+ monitorRecord: string;
+}
+
+/** A RUNNING channel session and an ACTIVE two-slot team run, both hanging. */
+async function startWork(): Promise<Live> {
+ const created = await server.callTool("create_session", {
+ model: "contract-fake-model",
+ prompt: "never answer @@HANG@@",
+ });
+ expect(created.isError).toBe(false);
+ const sessionId = (created.json as Json).session_id as string;
+
+ const run = await server.callTool("team", {
+ mode: "run",
+ path: join(layout.cwd, "team-shutdown"),
+ models: ["contract-fake-a", "contract-fake-b"],
+ input: "never answer @@HANG@@",
+ });
+ expect(run.isError).toBe(false);
+ const monitorRecord = findField(run.json, "monitor_record") as string;
+ expect(typeof monitorRecord).toBe("string");
+
+ await waitFor(
+ async () => {
+ const list = await server.callTool("list_sessions", {});
+ const row = ((list.json as Json).sessions as Json[]).find((s) => s.session_id === sessionId);
+ return row?.state === "RUNNING";
+ },
+ { what: "the session to be RUNNING", timeoutMs: 20_000, intervalMs: 100 }
+ );
+ const status = await server.callTool("team", {
+ mode: "status",
+ path: join(layout.cwd, "team-shutdown"),
+ });
+ const slots = ((status.json as Json).run as Json).slots as Json[];
+ expect(slots.map((s) => s.state)).toEqual(["RUNNING", "RUNNING"]);
+ return { sessionId, monitorRecord };
+}
+
+async function exitCode(ms: number): Promise<number | null> {
+ return Promise.race([server.proc.exited, Bun.sleep(ms).then(() => null)]);
+}
+
+/** Both records ended `cancelled`, and the session's wait log (if any) is closed. */
+function expectRecordsEnded(live: Live): void {
+ const sessionDir = join(layout.sessionsDir, live.sessionId);
+ const meta = readJson(join(sessionDir, "meta.json"));
+ expect(meta?.status).toBe("cancelled");
+ expect(meta?.state).toBe("CANCELLED");
+ expect(meta?.terminalReason).toBe("cancelled");
+ expect(waitPairingViolations(readWaitLines(sessionDir) ?? [], false)).toEqual([]);
+
+ const teamMeta = readJson(join(layout.sessionsDir, live.monitorRecord, "meta.json"));
+ expect(teamMeta).toMatchObject({ kind: "team", status: "cancelled", slots: 2, cancelled: 2 });
+
+ const status = readJson(join(layout.cwd, "team-shutdown", "status.json")) as Json;
+ for (const m of Object.values(status.models as Record<string, Json>)) {
+ expect(m.state).toBe("CANCELLED");
+ expect((m.error as Json | undefined)?.reason).toBe("cancelled");
+ }
+}
+
+describe.skipIf(!MAGMUX_AVAILABLE)("MCP server shutdown", () => {
+ test(
+ "stdin EOF: records end cancelled, every pane is reaped, exit 0",
+ async () => {
+ const live = await startWork();
+
+ (server.proc.stdin as { end(): unknown }).end();
+ const code = await exitCode(20_000);
+
+ expect(code).toBe(0);
+ expectRecordsEnded(live);
+ const report = await paneOrphans(layout, 8_000);
+ expect(report).toEqual({ processes: [], files: [] });
+ },
+ T_TEST
+ );
+
+ test(
+ "SIGTERM: records end cancelled, every pane is reaped, exit 143",
+ async () => {
+ const live = await startWork();
+
+ server.proc.kill("SIGTERM");
+ const code = await exitCode(20_000);
+
+ expect(code).toBe(143);
+ expectRecordsEnded(live);
+ const report = await paneOrphans(layout, 8_000);
+ expect(report).toEqual({ processes: [], files: [] });
+ },
+ T_TEST
+ );
+
+ test(
+ "SIGKILL: no record ends, but the pane watchers remove every process and file",
+ async () => {
+ const live = await startWork();
+
+ server.proc.kill("SIGKILL");
+ await exitCode(5_000);
+
+ const report = await paneOrphans(layout, 10_000);
+ expect(report).toEqual({ processes: [], files: [] });
+ // the writer died: its records have no end (an observer reports from its liveness)
+ expect(readJson(join(layout.sessionsDir, live.sessionId, "meta.json"))).toBeUndefined();
+ expect(readJson(join(layout.sessionsDir, live.monitorRecord, "meta.json"))).toBeUndefined();
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.ts
index 339d96ed..6d202c16 100644
--- a/packages/cli/src/pane/pane-registry.ts
+++ b/packages/cli/src/pane/pane-registry.ts
@@ -24,6 +24,7 @@ import {
writeFileSync,
} from "node:fs";
import { join } from "node:path";
+import { claimSignalExit } from "../signal-owner.js";
import { MagmuxClient } from "./magmux-client.js";
import { ensureSockRoot, sockRootFor } from "./pane-launch.js";
import {
@@ -357,6 +358,8 @@ export function installPaneShutdownHooks(opts?: ShutdownHookOptions): void {
if (opts) hookOpts = { exitAfter: true, ...opts };
if (!hooksInstalled) {
hooksInstalled = true;
+ // stats-buffer's module-load listeners must not exit before our records are settled
+ claimSignalExit();
for (const [sig, n] of SIGNALS) process.on(sig, () => void shutdown("signal", 128 + n));
// A synchronous exit can only SIGKILL magmux handles; groups and files are the watchers' job.
process.on("exit", () => {
diff --git a/packages/cli/src/signal-owner.ts b/packages/cli/src/signal-owner.ts
new file mode 100644
index 00000000..050c0ea5
--- /dev/null
+++ b/packages/cli/src/signal-owner.ts
@@ -0,0 +1,21 @@
+/**
+ * Who exits the process on SIGTERM / SIGINT.
+ *
+ * `stats-buffer.ts` registers signal listeners at module load that flush telemetry and
+ * call `process.exit` synchronously. A process that owns interactive panes must instead
+ * settle its records (meta.json, the closing wait line, the team record) and reap its
+ * panes BEFORE it exits, which is asynchronous; the pane registry's shutdown exits with
+ * 128 + n itself once that is done. It claims the exit here, and the stats listener then
+ * only flushes (its `exit` listener still flushes once more at the real exit).
+ *
+ * A flag module rather than an import, so `stats-buffer.ts` does not load the pane code.
+ */
+let claimed = false;
+
+export function claimSignalExit(): void {
+ claimed = true;
+}
+
+export function signalExitClaimed(): boolean {
+ return claimed;
+}
diff --git a/packages/cli/src/stats-buffer.ts b/packages/cli/src/stats-buffer.ts
index 6421ee14..199f64cc 100644
--- a/packages/cli/src/stats-buffer.ts
+++ b/packages/cli/src/stats-buffer.ts
@@ -18,6 +18,7 @@ import {
} from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
+import { signalExitClaimed } from "./signal-owner.js";
import type { StatsEvent } from "./stats-otlp.js";
// ─── Constants ────────────────────────────────────────────────────────────────
@@ -248,6 +249,7 @@ for (const signal of ["SIGTERM", "SIGINT"] as const) {
} catch {
// Silently ignore
}
- process.exit(SIGNAL_EXIT_CODE[signal]);
+ // A pane owner exits with the same code itself, after settling its records.
+ if (!signalExitClaimed()) process.exit(SIGNAL_EXIT_CODE[signal]);
});
}