Skip to content

Commit 46ceb5a

Browse files
tombaldwinclaude
andcommitted
query, mcp, lsp: exit naturally, never process.exit (Node 24 shutdown deadlock)
Follows 128ac34 (scan.mjs). query.mjs: all 91 process.exit sites become qexit(code), which throws a QueryExit; one uncaughtException listener sets process.exitCode and returns, so the process ends naturally (isolate disposed before the platform: no nodejs/node#64274 deadlock). Chosen over a labelled block because query's exits live inside helper functions a label cannot reach; gate-core's GateDone is the same shape and `accepts` already relies on it. Every catch in query.mjs (18) rethrows QueryExit first; the file has no finally and no await. gateCore gets `exit: qexit`. policy.mjs's unreadable-config refusal is shared with scan.mjs and keeps process.exit. mcp.mjs / lsp.mjs: stdin EOF and LSP `exit` call contract.mjs exitNaturally(0): set exitCode, destroy stdin, drain; an unref'd 2 s process.exit fallback fires only if another handle holds the loop open. Measured: both exit in 0.04-0.08 s, code 0. Unit test extended to scan/query/lsp/mcp (named allow-list of remaining process.exit; every query catch guarded); fails on each old file, one at a time. Byte-identity, 91 query invocations (every verb; exit 0 x48, 1 x20, 2 x23; with/without --json): rc, stdout, stderr and --gate-json identical, except `gate --json` over a 34k-function report through a pipe: old = 65,536 bytes, invalid JSON (console.log async + process.exit); new = 1,591,350 bytes, valid. That diff is also the evidence the comparison can fail. Stress reproduction on `query.mjs gate` (old file, --stress-concurrent-allocation, heap 16-192 MB, small and 34k-function reports, ~160 runs): 0 hangs -- NOT reproduced locally; the gate is too light to leave a background compile job parked. The fix is the same mechanism as scan's, whose reproduction stands. npm test (unit 140, behavioural 3812 in 8 shards, MCP 246, LSP 130, watch 16, probe, fuzz) green; ci/self-gate.sh OK. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013jaUYop2PEqPfxttcNWPFx
1 parent 128ac34 commit 46ceb5a

6 files changed

Lines changed: 187 additions & 133 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ report bytes or gate verdicts (regenerate baselines / expect verdict changes acr
2121
Reproduced on macOS with Node 24.13 under `--stress-concurrent-allocation`: 15 of 67 runs hung before, 0 of 67
2222
after. Report bytes, stdout, stderr and exit codes are unchanged on 90 fixture runs (exit 0/1/2, with and
2323
without `--json`).
24+
- **`candor-ts-query` and the MCP and LSP servers no longer exit through `process.exit()` either.** Every query
25+
verb exit is a thrown `QueryExit` that one handler turns into `process.exitCode`, so the process ends naturally;
26+
every `catch` in `query.mjs` rethrows it first, so no handler can swallow an exit. The servers end on stdin EOF
27+
(and LSP `exit`) by closing stdin and draining, with a 2 s unref'd `process.exit` fallback only if some other
28+
handle keeps them alive (measured: they exit in 0.04–0.08 s). The unit test now covers all four entry files and
29+
fails on each old one. Over 91 query invocations (every verb, exit 0/1/2, with and without `--json`), exit code,
30+
stdout, stderr and `--gate-json` files are identical except one: ⚠ **`gate --json` over a large report through
31+
a pipe was truncated at 65,536 bytes (invalid JSON); it is now the whole 1.59 MB document.** `console.log` is
32+
asynchronous on a pipe and `process.exit()` discarded the rest; a natural exit flushes it.
2433
- **The `--workspace` and `--dep-inits` dependency re-scans have a deadline (600 s).** They had none, so one child
2534
that never returned hung the whole scan. On expiry the child is killed, stderr names the dependency, and it is
2635
handled as a dependency that failed to scan: not chained, so its calls read Unknown/invisible.

‎contract.mjs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,16 @@ export function isCandorConfigSink(p) {
167167
const abs = path.resolve(p);
168168
return path.basename(abs) === "config" && path.basename(path.dirname(abs)) === ".candor";
169169
}
170+
171+
// ── A SERVER ENDS NATURALLY, NOT THROUGH `process.exit()` ─────────────────────────────────────────────────────
172+
// `process.exit()` on Node 24 can DEADLOCK in platform shutdown (nodejs/node#64274 — scan.mjs's header, EXIT BY
173+
// FALLING OFF THE END, has the measurement). The MCP and LSP servers ended on stdin EOF (and LSP `exit`) that way,
174+
// after whatever analysis the session ran. Instead: record the code, stop reading stdin, and let the event loop
175+
// drain — the isolate is disposed before the platform, which does not hang, and pending stdout writes flush. The
176+
// unref'd timer is the fallback for a handle this process did not expect to hold open: it does not itself keep
177+
// the process alive, and it only fires if something else does.
178+
export function exitNaturally(code, graceMs = 2000) {
179+
process.exitCode = code;
180+
try { process.stdin.removeAllListeners("data"); process.stdin.destroy(); } catch { /* already closed */ }
181+
setTimeout(() => process.exit(code), graceMs).unref();
182+
}

‎lsp.mjs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import { createRequire } from "node:module";
5050
import nodePath from "node:path";
5151
import { fileURLToPath, pathToFileURL } from "node:url";
5252
import * as Q from "./query-core.mjs";
53+
import { exitNaturally } from "./contract.mjs";
5354
import { discoverConfigPolicy, evaluatePolicy, parsePolicy, scopeMatches, reportNetClasses, parseUnknownAliases, discoverConfigText, policyVocabularyAnchor, policyErrorText, unanswerableScoped, wholePolicyUnanswerable, resolveReasonClasses, fatalPolicyErrors, policyZeroRules, reportUnits, settleAccept } from "./policy.mjs";
5455

5556
// Version: from the sibling package.json when running inside the npm package; a single-file BUNDLE of
@@ -1065,7 +1066,7 @@ function handle(msg) {
10651066
}
10661067
if (method === "shutdown" && activityTimer) clearInterval(activityTimer);
10671068
if (method === "shutdown") return result(id, null);
1068-
if (method === "exit") process.exit(0);
1069+
if (method === "exit") { exiting = true; exitNaturally(0); return; } // see contract.mjs — never process.exit
10691070
if (id !== undefined) error(id, -32601, `method not found: ${method}`);
10701071
}
10711072

@@ -1079,9 +1080,11 @@ function result(id, r) { send({ jsonrpc: "2.0", id, result: r }); }
10791080
function error(id, code, message) { send({ jsonrpc: "2.0", id, error: { code, message } }); }
10801081

10811082
let buf = Buffer.alloc(0);
1083+
let exiting = false; // set by `exit`: the frames after it in the same chunk are not handled
10821084
process.stdin.on("data", (chunk) => {
10831085
buf = Buffer.concat([buf, chunk]);
10841086
for (;;) {
1087+
if (exiting) return;
10851088
const headerEnd = buf.indexOf("\r\n\r\n");
10861089
if (headerEnd < 0) return;
10871090
const header = buf.slice(0, headerEnd).toString("utf8");
@@ -1097,4 +1100,4 @@ process.stdin.on("data", (chunk) => {
10971100
try { handle(msg); } catch (e) { if (msg.id !== undefined) error(msg.id, -32603, e.message); }
10981101
}
10991102
});
1100-
process.stdin.on("end", () => process.exit(0));
1103+
process.stdin.on("end", () => { if (!exiting) { exiting = true; exitNaturally(0); } });

‎mcp.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import nodePath from "node:path";
2121
import * as Q from "./query-core.mjs";
2222
import { accepts as acceptsVerb, reasonOf, noReportMessage } from "./accepts.mjs";
2323
import { runAcceptsGate } from "./gate-core.mjs";
24+
import { exitNaturally } from "./contract.mjs";
2425
import { discoverConfigPolicy, evaluatePolicy, parsePolicy, scopeMatches, reportNetClasses,
2526
parseUnknownAliases, discoverConfigText, policyVocabularyAnchor, policyErrorText,
2627
unanswerableScoped, wholePolicyUnanswerable, resolveReasonClasses, fatalPolicyErrors, reportUnits,
@@ -1090,4 +1091,4 @@ process.stdin.on("data", (chunk) => {
10901091
try { handle(msg); } catch (e) { if (msg.id !== undefined) error(msg.id, -32603, e.message); }
10911092
}
10921093
});
1093-
process.stdin.on("end", () => process.exit(0));
1094+
process.stdin.on("end", () => exitNaturally(0)); // see contract.mjs — never process.exit

0 commit comments

Comments
 (0)