Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(pane): treat a refused pane socket as stale only when its magmux is dead
Jack Rudenkoa7f3d9320817
diff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.tsindex 5eb21605..d7c9cce2 100644--- a/packages/cli/src/pane/pane-registry.test.ts+++ b/packages/cli/src/pane/pane-registry.test.ts@@ -56,6 +56,7 @@ import {isPaneRecordPath,isPaneSockPath,isPaneWatcherCommand,+ magmuxNeedle,pidMayBeAlive,recordPathOf,sockPathOf,@@ -783,7 +784,7 @@ describe("with the process table unavailable (a sandbox refuses ps): owners judgownerPid,ownerStart: owner === "live" ? ownerStartOfSelf() : "",watcherPid: null,- magmuxPid: null,+ magmuxPid: owner === "dead" ? deadPid() : null, // a dead owner's magmux died with itpanePid: null,sessionUuid: crypto.randomUUID(),sockPath: sockPathOf(root, paneId),@@ -858,7 +859,23 @@ describe("with the process table unavailable (a sandbox refuses ps): owners judgfor (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 () => {+ test("a dead owner's refused socket whose magmux pid may be alive, or was never recorded: kept", async () => {+ // a LIVE listener with a full accept queue refuses too (darwin); only a dead pid proves it gone+ for (const magmuxPid of [process.pid, null]) {+ const t = env();+ const rec = await ownerPane(t, "dr", "dead");+ updateRecord(t.sockRoot, rec.paneId, { magmuxPid });+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(t.sockRoot));+ expect({ magmuxPid, r }).toEqual({+ magmuxPid,+ r: { reaped: [], cleaned: [], kept: [rec.paneId] },+ });+ for (const p of filesOf(rec)) expect(existsSync(p)).toBe(true);+ }+ });++ test("recordless sockets without a table: a live owner's is left alone; a dead owner's are kept, live or refused", async () => {+ // no table names the pane's magmux, so a refusal proves nothing about itconst t = env();const root = ensureSockRoot(t.sockRoot);const gone = deadPid();@@ -870,12 +887,15 @@ describe("with the process table unavailable (a sandbox refuses ps): owners judgtry {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(r.kept.sort()).toEqual([+ `c${gone}-${OWNER_START36}-tdl-abcdef`,+ `c${gone}-${OWNER_START36}-tdr-abcdef`,+ ]);+ expect(r.cleaned).toEqual([]);expect([ownLive, deadLive, deadRefused].map((p) => existsSync(p))).toEqual([true,true,- false,+ true,]);} finally {for (const s of servers) s.close();@@ -913,7 +933,8 @@ describe("with the process table unavailable (a sandbox refuses ps): owners judg}}, 30_000);- test("a dead owner's recordless socket: an inconclusive probe keeps it, a stale one removes it", async () => {+ test("a dead owner's recordless socket without a table: only ENOENT removes it", async () => {+ // no table names its magmux, so ECONNREFUSED is inconclusive herefor (const code of [...INCONCLUSIVE, ...STALE]) {const t = env();const root = ensureSockRoot(t.sockRoot);@@ -923,7 +944,7 @@ describe("with the process table unavailable (a sandbox refuses ps): owners judgconst r = await withDialError(code, () =>withProcessTableUnavailable(() => sweepOrphanPanes(root)));- const removed = STALE.includes(code);+ const removed = code === "ENOENT";expect({ code, kept: r.kept, cleaned: r.cleaned }).toEqual({code,kept: removed ? [] : [id],@@ -934,7 +955,7 @@ describe("with the process table unavailable (a sandbox refuses ps): owners judg}, 30_000);});-describe("the pane-socket probe: only ECONNREFUSED and ENOENT prove a socket stale", () => {+describe("the pane-socket probe: ENOENT, or ECONNREFUSED with magmux proven dead, is stale", () => {test("real sockets: live → answers; refused or missing → stale; mode 000 or a plain file → inconclusive", async () => {const t = env();const root = ensureSockRoot(t.sockRoot);@@ -949,25 +970,59 @@ describe("the pane-socket probe: only ECONNREFUSED and ENOENT prove a socket staconst plain = join(root, "magmux-plain.sock");writeFileSync(plain, "");try {- const answers = await probeSocket(live);+ const answers = await probeSocket(live, true);expect(answers.state).toBe("answers");if (answers.state === "answers") answers.client.close();- expect(await probeSocket(refused)).toEqual({ state: "stale", code: "ECONNREFUSED" });- expect(await probeSocket(join(root, "magmux-none.sock"))).toEqual({+ expect(await probeSocket(refused, false)).toEqual({ state: "stale", code: "ECONNREFUSED" });+ expect(await probeSocket(join(root, "magmux-none.sock"), true)).toEqual({state: "stale",code: "ENOENT",});- expect(await probeSocket(locked)).toEqual({ state: "inconclusive", code: "EACCES" });- expect(await probeSocket(plain)).toEqual({ state: "inconclusive", code: "ENOTSOCK" });+ expect(await probeSocket(locked, false)).toEqual({ state: "inconclusive", code: "EACCES" });+ expect(await probeSocket(plain, false)).toEqual({ state: "inconclusive", code: "ENOTSOCK" });} finally {for (const s of servers) s.close();}}, 20_000);+ test("ECONNREFUSED while the pane's magmux may live is inconclusive", async () => {+ // darwin refuses a LIVE listener whose accept queue is full (magmux sockdir.go ReapStale)+ const prev = setSocketDialForTest(() =>+ Promise.reject(new MagmuxConnectError("connect ECONNREFUSED", "ECONNREFUSED"))+ );+ try {+ expect(await probeSocket("/nonexistent/magmux-busy.sock", true)).toEqual({+ state: "inconclusive",+ code: "ECONNREFUSED",+ });+ } finally {+ setSocketDialForTest(prev);+ }+ });++ test("with a readable table, a dead owner's refused recordless socket: kept while a magmux for its id runs, removed once none does", async () => {+ const t = env();+ const root = ensureSockRoot(t.sockRoot);+ const id = `c${deadPid()}-${OWNER_START36}-trf-abcdef`;+ const sock = sockPathOf(root, id);+ await staleSocket(sock);+ // a process whose argv carries the pane's magmux needle, as a busy magmux's would+ const mag = Bun.spawn(["/bin/sh", "-c", "sleep 30; true", "sh", magmuxNeedle(id)]);+ try {+ expect(await sweepOrphanPanes(root)).toEqual({ reaped: [], cleaned: [], kept: [id] });+ expect(existsSync(sock)).toBe(true);+ } finally {+ mag.kill("SIGKILL");+ await mag.exited;+ }+ expect(await sweepOrphanPanes(root)).toEqual({ reaped: [], cleaned: [id], kept: [] });+ expect(existsSync(sock)).toBe(false);+ }, 20_000);+test("a dial that never settles is inconclusive", async () => {const prev = setSocketDialForTest(() => new Promise<never>(() => {}));try {- expect(await probeSocket("/nonexistent/magmux-x.sock")).toEqual({+ expect(await probeSocket("/nonexistent/magmux-x.sock", false)).toEqual({state: "inconclusive",code: "ETIMEDOUT",});diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.tsindex 38bd91a9..83ed3244 100644--- a/packages/cli/src/pane/pane-registry.ts+++ b/packages/cli/src/pane/pane-registry.ts@@ -517,20 +517,20 @@ async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Pro/*** What one connection attempt says about a pane socket:* - `answers`: the connect succeeded; some magmux serves it (the caller owns `client`);- * - `stale`: ECONNREFUSED or ENOENT, nothing listens there;- * - `inconclusive`: any other error (EPERM, EACCES, EMFILE, ENFILE, ...) or no answer- * within `SOCKET_PROBE_TIMEOUT_MS`; says nothing about the listener, so files stay.+ * - `stale`: ENOENT, or ECONNREFUSED while the caller has proved the pane's magmux dead;+ * - `inconclusive`: any other error (EPERM, EACCES, EMFILE, ENFILE, ...), ECONNREFUSED+ * while that magmux may live, or no answer within `SOCKET_PROBE_TIMEOUT_MS`; says+ * nothing about the listener, so files stay.*- * Known darwin limit (magmux `sockdir.go`): a LIVE listener whose accept queue is full- * answers ECONNREFUSED. Every caller probes only after the owner is proven dead, so the- * remaining risk is a dead owner's still-running magmux with a full backlog read as stale.+ * ECONNREFUSED alone is not proof: on darwin a LIVE listener whose accept queue is full+ * answers it (measured, magmux `sockdir.go` ReapStale), which is why magmux reaps by pid.+ * So the caller passes `magmuxMayLive`, its own pid evidence for the pane's magmux.*/export type SocketProbe =| { state: "answers"; client: MagmuxClient }| { state: "stale"; code: string }| { state: "inconclusive"; code: string };-const STALE_SOCKET_CODES = new Set(["ECONNREFUSED", "ENOENT"]);const SOCKET_PROBE_TIMEOUT_MS = 2000;let dialSocket: (sockPath: string) => Promise<MagmuxClient> = (p) => MagmuxClient.dial(p);@@ -545,7 +545,7 @@ export function setSocketDialForTest(}/** THE pane-socket probe, for the record sweep and the recordless-socket sweep. */-export async function probeSocket(sockPath: string): Promise<SocketProbe> {+export async function probeSocket(sockPath: string, magmuxMayLive: boolean): Promise<SocketProbe> {const dial = dialSocket(sockPath);let timer: ReturnType<typeof setTimeout> | undefined;const timeout = new Promise<"timeout">((resolve) => {@@ -561,9 +561,8 @@ export async function probeSocket(sockPath: string): Promise<SocketProbe> {return { state: "inconclusive", code: "ETIMEDOUT" };} catch (e) {const code = (e as { errno?: string | null; code?: string }).errno ?? "unknown";- return STALE_SOCKET_CODES.has(code)- ? { state: "stale", code }- : { state: "inconclusive", code };+ const stale = code === "ENOENT" || (code === "ECONNREFUSED" && !magmuxMayLive);+ return stale ? { state: "stale", code } : { state: "inconclusive", code };} finally {clearTimeout(timer);}@@ -574,8 +573,8 @@ export async function probeSocket(sockPath: string): Promise<SocketProbe> {* No process can be identified, so nothing is signalled. A watcher pid that may be alive* may be mid-job, and a socket that answers (a live magmux) or whose probe is* inconclusive may still be served: each keeps the files, and the pane is left running- * for a sweep that can read the table. Only a stale socket (`probeSocket`) means the- * pane's magmux is gone; then its files are removed, as the dead-owner path does when+ * for a sweep that can read the table. Only a stale socket (`probeSocket`, with the+ * recorded magmux pid as its evidence) means the pane's magmux is gone; then its files are removed, as the dead-owner path does when* nothing is verified alive.*/async function sweepUnidentifiable(rec: PaneRecord, root: string, out: SweepResult) {@@ -583,7 +582,9 @@ async function sweepUnidentifiable(rec: PaneRecord, root: string, out: SweepResuout.kept.push(rec.paneId);return;}- const probe = await probeSocket(sockPathOf(root, rec.paneId));+ // no recorded pid: the owner died before it recorded magmux, which may still be starting+ const magmuxMayLive = rec.magmuxPid === null || pidMayBeAlive(rec.magmuxPid);+ const probe = await probeSocket(sockPathOf(root, rec.paneId), magmuxMayLive);if (probe.state !== "stale") {if (probe.state === "answers") probe.client.close();out.kept.push(rec.paneId);@@ -612,7 +613,9 @@ async function sweepRecordlessSocket(root: string, name: string, out: SweepResulconst owner = ownerOfSocketId(id);if (!owner || ownerAlive(owner, table)) return; // no owner in the id: not ours to judgeconst sockPath = join(root, name);- const probe = await probeSocket(sockPath);+ // the table names the pane's magmux; without it no pid is known for a recordless socket+ const magmuxMayLive = !table || table.some((r) => isPaneMagmuxCommand(r.command, id));+ const probe = await probeSocket(sockPath, magmuxMayLive);if (probe.state === "stale") {rmSync(sockPath, { force: true });out.cleaned.push(id);