Skip to content

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

fix(pane): stop dead owners' records filling the pane limit without ps

Jack Rudenko3713ac19dcb7
diff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.ts
index 32402364..21336726 100644
--- a/packages/cli/src/pane/pane-registry.test.ts
+++ b/packages/cli/src/pane/pane-registry.test.ts
@@ -16,7 +16,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
-import { createServer } from "node:net";
+import { type Server, createServer } from "node:net";
import { join } from "node:path";
import { waitForExit } from "../process-tree.js";
import {
@@ -43,6 +43,7 @@ import {
reservePanes,
reservedPaneCount,
sweepOrphanPanes,
+ updateRecord,
writeRecord,
} from "./pane-registry.js";
import { startPaneSession } from "./pane-session.js";
@@ -51,6 +52,7 @@ import {
isPaneRecordPath,
isPaneSockPath,
isPaneWatcherCommand,
+ pidMayBeAlive,
recordPathOf,
sockPathOf,
} from "./process-identity.js";
@@ -217,7 +219,7 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
const t = env();
const { s, uuid } = await withProcessTableUnavailable(async () => {
const started = await hangSession(t);
- // onSnapshot → setPanePid → readProcessTableAsync, which rejected unhandled
+ // onSnapshot → setPanePid → readProcessTableAsync must resolve, never reject
for (let i = 0; i < 100 && !readRecord(t.sockRoot, started.s.paneId)?.panePid; i++)
await Bun.sleep(50);
await Bun.sleep(200);
@@ -734,24 +736,37 @@ describe("reservations", () => {
});
});
-describe("with the process table unavailable (a sandbox refuses ps): every pane is assumed alive", () => {
- /** A pane of THIS live process, as another owner's sweep or count would find it. */
- function liveOwnerPane(t: PaneTestEnv, label: string): PaneRecord {
+describe("with the process table unavailable (a sandbox refuses ps): owners judged by kill(pid, 0)", () => {
+ /** A listening unix socket standing in for a live magmux. */
+ async function liveSocket(path: string): Promise<Server> {
+ const server = createServer((c) => c.end());
+ await new Promise<void>((resolve) => server.listen(path, resolve));
+ return server;
+ }
+
+ /**
+ * A pane record as another owner's sweep or count would find it: owned by THIS live
+ * process, or by a pid that is gone (an owner SIGKILLed inside a sandbox, so its
+ * record has no ownerStart and nothing removed it). The socket is a plain file: it
+ * refuses a connection, as a dead magmux's does.
+ */
+ function ownerPane(t: PaneTestEnv, label: string, owner: "live" | "dead"): PaneRecord {
const root = ensureSockRoot(t.sockRoot);
- const paneId = `c${process.pid}-${OWNER_START36}-t${label}-abcdef`;
+ const ownerPid = owner === "live" ? process.pid : deadPid();
+ const paneId = `c${ownerPid}-${OWNER_START36}-t${label}-abcdef`;
const ctl = join(root, `launch-${label}Ctl1`);
const turn = join(root, `launch-${label}Trn1`);
mkdirSync(ctl, { mode: 0o700 });
mkdirSync(turn, { mode: 0o700 });
const rec: PaneRecord = {
paneId,
- ownerPid: process.pid,
- ownerStart: ownerStartOfSelf(), // read while the table is still readable
+ ownerPid,
+ ownerStart: owner === "live" ? ownerStartOfSelf() : "",
watcherPid: null,
magmuxPid: null,
panePid: null,
sessionUuid: crypto.randomUUID(),
- sockPath: join(root, `magmux-${paneId}.sock`),
+ sockPath: sockPathOf(root, paneId),
launcherDir: ctl,
turnDir: turn,
createdAt: new Date().toISOString(),
@@ -761,37 +776,90 @@ describe("with the process table unavailable (a sandbox refuses ps): every pane
return rec;
}
- test("the sweep keeps a live owner's record, socket and dirs", async () => {
+ const filesOf = (rec: PaneRecord) => [rec.sockPath, rec.launcherDir, rec.turnDir];
+
+ test("the ps-free probe: ESRCH is dead; success and EPERM are alive", () => {
+ expect(pidMayBeAlive(process.pid)).toBe(true);
+ expect(pidMayBeAlive(deadPid())).toBe(false);
+ expect(pidMayBeAlive(1)).toBe(true); // launchd/init: EPERM
+ });
+
+ test("a live owner: counted, and the sweep keeps its record, socket and dirs", async () => {
const t = env();
- const rec = liveOwnerPane(t, "sw");
+ const rec = ownerPane(t, "lv", "live");
+ expect(await withProcessTableUnavailable(() => livePaneCount(t.sockRoot))).toBe(1);
const r = await withProcessTableUnavailable(() => sweepOrphanPanes(t.sockRoot));
- expect(r.kept).toContain(rec.paneId);
- expect(r.cleaned).toEqual([]);
+ expect(r).toEqual({ reaped: [], cleaned: [], kept: [] });
expect(readRecord(t.sockRoot, rec.paneId)).not.toBeNull();
- for (const p of [rec.sockPath, rec.launcherDir, rec.turnDir]) expect(existsSync(p)).toBe(true);
+ for (const p of filesOf(rec)) expect(existsSync(p)).toBe(true);
});
- test("the sweep leaves a recordless live socket alone", async () => {
+ test("a dead owner whose magmux is gone: not counted, and the sweep removes its files", async () => {
const t = env();
- const root = ensureSockRoot(t.sockRoot);
- const sock = join(root, `magmux-c${process.pid}-${OWNER_START36}-tls-abcdef.sock`);
- const server = createServer((c) => c.end());
- await new Promise<void>((resolve) => server.listen(sock, resolve));
+ const rec = ownerPane(t, "dd", "dead");
+ expect(await withProcessTableUnavailable(() => livePaneCount(t.sockRoot))).toBe(0);
+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(t.sockRoot));
+ expect(r.cleaned).toEqual([rec.paneId]);
+ expect(readRecord(t.sockRoot, rec.paneId)).toBeNull();
+ for (const p of filesOf(rec)) expect(existsSync(p)).toBe(false);
+ });
+
+ test("dead owners never fill the pane limit", async () => {
+ const t = env();
+ for (let i = 0; i < MAX_LIVE_PANES; i++) ownerPane(t, i.toString(36).padStart(2, "0"), "dead");
+ // 48 records of dead owners: a start must still be admitted, not refused as pane_limit
+ await withProcessTableUnavailable(() => reservePanes(1, t.sockRoot));
+ releasePaneReservations(1);
+ });
+
+ test("a dead owner whose magmux still answers: not counted, files kept, nothing signalled", async () => {
+ const t = env();
+ const rec = ownerPane(t, "dm", "dead");
+ rmSync(rec.sockPath);
+ const server = await liveSocket(rec.sockPath);
try {
- const r = await withProcessTableUnavailable(() => sweepOrphanPanes(root));
- expect(r.cleaned).toEqual([]);
- expect(existsSync(sock)).toBe(true);
+ expect(await withProcessTableUnavailable(() => livePaneCount(t.sockRoot))).toBe(0);
+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(t.sockRoot));
+ expect(r.kept).toEqual([rec.paneId]);
+ expect(readRecord(t.sockRoot, rec.paneId)).not.toBeNull();
+ for (const p of filesOf(rec)) expect(existsSync(p)).toBe(true);
} finally {
server.close();
}
}, 20_000);
- test("the pane limit counts a live owner's record", async () => {
+ test("a dead owner whose watcher pid may be alive: kept (the watcher may be mid-job)", async () => {
const t = env();
- liveOwnerPane(t, "lc");
- expect(livePaneCount(t.sockRoot)).toBe(1);
- expect(await withProcessTableUnavailable(() => livePaneCount(t.sockRoot))).toBe(1);
+ const rec = ownerPane(t, "dw", "dead");
+ updateRecord(t.sockRoot, rec.paneId, { watcherPid: process.pid });
+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(t.sockRoot));
+ expect(r.kept).toEqual([rec.paneId]);
+ for (const p of filesOf(rec)) expect(existsSync(p)).toBe(true);
});
+
+ test("recordless sockets: a live owner's is left alone; a dead owner's live one is kept, its refused one removed", async () => {
+ const t = env();
+ const root = ensureSockRoot(t.sockRoot);
+ const gone = deadPid();
+ const ownLive = join(root, `magmux-c${process.pid}-${OWNER_START36}-tls-abcdef.sock`);
+ const deadLive = join(root, `magmux-c${gone}-${OWNER_START36}-tdl-abcdef.sock`);
+ const deadRefused = join(root, `magmux-c${gone}-${OWNER_START36}-tdr-abcdef.sock`);
+ const servers = [await liveSocket(ownLive), await liveSocket(deadLive)];
+ writeFileSync(deadRefused, "");
+ try {
+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(root));
+ expect(r.reaped).toEqual([]);
+ expect(r.kept).toEqual([`c${gone}-${OWNER_START36}-tdl-abcdef`]);
+ expect(r.cleaned).toEqual([`c${gone}-${OWNER_START36}-tdr-abcdef`]);
+ expect([ownLive, deadLive, deadRefused].map((p) => existsSync(p))).toEqual([
+ true,
+ true,
+ false,
+ ]);
+ } finally {
+ for (const s of servers) s.close();
+ }
+ }, 20_000);
});
describe("owner identity: one check for the pane limit, the record sweep and the socket sweep", () => {
diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.ts
index 2add5095..19304ad6 100644
--- a/packages/cli/src/pane/pane-registry.ts
+++ b/packages/cli/src/pane/pane-registry.ts
@@ -31,6 +31,7 @@ import { ensureSockRoot, sockRootFor } from "./pane-launch.js";
import {
type GroupSnapshot,
type PaneIdentity,
+ type ProcessTable,
type PsRow,
findPaneMagmux,
formatGroupFile,
@@ -45,10 +46,12 @@ import {
liveEscaped,
mergeSnapshots,
parseGroupFile,
+ pidMayBeAlive,
readProcessTable,
readProcessTableAsync,
recordPathOf,
sameSnapshot,
+ sockPathOf,
startedAt,
verifiedGroupSnapshot,
} from "./process-identity.js";
@@ -99,8 +102,11 @@ export type PaneOwner = Pick<PaneRecord, "paneId" | "ownerPid" | "ownerStart">;
* equal the row's `lstart`. Without one (written while the owner could not read the
* table, or a recordless socket) the start time the pane id embeds must match the row's
* timezone-free `startMs`; an id that embeds none is not ours to judge and counts alive.
+ * With the table unavailable only `kill(pid, 0)` can answer (`pidMayBeAlive`): ESRCH is
+ * dead, anything else alive.
*/
-export function ownerAlive(owner: PaneOwner, table: PsRow[]): boolean {
+export function ownerAlive(owner: PaneOwner, table: ProcessTable): boolean {
+ if (!table) return pidMayBeAlive(owner.ownerPid);
const row = table.find((r) => r.pid === owner.ownerPid);
if (!row) return false;
if (owner.ownerStart) return row.lstart === owner.ownerStart;
@@ -290,15 +296,10 @@ async function tick(): Promise<void> {
/* ───────────────────────────── the pane limit ───────────────────────────── */
-/**
- * Records with a live owner whose reap has not finished, across every owner, plus our
- * reservations. With the table unavailable every such record's owner counts as alive.
- */
+/** Records with a live owner whose reap has not finished, across every owner, plus our reservations. */
export function livePaneCount(root: string = sockRootFor()): number {
const table = readProcessTable();
- const counted = readRecords(root).filter(
- (r) => !r.reapFailed && (!table || ownerAlive(r, table))
- ).length;
+ const counted = readRecords(root).filter((r) => !r.reapFailed && ownerAlive(r, table)).length;
return counted + reserved;
}
@@ -484,11 +485,11 @@ async function killVerified(rec: PaneRecord, root: string): Promise<SweepTargets
async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Promise<void> {
const table = readProcessTable();
+ if (ownerAlive(rec, table)) return;
if (!table) {
- out.kept.push(rec.paneId); // nothing can be verified: the owner may be alive
+ await sweepUnidentifiable(rec, root, out);
return;
}
- if (ownerAlive(rec, table)) return;
const watcher = rec.watcherPid ? table.find((r) => r.pid === rec.watcherPid) : undefined;
if (watcher && isPaneWatcherCommand(watcher.command, rec.paneId)) {
out.kept.push(rec.paneId); // the watcher is mid-job
@@ -513,6 +514,37 @@ async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Pro
else out.cleaned.push(rec.paneId);
}
+/** A unix socket at `sockPath` accepts a connection: some magmux still serves it. */
+async function socketAnswers(sockPath: string): Promise<boolean> {
+ try {
+ (await MagmuxClient.dial(sockPath)).close();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A dead owner's record (kill(pid, 0) answered ESRCH) while the table is unavailable.
+ * No process can be identified, so nothing is signalled. A watcher pid that may be alive
+ * may be mid-job, and a socket that still answers is a live magmux: both keep the files,
+ * and the pane is left running for a sweep that can read the table. Otherwise the pane's
+ * magmux is gone and its files are removed, as the dead-owner path does when nothing is
+ * verified alive.
+ */
+async function sweepUnidentifiable(rec: PaneRecord, root: string, out: SweepResult) {
+ if (rec.watcherPid && pidMayBeAlive(rec.watcherPid)) {
+ out.kept.push(rec.paneId);
+ return;
+ }
+ if (await socketAnswers(sockPathOf(root, rec.paneId))) {
+ out.kept.push(rec.paneId);
+ return;
+ }
+ removePaneFiles(root, rec);
+ out.cleaned.push(rec.paneId);
+}
+
/** `c<pid>-<start36>-…`: the owner pid and start (ms) a pane id embeds. */
export function ownerOfPaneId(id: string): { pid: number; startMs: number } | null {
const m = id.match(/^c(\d+)-([0-9a-z]+)-/);
@@ -529,10 +561,6 @@ function ownerOfSocketId(id: string): PaneOwner | null {
async function sweepRecordlessSocket(root: string, name: string, out: SweepResult): Promise<void> {
const id = name.slice("magmux-".length, -".sock".length);
const table = readProcessTable();
- if (!table) {
- out.kept.push(id); // the owner may be alive and the socket a live magmux's
- return;
- }
const owner = ownerOfSocketId(id);
if (!owner || ownerAlive(owner, table)) return; // no owner in the id: not ours to judge
const sockPath = join(root, name);
@@ -544,6 +572,12 @@ async function sweepRecordlessSocket(root: string, name: string, out: SweepResul
out.cleaned.push(id);
return;
}
+ if (!table) {
+ // a live magmux of a dead owner: without the table nothing identifies its processes
+ client.close();
+ out.kept.push(id);
+ return;
+ }
const list = await client.request<{ panes?: Array<{ pid?: number; pane?: number }> }>({
type: "list",
});
diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.ts
index d0a98932..687220a3 100644
--- a/packages/cli/src/pane/process-identity.test.ts
+++ b/packages/cli/src/pane/process-identity.test.ts
@@ -374,8 +374,8 @@ describe("the process table when ps cannot run (macOS refuses the setuid ps in a
});
test("readProcessTableAsync resolves null, never rejects, when execFile throws synchronously", async () => {
- // Bun throws EPERM from execFile itself; an unguarded executor rejected, and the MCP
- // server's unhandled rejection (setPanePid) exited it with status 1
+ // Bun throws EPERM from execFile itself; a rejection here is unhandled in setPanePid
+ // and exits the MCP server with status 1
await withProcessTableUnavailable(async () => {
await expect(readProcessTableAsync()).resolves.toBeNull();
expect(readProcessTable()).toBeNull();
diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.ts
index cb9071b5..b35d1fc0 100644
--- a/packages/cli/src/pane/process-identity.ts
+++ b/packages/cli/src/pane/process-identity.ts
@@ -126,8 +126,11 @@ export function startedAt(row: PsRow, startMs: number): boolean {
/**
* The process table, or null when it is UNAVAILABLE: `ps` could not run, failed, or
* printed no row. A readable table is never empty (it lists the reader), so null never
- * means "no process": every caller treats what it would have looked up as possibly
- * alive — no reap, no sweep, no file removed, no owner counted dead.
+ * means "no process". Without a table no process can be identified, so nothing is
+ * signalled and no group is verified; only an owner's liveness has a fallback
+ * (`pidMayBeAlive`), and only a pane whose magmux no longer answers its socket has its
+ * files removed. A crashed owner's magmux and Claude Code are left running until a sweep
+ * that can read the table.
*
* Measured: macOS refuses to exec the setuid `/bin/ps` from ANY Seatbelt sandbox, even
* `sandbox-exec -p '(version 1)(allow default)'` (EPERM, `posix_spawn 'ps'`), so inside
@@ -135,6 +138,23 @@ export function startedAt(row: PsRow, startMs: number): boolean {
*/
export type ProcessTable = PsRow[] | null;
+/**
+ * Whether `pid` may be a live process, with no `ps`: `kill(pid, 0)`. Only ESRCH proves it
+ * gone; success, EPERM (another user's process) or anything else counts as alive. It
+ * cannot tell a reused pid apart. Measured under `sandbox-exec -p '(version 1)(allow
+ * default)'`: a live process started outside the sandbox → success, a reaped child →
+ * ESRCH, launchd → EPERM, the same as outside it.
+ */
+export function pidMayBeAlive(pid: number): boolean {
+ if (!Number.isInteger(pid) || pid <= 0) return true; // 0 and negatives name groups
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return (e as NodeJS.ErrnoException).code !== "ESRCH";
+ }
+}
+
const PS_ENV = { PATH: "/bin:/usr/bin:/usr/sbin:/sbin", LC_ALL: "C" };
const PS_OPTIONS = { env: PS_ENV, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 } as const;