Skip to content

Commit 294a1d6

Browse files
tombaldwinclaude
andcommitted
No process.exit() after analysis in policy, verify and watch (Node 24 shutdown deadlock, nodejs/node#64274)
policy.mjs's unreadable-config refusal throws PolicyExit (QueryExit inside query); verify.mjs ends through a thrown VerifyExit; watch.mjs's SIGINT/SIGTERM stop exits naturally. The unit test now pins policy, verify, watch, accepts, gate-core and contract too. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013jaUYop2PEqPfxttcNWPFx
1 parent d063caf commit 294a1d6

9 files changed

Lines changed: 84 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,20 @@ report bytes or gate verdicts (regenerate baselines / expect verdict changes acr
1010

1111
## Unreleased
1212

13+
- **No more `process.exit()` after analysis in `policy.mjs`, `verify.mjs` and `watch.mjs` (Node 24 shutdown deadlock,
14+
nodejs/node#64274; the same fix 0.41.2 made for `scan.mjs`, `query.mjs`, `mcp.mjs` and `lsp.mjs`).** `policy.mjs`'s
15+
unreadable-`.candor/config` refusal (exit 2) is reached after analysis, when `scan --policy` resolves the policy's
16+
config vocabulary and when a `query` verb reads it; it now throws a `PolicyExit` (a `QueryExit` inside `query`) that
17+
the entry file records as `process.exitCode`. `candor-ts-verify` ends every verdict (0/1/2, `--json`, syscall mode)
18+
through a thrown `VerifyExit`, and `candor-ts-watch`'s SIGINT/SIGTERM stop clears its timer and exits 0 naturally.
19+
Left alone, on purpose: usage errors in `watch.mjs` (before the first scan), the engine-pin and config-load refusals
20+
in `scan.mjs` (before analysis), the MCP/LSP servers' use of the policy refusal (they only read reports, their request
21+
handlers would turn a thrown error into a reply, so they keep `process.exit`), and the repo's own harness scripts
22+
(`fuzz`, `check`, `sensitivity`, ... run scans as child processes). Stdout, stderr, exit codes and the
23+
`--gate-json` / report files are byte-identical on 27 fixture runs (exit 0/1/2, `--json`, a 1.09 MB `gate --json`
24+
through a pipe). The unit test now covers `policy`, `verify`, `watch`, `accepts`, `gate-core` and `contract` as
25+
well, and fails on a seeded `process.exit` in each.
26+
1327
## [0.41.3] — 2026-11-06
1428

1529
- **No change to candor-ts.** The version moves with the 0.41.3 family patch (a candor-java fix).

‎accepts.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ export function noReportMessage({ locator = null, fromDir = ".", mcp = false } =
334334
const m = raw.split("#", 1)[0].trim().match(/^(\S+)\s*(.*)$/);
335335
if (m && m[1].toLowerCase() === "baseline" && m[2].trim()) { base = m[2].trim(); break; }
336336
}
337-
} catch { /* best effort: a config that cannot be read is named by the gate, not here */ }
337+
} catch (e) { if (e?.candorExit) throw e; /* best effort: a config that cannot be read is named by the gate, not here */ }
338338
}
339339
const cur = ".candor/report";
340340
let m = `candor-ts accepts: no report to judge — no report files found${locator ? ` at \`${locator}\`` : ""} (and no --report / CANDOR_REPORT).\n`

‎contract.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,5 +178,5 @@ export function isCandorConfigSink(p) {
178178
export function exitNaturally(code, graceMs = 2000) {
179179
process.exitCode = code;
180180
try { process.stdin.removeAllListeners("data"); process.stdin.destroy(); } catch { /* already closed */ }
181-
setTimeout(() => process.exit(code), graceMs).unref();
181+
setTimeout(function fallbackExit() { process.exit(code); }, graceMs).unref();
182182
}

‎policy.mjs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1776,10 +1776,35 @@ function readConfigOrRefuse(p, via = null) {
17761776
+ `— failing (exit 2, unevaluable). A config that cannot be read is a guard the operator believes `
17771777
+ `is on: it may name a policy, a baseline or an engine pin, and treating it as absent would run `
17781778
+ `without them.`);
1779-
process.exit(2);
1779+
exitRefusal(2);
17801780
}
17811781
}
17821782

1783+
// ── THE UNREADABLE-CONFIG REFUSAL EXITS NATURALLY WHERE THE CALLER CAN, NEVER `process.exit()` THERE ────────────
1784+
// This refusal is reached from code that runs AFTER analysis (scan.mjs resolves the policy's `.candor/config`
1785+
// vocabulary while it writes the verdict; `query` verbs read it with a loaded report), and `process.exit()` on
1786+
// Node 24 can DEADLOCK in platform shutdown (nodejs/node#64274 — scan.mjs's header, EXIT BY FALLING OFF THE END,
1787+
// has the measurement). So it THROWS a `PolicyExit` (`candorExit` is the marker for "this is an exit, not an
1788+
// error": catch sites that must not swallow one test it) and the entry file's top-level handler records the code
1789+
// and returns. An entry file whose catches cannot be audited for that (query.mjs: a `QueryExit` is already
1790+
// rethrown by every catch there) installs `onPolicyExit` so the refusal arrives as ITS exit type. The MCP and LSP
1791+
// servers install nothing and keep `process.exit`: they only read reports (analysis runs in child processes
1792+
// that exit on their own), and their request handlers answer a thrown error with a JSON-RPC reply — converting
1793+
// would keep the server alive and add bytes where it used to end.
1794+
export class PolicyExit extends Error {
1795+
constructor(code) { super("candor-ts policy exit"); this.code = code; this.candorExit = true; }
1796+
}
1797+
let policyExitHook = null;
1798+
export function onPolicyExit(fn) { policyExitHook = fn; }
1799+
function exitRefusal(code) {
1800+
if (policyExitHook) policyExitHook(code); // must throw
1801+
if (policyExitMode === "throw") throw new PolicyExit(code);
1802+
process.exit(code);
1803+
}
1804+
let policyExitMode = "exit";
1805+
/** `"throw"`: refusals throw a `PolicyExit` for the entry file's handler (scan.mjs). Default `"exit"` (servers). */
1806+
export function policyExitsThrow() { policyExitMode = "throw"; }
1807+
17831808
export function discoverConfigPath(fromDir) {
17841809
const env = process.env.CANDOR_CONFIG;
17851810
if (env) { readConfigOrRefuse(env, "CANDOR_CONFIG"); return nodePath.resolve(env); }

‎query.mjs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { fileURLToPath } from "node:url";
2626
import { parsePolicy, scopeMatches, discoverConfigPolicy, parseUnknownAliases, discoverConfigText,
2727
evaluatePolicy, reportNetClasses, resolveReasonClasses, discoverConfigPath,
2828
policyVocabularyAnchor, policyErrorText, policyUnreadable, policyZeroRules,
29-
fatalPolicyErrors, refusalVerdict, unanswerableScoped, wholePolicyUnanswerable, reportUnits, acceptedUnitsOver, acceptReviewOver, } from "./policy.mjs";
29+
fatalPolicyErrors, refusalVerdict, unanswerableScoped, wholePolicyUnanswerable, reportUnits, acceptedUnitsOver, acceptReviewOver, onPolicyExit, } from "./policy.mjs";
3030
import { accepts as acceptsVerb, reasonOf, noReportMessage } from "./accepts.mjs";
3131
import { gateCore, runAcceptsGate } from "./gate-core.mjs";
3232
import { hasReport, refusalMarkerFor, refusalSentence } from "./query-core.mjs";
@@ -1281,10 +1281,11 @@ const usage = () => {
12811281
// listener below records the code and RETURNS, and the process ends naturally — the isolate is disposed before the
12821282
// platform, which does not hang. Every `catch` in this file rethrows a QueryExit first, so no handler can swallow
12831283
// an exit and carry on; this file has no `finally` and no `await`, so nothing else runs on the way out. The same
1284-
// shape as gate-core's `GateDone`, which `accepts` already relies on. `policy.mjs`'s unreadable-config refusal is
1285-
// shared with scan.mjs (whose catches do not rethrow) and keeps its `process.exit`.
1286-
class QueryExit extends Error { constructor(code) { super("candor-ts-query exit"); this.code = code; } }
1284+
// shape as gate-core's `GateDone`, which `accepts` already relies on. `policy.mjs`'s unreadable-config refusal reaches
1285+
// here through `onPolicyExit(qexit)` below, so it is a QueryExit too.
1286+
class QueryExit extends Error { constructor(code) { super("candor-ts-query exit"); this.code = code; this.candorExit = true; } }
12871287
const qexit = (code) => { throw new QueryExit(code); };
1288+
onPolicyExit(qexit); // policy.mjs's unreadable-config refusal arrives as a QueryExit, which every catch here rethrows
12881289
process.on("uncaughtException", (e) => {
12891290
if (e instanceof QueryExit) { if (e.code !== undefined) process.exitCode = e.code; return; }
12901291
console.error(e?.stack ?? String(e)); // anything else is a crash: say so and exit 1, naturally

‎scan.mjs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import { createRequire } from "node:module";
2929
import { execFileSync } from "node:child_process";
3030
import os from "node:os";
3131
import { parsePolicy, evaluatePolicy, scopeMatches, parseUnknownAliases, parseNetPartners, discoverConfigText,
32-
reasonClass, discoverConfigPath, policyVocabularyAnchor, policyErrorText, policyRefusalUnevaluated, policyUnreadable, policyZeroRules, fatalPolicyErrors, refusalVerdict, sortViolations,
32+
reasonClass, discoverConfigPath, PolicyExit, policyExitsThrow, policyVocabularyAnchor, policyErrorText, policyRefusalUnevaluated, policyUnreadable, policyZeroRules, fatalPolicyErrors, refusalVerdict, sortViolations,
3333
netClassResolver, resolveReasonClasses, noteSyntheticHits, settleAccept, announceAccepted } from "./policy.mjs";
3434
import { unverifiedHoleRule, ruleUpgrade, canonicalDenySet, byCodePoint, claimsToHaveJudgedNothing, reportCorruptKeys, entryCorruptKeys } from "./query-core.mjs";
3535
import { printAgents, writeStdoutSync, writeSinkAtomic, resolveSinkArtifact, isCandorConfigSink } from "./contract.mjs";
@@ -99,7 +99,9 @@ const SPEC_VERSION = "0.41";
9999
// engine can walk", and nothing here can tell the two apart. It stays LOUD either way — exit 2, no
100100
// report, never a green — so the cost is a misleading message, not a wrong verdict. If this message
101101
// ever appears on a SHALLOW tree, the message is the bug and the recursion is where to look.
102+
policyExitsThrow(); // policy.mjs's unreadable-config refusal throws a PolicyExit instead of process.exit()
102103
process.on("uncaughtException", (e) => {
104+
if (e instanceof PolicyExit) { process.exitCode = e.code; return; } // the refusal already said why on stderr
103105
if (e instanceof RangeError && /Maximum call stack/i.test(e?.message ?? "")) {
104106
console.error("candor-ts: this tree nests deeper than the engine can walk — the AST passes recurse, "
105107
+ "and the JS stack ran out before the scan finished. NOTHING was analyzed and no report was "

‎test-unit.mjs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1961,7 +1961,8 @@ test("⟨0.41⟩ accept: this engine's positional spellings are refused, a decla
19611961
assert.equal(positionalKey(k), false, k);
19621962
});
19631963

1964-
// EXIT WITHOUT process.exit (scan.mjs, query.mjs, lsp.mjs, mcp.mjs). On Node 24 `process.exit()` can deadlock in
1964+
// EXIT WITHOUT process.exit (scan.mjs, query.mjs, lsp.mjs, mcp.mjs, and the shipped modules that run after them:
1965+
// policy.mjs, verify.mjs, watch.mjs, accepts.mjs, gate-core.mjs, contract.mjs). On Node 24 `process.exit()` can deadlock in
19651966
// platform shutdown — a background worker parked for a GC the joining main thread will never run (nodejs/node#64274)
19661967
// — and candor-spec CI hung on it in PARTs 38, 98 and 104. scan.mjs ends through `{ process.exitCode = N; break
19671968
// scan; }`, query.mjs through a thrown QueryExit, the servers through contract.mjs `exitNaturally`. A
@@ -1970,6 +1971,14 @@ test("⟨0.41⟩ accept: this engine's positional spellings are refused, a decla
19701971
const ENTRY_EXITS = {
19711972
"scan.mjs": ["enforceEnginePin", "loadCandorConfig"], // pre-analysis refusals: engine pin, config load
19721973
"query.mjs": [], "lsp.mjs": [], "mcp.mjs": [],
1974+
// policy.mjs's unreadable-config refusal is reached AFTER analysis (scan.mjs resolving the policy's config
1975+
// vocabulary, query verbs with a loaded report): it throws a PolicyExit / QueryExit, and `exitRefusal` keeps the
1976+
// `process.exit` ONLY for the MCP/LSP servers, which install neither (see the comment there).
1977+
"policy.mjs": ["exitRefusal"],
1978+
"verify.mjs": [], // every exit is a thrown VerifyExit
1979+
"watch.mjs": ["main"], // usage errors, before the first scan; the SIGINT/SIGTERM stop exits naturally
1980+
"accepts.mjs": [], "gate-core.mjs": [],
1981+
"contract.mjs": ["fallbackExit"], // the unref'd 2 s fallback timer in exitNaturally
19731982
};
19741983
test("entry files: no process.exit outside the named pre-analysis functions; query.mjs catches cannot swallow an exit", async () => {
19751984
const ts = (await import("typescript")).default;

‎verify.mjs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,25 @@ import { parseTrace, programCheck } from "./verify-syscall.mjs";
2323

2424
const HERE = path.dirname(fileURLToPath(import.meta.url));
2525

26+
// ── EVERY EXIT IS A THROWN VerifyExit, NEVER `process.exit()` ───────────────────────────────────────────────────
27+
// `process.exit()` on Node 24 can DEADLOCK in platform shutdown (nodejs/node#64274 — scan.mjs's header, EXIT BY
28+
// FALLING OFF THE END, has the measurement). This process loads a report and then judges what `--run` observed, so
29+
// its verdict exits (0 / 1 / 2) run after the heavy work. Same shape as query.mjs: the listener records the code and
30+
// RETURNS, the module has no `finally` and no `await`, and nothing else runs on the way out. The one `catch` that
31+
// can sit around an exit (the trace-file reads) does not call one.
32+
class VerifyExit extends Error { constructor(code) { super("candor-ts-verify exit"); this.code = code; } }
33+
const vexit = (code) => { throw new VerifyExit(code); };
34+
process.on("uncaughtException", (e) => {
35+
if (e instanceof VerifyExit) { process.exitCode = e.code; return; }
36+
console.error(e?.stack ?? String(e)); // anything else is a crash: say so and exit 1, naturally
37+
process.exitCode = 1;
38+
});
39+
2640
function usage(msg) {
2741
if (msg) console.error(`candor verify: ${msg}`);
2842
console.error('usage: candor-ts-verify [<dir>] --run "<cmd>" [--report <prefix>] [--scope direct|all] [--json]');
2943
console.error(' or: candor-ts-verify [<dir>] --syscall-trace <file> [--trace-format strace|dtruss] [--report <prefix>] [--json]');
30-
process.exit(2);
44+
vexit(2);
3145
}
3246

3347
const argv = process.argv.slice(2);
@@ -97,7 +111,7 @@ if (syscallTrace) {
97111
console.log(` effects candor reports : { ${r.reportUnion.join(", ") || "none"} }${r.disclosedUnknown ? " (+ Unknown disclosed)" : ""}`);
98112
if (r.escaped.length) console.log(` ✘ ESCAPED (ran, candor claims nowhere): { ${r.escaped.join(", ")} }`);
99113
}
100-
process.exit(r.escaped.length ? 1 : 0);
114+
vexit(r.escaped.length ? 1 : 0);
101115
}
102116

103117
// A fresh trace file + the capture preload wired via NODE_OPTIONS so EVERY node subprocess of --run
@@ -178,4 +192,4 @@ if (wantJson) {
178192
}
179193
}
180194

181-
process.exit(violations.length ? 1 : (attributionIncomplete ? 2 : 0));
195+
vexit(violations.length ? 1 : (attributionIncomplete ? 2 : 0));

‎watch.mjs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ async function main() {
101101
console.error(`candor-ts-watch: ${Object.keys(prev).length} source(s) → ${out}.json (${first.ms}ms). Watching… (Ctrl-C to stop)`);
102102
if (!first.ok) console.error(first.stderr?.trim());
103103

104-
setInterval(() => {
104+
const timer = setInterval(() => {
105105
const cur = hashFiles(trackedFiles(target));
106106
const changed = changedFiles(prev, cur);
107107
if (!changed.length) return; // the freshness gate: nothing relevant changed, do nothing
@@ -127,7 +127,12 @@ async function main() {
127127
// instrumented with NODE_V8_COVERAGE discards its coverage (the TESTING.md §6 flush rule — this made
128128
// the live loop measure 0% while actually exercised). Handle both: announce, exit 0.
129129
for (const sig of ["SIGINT", "SIGTERM"]) {
130-
process.on(sig, () => { console.error(`candor-ts-watch: ${sig} — stopping`); process.exit(0); });
130+
process.on(sig, () => {
131+
console.error(`candor-ts-watch: ${sig} — stopping`);
132+
// Stop the only handle keeping the loop alive and let the process end NATURALLY, exit code 0: `process.exit()`
133+
// can deadlock in Node 24 platform shutdown (nodejs/node#64274 — scan.mjs's header, EXIT BY FALLING OFF THE END).
134+
process.exitCode = 0; clearInterval(timer);
135+
});
131136
}
132137
}
133138

0 commit comments

Comments
 (0)