From ae3c261ea334b16f077af0650b1347e6e55d432c Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 05:06:30 -0500 Subject: [PATCH 1/3] test(javascript): the cap-0 release test accepts the engine's own crash on a Node without the fix; the guide says what a release can cost Issue #1119: a fork released with the child-session cap at 0 sometimes died with an access violation, and the test expected a clean exit. The crash is Node's (nodejs/node#64209: the inspector writes to a socket the release's detach has just closed), fixed in 24.19.0 and 26.5.0 and in no 22.x release. Three server-side workarounds were built or designed and none was safe, so the server does not change. - The test requires exit 0 on a Node with the fix. On one without it, it accepts 0 or exactly the engine's crash: the launch's exit code for an access violation on Windows (0xC0000005, unsigned or signed), or 1 elsewhere with the fixture naming a memory-fault signal for its fork. A tolerated crash prints a warning. - The fixture names the signal when its fork was killed by one. - The JavaScript guide no longer says a cap of 0 leaves children untouched, and says what a release can cost on which Node and how to avoid releases. Measured here on Node 24.14.1, six runs at a time: 30 runs, 2 crashes (launch exit code -1073741819), all 30 passed. Helper, test and guide written by a GPT model; the signed exit code, the signal check and the changelog entry are the manager session's. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1119.fixed.md | 1 + docs/javascript/README.md | 22 ++++++-- .../javascript-subprocess-tree.test.ts | 50 ++++++++++++++++--- .../javascript/subprocess-tree/parent.js | 5 +- .../helpers/node-inspector-version.ts | 9 ++++ .../test-utils/node-inspector-version.test.ts | 31 ++++++++++++ 6 files changed, 106 insertions(+), 12 deletions(-) create mode 100644 changelog.d/1119.fixed.md create mode 100644 tests/test-utils/helpers/node-inspector-version.ts create mode 100644 tests/unit/test-utils/node-inspector-version.test.ts diff --git a/changelog.d/1119.fixed.md b/changelog.d/1119.fixed.md new file mode 100644 index 000000000..2128818a0 --- /dev/null +++ b/changelog.d/1119.fixed.md @@ -0,0 +1 @@ +**The JavaScript guide no longer says that a child-session cap of 0 leaves child processes untouched** — with `DEBUG_MCP_MAX_CHILD_SESSIONS=0` every fork is still attached and then released, and the guide now says what a release can cost: on a Node without the inspector fix `nodejs/node#64209` (it is in 24.19.0, 26.5.0 and from 27; no 22.x release carries it) a released child can die with an access violation, measured at 44 of 259 releases on Node 24.14.1 and 13 of 256 on 22.23.5 on one Windows machine; and on any Node a child that is starting worker threads when the debugger detaches can be left with a worker that waits for a debugger and never runs. To avoid releases, raise the cap to cover the children, or pass `dapLaunchArgs: { autoAttachChildProcesses: false }`, which stops child processes from being followed at all. No server behaviour changes: three workarounds were built or designed, and none was safe. (#1119) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 44bf565e2..e9d09520d 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -351,10 +351,24 @@ The program's own process gains from the same change: a logpoint on its first st go out through its `console.log` (measured on an ES module: the line arrived as `stdout` in 12 of 12 runs, the binding not yet in), and is now delivered on the debugger's channel. -Opt out per launch with `dapLaunchArgs: { autoAttachChildProcesses: false }` or server-wide with -`DEBUG_MCP_MAX_CHILD_SESSIONS=0` (the program's own target is still adopted; every fork is released -to run undebugged). Opted out, the children run as they did before the session tree: untouched by the -debugger, their output on the parent's buffer where the parent's pipes carry it. +A release detaches the debugger from a child so it can run undebugged; a child beyond +`DEBUG_MCP_MAX_CHILD_SESSIONS` is released by a throwaway attach followed immediately by a detach. +On Node without [nodejs/node#64209](https://github.com/nodejs/node/pull/64209), a released child can +die with an access violation when the debugger detaches while the child's inspector is writing. +The fix is in Node 24 from 24.19.0, Node 26 from 26.5.0, and Node 27 and later; no Node 22 release +carries it (22.23.5 is the newest), and Node 25 ended without it. Measured through the server on +one Windows machine with issue #1119's child: 44 of 259 releases on Node 24.14.1 crashed, and +13 of 256 on Node 22.23.5. + +On any Node version, releasing a child that is starting worker threads at detach can leave a +worker waiting for a debugger and never running: measured at engine level, a worker parked by +the inspector stays parked after the debugger disconnects (#1119). + +Avoid releases by raising `DEBUG_MCP_MAX_CHILD_SESSIONS` to cover the children, or pass +`dapLaunchArgs: { autoAttachChildProcesses: false }` to stop following child processes at all. +Setting `DEBUG_MCP_MAX_CHILD_SESSIONS=0` still adopts the program's own target and releases every +fork; it does not avoid these detach limits. With child following off, their output is on the +parent's buffer where the parent's pipes carry it. ```javascript // parent.js diff --git a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts index ca03fa02e..006e751df 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts @@ -18,6 +18,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; +import { hasInspectorSocketCrashFix } from '../../../test-utils/helpers/node-inspector-version.js'; const root = fileURLToPath(new URL('../../../../', import.meta.url)); const treeDir = path.join(root, 'tests/fixtures/javascript/subprocess-tree'); @@ -335,8 +336,8 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect((await call('set_breakpoint', { file: childFixture, line: CHILD_BREAKPOINT_LINE })).success).toBe(true); const started = await launch(parentFixture); - // No child session, no stop: the fork runs undebugged to its end and the - // parent ends with it — inside the launch hold on a fast box, so the + // No child session, no stop: the parent ends when the released fork exits + // (normally or in the engine crash below) — inside the launch hold on a fast box, so the // launch answer itself may be the end. const ended = started.state === 'stopped' ? started : await call('wait_for_stop', { sessionId: rootId, timeout: 30000 }); expect(ended.state, JSON.stringify(ended)).toBe('stopped'); @@ -344,15 +345,38 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(ended.sessionId).toBe(rootId); } // A launch answer carries the exit code under `data`; a wait answer hoists it. - expect(ended.exitCode ?? (ended as { data?: { exitCode?: number } }).data?.exitCode, JSON.stringify(ended)).toBe(0); + const exitCode = ended.exitCode ?? (ended as { data?: { exitCode?: number } }).data?.exitCode; + // Which Node runs the debuggee: this .js launch names no runtime, so the + // adapter uses the Node that runs the server (startStdioClient starts it + // with process.execPath), and parent.js's fork inherits it. process.version + // is the debuggee's version. + // + // Issue #1119: on a Node without nodejs/node#64209 (in 24.19.0, 26.5.0 and + // from 27), the inspector can crash when it writes to its socket just after + // the release's detach closed it. That is the engine's defect, and no + // server-side workaround was found that is safe. The fork then dies of an + // access violation (Windows) or of a fatal signal (elsewhere), and + // parent.js ends with the fork's exit code, or with 1 when a signal killed + // it. Windows reports 0xC0000005 unsigned or as a signed 32-bit number. + const WINDOWS_ACCESS_VIOLATION = 0xC0000005; + const engineCrashExitCodes = process.platform === 'win32' + ? [WINDOWS_ACCESS_VIOLATION, WINDOWS_ACCESS_VIOLATION | 0] + : [1]; + if (hasInspectorSocketCrashFix(process.version)) { + expect(exitCode, JSON.stringify(ended)).toBe(0); + } else { + expect([0, ...engineCrashExitCodes], JSON.stringify(ended)).toContain(exitCode); + } expect(ended.childrenReleased, JSON.stringify(ended)).toBe(1); expect(ended.children).toBeUndefined(); // The count is explained where it appears (issue #1137): what it means, - // that the fork ran undebugged, and which setting decided it — so "without + // that the fork was released, and which setting decided it — so "without // hitting any breakpoint" no longer reads as a wrong breakpoint. const RELEASED = '1 child process was released to run undebugged (child sessions are off: DEBUG_MCP_MAX_CHILD_SESSIONS=0): ' + 'a breakpoint only it reaches will not hit.'; + // "to run undebugged" describes the release's intent, not proof the child + // survived the engine's detach. Keep checking the server's exact wording. expect(JSON.stringify(ended)).toContain(RELEASED); // A launch that answered while the program was still running promised a // pause at the breakpoint; once the fork has been released, the same answer @@ -361,8 +385,22 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(JSON.stringify(started)).toContain(RELEASED); } expect((await rows()).filter((row) => row.parentSessionId === rootId)).toEqual([]); - const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent child exit 0'), 5000); - expect(output).toContain('child done 3'); + if (exitCode === 0) { + const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent child exit 0'), 5000); + expect(output).toContain('parent child exit 0'); + expect(output).toContain('child done 3'); + } else { + // The engine's crash and nothing else: parent.js must have seen its fork + // die of the access violation (Windows) or of a memory-fault signal. A + // fork ended from outside (SIGKILL, SIGTERM) is not accepted. + const crashLine = process.platform === 'win32' + ? new RegExp(`parent child exit (${WINDOWS_ACCESS_VIOLATION}|${WINDOWS_ACCESS_VIOLATION | 0}) \\(`) + : /parent child exit null \(\d+\) signal (SIGSEGV|SIGBUS|SIGABRT|SIGILL)/; + const output = await pollUntil(() => outputText(rootId), (text) => crashLine.test(text), 5000); + expect(output).toMatch(crashLine); + // A tolerated crash stays visible in the run's output. + console.warn(`[cap-0 release] Node ${process.version} lacks nodejs/node#64209: the released fork crashed (launch exit code ${exitCode})`); + } }, 120_000); /** diff --git a/tests/fixtures/javascript/subprocess-tree/parent.js b/tests/fixtures/javascript/subprocess-tree/parent.js index 292829bc1..a6fbeb0ef 100644 --- a/tests/fixtures/javascript/subprocess-tree/parent.js +++ b/tests/fixtures/javascript/subprocess-tree/parent.js @@ -18,7 +18,8 @@ console.log('parent start'); const childScript = join(here, process.argv[2] ?? 'child.js'); // argv names another child (child_grand.js) const child = fork(childScript, [], { stdio: 'inherit', windowsHide: true }); const marker = child.pid; // BREAKPOINT: the parent pauses here while the child is reported and adopted -child.on('exit', (code) => { - console.log(`parent child exit ${code} (${marker})`); +child.on('exit', (code, signal) => { + // A fork killed by a signal has no exit code; its signal is named after the marker. + console.log(`parent child exit ${code} (${marker})${signal ? ` signal ${signal}` : ''}`); process.exit(code ?? 1); }); diff --git a/tests/test-utils/helpers/node-inspector-version.ts b/tests/test-utils/helpers/node-inspector-version.ts new file mode 100644 index 000000000..c2c90f443 --- /dev/null +++ b/tests/test-utils/helpers/node-inspector-version.ts @@ -0,0 +1,9 @@ +/** Whether a released Node version includes nodejs/node#64209 (issue #1119). */ +export function hasInspectorSocketCrashFix(version: string): boolean { + const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(version); + if (!match) return false; + + const major = Number(match[1]); + const minor = Number(match[2]); + return major >= 27 || (major === 24 && minor >= 19) || (major === 26 && minor >= 5); +} diff --git a/tests/unit/test-utils/node-inspector-version.test.ts b/tests/unit/test-utils/node-inspector-version.test.ts new file mode 100644 index 000000000..b304176c8 --- /dev/null +++ b/tests/unit/test-utils/node-inspector-version.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +import { hasInspectorSocketCrashFix } from '../../test-utils/helpers/node-inspector-version.js'; + +describe('hasInspectorSocketCrashFix (nodejs/node#64209, issue #1119)', () => { + it.each([ + ['v20.20.0', false], + ['v22.23.5', false], + ['22.99.99', false], + ['v23.11.0', false], + ['v24.14.1', false], + ['24.18.99', false], + ['v24.19.0', true], + ['24.19.1', true], + ['24.20.0', true], + ['v25.9.0', false], + ['25.99.99', false], + ['v26.4.99', false], + ['26.5.0', true], + ['v26.5.1', true], + ['26.6.0', true], + ['v27.0.0', true], + ['28.0.0', true], + ['30.0.0', true], + ['', false], + ['not a version', false], + ['24.19', false], + ['26.5.0-rc.1', false] + ])('%s has the fix: %s', (version, expected) => { + expect(hasInspectorSocketCrashFix(version)).toBe(expected); + }); +}); From 560760687152a9c352be0f7be486098032455b69 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 05:12:41 -0500 Subject: [PATCH 2/3] test(javascript): closing a paused fork meets the same engine crash; one check for a released fork's outcome With the first commit in place the whole file failed once in three runs: the test that closes a paused, adopted fork saw the fork die with 3221225477 where it expected it to finish. close_debug_session on a child releases it by a detach, and the engine's crash follows that detach too. Both tests now share one check: the fork ran to its end, or, only on a Node without the fix, parent.js saw it die of the access violation or of a memory-fault signal. The guide and the changelog entry say that closing a child session releases it the same way. Measured on Node 24.14.1: the whole file twelve times, four at a time: 12 passed, 1 tolerated crash. Mine (the manager session). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1119.fixed.md | 2 +- docs/javascript/README.md | 5 +- .../javascript-subprocess-tree.test.ts | 85 +++++++++++-------- 3 files changed, 54 insertions(+), 38 deletions(-) diff --git a/changelog.d/1119.fixed.md b/changelog.d/1119.fixed.md index 2128818a0..dcd772863 100644 --- a/changelog.d/1119.fixed.md +++ b/changelog.d/1119.fixed.md @@ -1 +1 @@ -**The JavaScript guide no longer says that a child-session cap of 0 leaves child processes untouched** — with `DEBUG_MCP_MAX_CHILD_SESSIONS=0` every fork is still attached and then released, and the guide now says what a release can cost: on a Node without the inspector fix `nodejs/node#64209` (it is in 24.19.0, 26.5.0 and from 27; no 22.x release carries it) a released child can die with an access violation, measured at 44 of 259 releases on Node 24.14.1 and 13 of 256 on 22.23.5 on one Windows machine; and on any Node a child that is starting worker threads when the debugger detaches can be left with a worker that waits for a debugger and never runs. To avoid releases, raise the cap to cover the children, or pass `dapLaunchArgs: { autoAttachChildProcesses: false }`, which stops child processes from being followed at all. No server behaviour changes: three workarounds were built or designed, and none was safe. (#1119) +**The JavaScript guide no longer says that a child-session cap of 0 leaves child processes untouched** — with `DEBUG_MCP_MAX_CHILD_SESSIONS=0` every fork is still attached and then released, and the guide now says what a release can cost: on a Node without the inspector fix `nodejs/node#64209` (it is in 24.19.0, 26.5.0 and from 27; no 22.x release carries it) a released child can die with an access violation, measured at 44 of 259 releases on Node 24.14.1 and 13 of 256 on 22.23.5 on one Windows machine (closing a child session with `close_debug_session` releases it the same way and met the same crash); and on any Node a child that is starting worker threads when the debugger detaches can be left with a worker that waits for a debugger and never runs. To avoid releases, raise the cap to cover the children, or pass `dapLaunchArgs: { autoAttachChildProcesses: false }`, which stops child processes from being followed at all. No server behaviour changes: three workarounds were built or designed, and none was safe. (#1119) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index e9d09520d..485c76ee2 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -353,12 +353,15 @@ of 12 runs, the binding not yet in), and is now delivered on the debugger's chan A release detaches the debugger from a child so it can run undebugged; a child beyond `DEBUG_MCP_MAX_CHILD_SESSIONS` is released by a throwaway attach followed immediately by a detach. +`close_debug_session` on a child session releases it the same way, and `detach_from_process` +releases a tree's children. On Node without [nodejs/node#64209](https://github.com/nodejs/node/pull/64209), a released child can die with an access violation when the debugger detaches while the child's inspector is writing. The fix is in Node 24 from 24.19.0, Node 26 from 26.5.0, and Node 27 and later; no Node 22 release carries it (22.23.5 is the newest), and Node 25 ended without it. Measured through the server on one Windows machine with issue #1119's child: 44 of 259 releases on Node 24.14.1 crashed, and -13 of 256 on Node 22.23.5. +13 of 256 on Node 22.23.5. A paused child that was closed met the same crash in one of three +runs of its test on Node 24.14.1. On any Node version, releasing a child that is starting worker threads at detach can leave a worker waiting for a debugger and never running: measured at engine level, a worker parked by diff --git a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts index 006e751df..7ee5649a6 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts @@ -95,6 +95,47 @@ async function pollUntil(read: () => Promise, accept: (value: T) => boolea return last; } +/** + * Issue #1119. On a Node without nodejs/node#64209 (it is in 24.19.0, 26.5.0 + * and from 27), the inspector can crash when it writes to its socket just + * after a detach closed it. That is the engine's defect, and no server-side + * workaround was found that is safe. The fork then dies of an access + * violation (Windows) or of a fatal signal (elsewhere), and parent.js ends + * with the fork's exit code, or with 1 when a signal killed it. Windows + * reports 0xC0000005 unsigned or as a signed 32-bit number. + * + * Which Node runs the debuggee: these .js launches name no runtime, so the + * adapter uses the Node that runs the server (startStdioClient starts it with + * process.execPath), and parent.js's fork inherits it. process.version is the + * debuggee's version. + */ +const WINDOWS_ACCESS_VIOLATION = 0xC0000005; +const ENGINE_CRASH_EXIT_CODES = process.platform === 'win32' + ? [WINDOWS_ACCESS_VIOLATION, WINDOWS_ACCESS_VIOLATION | 0] + : [1]; +/** parent.js saw its fork die of the access violation, or of a memory-fault signal: never of a signal sent from outside. */ +const ENGINE_CRASH_LINE = process.platform === 'win32' + ? new RegExp(`parent child exit (${WINDOWS_ACCESS_VIOLATION}|${WINDOWS_ACCESS_VIOLATION | 0}) \\(`) + : /parent child exit null \(\d+\) signal (SIGSEGV|SIGBUS|SIGABRT|SIGILL)/; + +/** + * What a fork the debugger has just detached from did: it ran to its end, or, + * only on a Node without the fix, the engine crashed it. Nothing else passes. + */ +async function releasedForkRanOrEngineCrashed(rootId: string): Promise<'ran' | 'engine-crash'> { + const settled = (text: string): boolean => text.includes('parent child exit 0') || ENGINE_CRASH_LINE.test(text); + const output = await pollUntil(() => outputText(rootId), settled, 5000); + if (output.includes('parent child exit 0')) { + expect(output).toContain('child done 3'); + return 'ran'; + } + expect(hasInspectorSocketCrashFix(process.version), `a released fork did not finish on a Node that has the fix: ${output}`).toBe(false); + expect(output).toMatch(ENGINE_CRASH_LINE); + // A tolerated crash stays visible in the run's output. + console.warn(`[released fork] Node ${process.version} lacks nodejs/node#64209: the fork crashed when the debugger detached`); + return 'engine-crash'; +} + async function launch(scriptPath: string, extra: Record = {}): Promise { const started = await call('start_debugging', { scriptPath, @@ -276,7 +317,9 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(closed.childrenClosed).toBeUndefined(); expect((await rows()).some((row) => row.id === childId)).toBe(false); - // The released fork finishes undebugged; the parent sees exit 0 and ends. + // The released fork finishes undebugged and the parent sees exit 0 and ends; + // or, on a Node without the fix, the engine crashes the fork at the detach + // (issue #1119: measured on this test too) and the parent ends with that. const ended = await call('wait_for_stop', { sessionId: rootId, timeout: 30000 }); expect(ended.state, JSON.stringify(ended)).toBe('stopped'); expect(ended.sessionId).toBe(rootId); @@ -285,8 +328,7 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(ended.message, JSON.stringify(ended)).toContain('Its child sessions stopped 1 time during this run.'); expect(ended.message).not.toContain('without hitting any breakpoint'); expect(ended.unhitBreakpoints).toBeUndefined(); - const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent child exit 0'), 5000); - expect(output).toContain('child done 3'); + await releasedForkRanOrEngineCrashed(rootId); }, 120_000); it("restarting the parent closes the previous run's fork, and closing the parent takes the fork with it", async () => { @@ -346,26 +388,11 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( } // A launch answer carries the exit code under `data`; a wait answer hoists it. const exitCode = ended.exitCode ?? (ended as { data?: { exitCode?: number } }).data?.exitCode; - // Which Node runs the debuggee: this .js launch names no runtime, so the - // adapter uses the Node that runs the server (startStdioClient starts it - // with process.execPath), and parent.js's fork inherits it. process.version - // is the debuggee's version. - // - // Issue #1119: on a Node without nodejs/node#64209 (in 24.19.0, 26.5.0 and - // from 27), the inspector can crash when it writes to its socket just after - // the release's detach closed it. That is the engine's defect, and no - // server-side workaround was found that is safe. The fork then dies of an - // access violation (Windows) or of a fatal signal (elsewhere), and - // parent.js ends with the fork's exit code, or with 1 when a signal killed - // it. Windows reports 0xC0000005 unsigned or as a signed 32-bit number. - const WINDOWS_ACCESS_VIOLATION = 0xC0000005; - const engineCrashExitCodes = process.platform === 'win32' - ? [WINDOWS_ACCESS_VIOLATION, WINDOWS_ACCESS_VIOLATION | 0] - : [1]; + // A clean exit, or (only on a Node without the fix) the engine's own crash: issue #1119, above. if (hasInspectorSocketCrashFix(process.version)) { expect(exitCode, JSON.stringify(ended)).toBe(0); } else { - expect([0, ...engineCrashExitCodes], JSON.stringify(ended)).toContain(exitCode); + expect([0, ...ENGINE_CRASH_EXIT_CODES], JSON.stringify(ended)).toContain(exitCode); } expect(ended.childrenReleased, JSON.stringify(ended)).toBe(1); expect(ended.children).toBeUndefined(); @@ -385,22 +412,8 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(JSON.stringify(started)).toContain(RELEASED); } expect((await rows()).filter((row) => row.parentSessionId === rootId)).toEqual([]); - if (exitCode === 0) { - const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent child exit 0'), 5000); - expect(output).toContain('parent child exit 0'); - expect(output).toContain('child done 3'); - } else { - // The engine's crash and nothing else: parent.js must have seen its fork - // die of the access violation (Windows) or of a memory-fault signal. A - // fork ended from outside (SIGKILL, SIGTERM) is not accepted. - const crashLine = process.platform === 'win32' - ? new RegExp(`parent child exit (${WINDOWS_ACCESS_VIOLATION}|${WINDOWS_ACCESS_VIOLATION | 0}) \\(`) - : /parent child exit null \(\d+\) signal (SIGSEGV|SIGBUS|SIGABRT|SIGILL)/; - const output = await pollUntil(() => outputText(rootId), (text) => crashLine.test(text), 5000); - expect(output).toMatch(crashLine); - // A tolerated crash stays visible in the run's output. - console.warn(`[cap-0 release] Node ${process.version} lacks nodejs/node#64209: the released fork crashed (launch exit code ${exitCode})`); - } + // The launch's exit code and what parent.js saw agree: 0 with a fork that ran, the crash code with one that crashed. + expect(await releasedForkRanOrEngineCrashed(rootId), JSON.stringify(ended)).toBe(exitCode === 0 ? 'ran' : 'engine-crash'); }, 120_000); /** From 8c3d9f892e5f3c1b2d5eb5002bbbfedda2191e33 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 06:06:00 -0500 Subject: [PATCH 3/3] test(javascript): one check for every test that releases a fork; three more tests covered; the guide says exactly who releases what From the review of this branch: the cascade test (closing one of two forks) and the two attach tests (detaching and closing an attached root with a paused fork) release the same fixture and still required a clean end, so they had the same exposure to the engine's crash. The shared check moves to tests/test-utils/helpers/released-fork-outcome.ts with a table of unit cases; it also ties the launch's or the target's exit code to what the fixture saw, in every test that uses it. SIGTRAP joins the accepted signals; SIGKILL, SIGTERM and SIGINT do not pass. The other two fixtures name the signal too. The guide and the changelog entry no longer say that closing a child releases it 'the same way' as the throwaway attach: it detaches the child's existing connection. They say on which sessions detach_from_process releases a tree's children and on which it is refused. Run by the manager session on Node 24.14.1: the three files twelve times four at a time, 12 passed; the tree file's two release tests thirty times six at a time, 30 passed, 1 on the crash branch (exit code -1073741819). The cascade and attach crash branches have met no real crash; their line shapes are held by the helper's unit cases. Written by a GPT model. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1119.fixed.md | 2 +- docs/javascript/README.md | 15 ++- .../javascript-subprocess-attach.test.ts | 30 +++-- .../javascript-subprocess-cascade.test.ts | 24 +++- .../javascript-subprocess-tree.test.ts | 48 +------- .../subprocess-tree/attach_parent.js | 4 +- .../javascript/subprocess-tree/parent_two.js | 4 +- .../helpers/released-fork-outcome.ts | 64 +++++++++++ .../test-utils/released-fork-outcome.test.ts | 106 ++++++++++++++++++ 9 files changed, 231 insertions(+), 66 deletions(-) create mode 100644 tests/test-utils/helpers/released-fork-outcome.ts create mode 100644 tests/unit/test-utils/released-fork-outcome.test.ts diff --git a/changelog.d/1119.fixed.md b/changelog.d/1119.fixed.md index dcd772863..64179ef1b 100644 --- a/changelog.d/1119.fixed.md +++ b/changelog.d/1119.fixed.md @@ -1 +1 @@ -**The JavaScript guide no longer says that a child-session cap of 0 leaves child processes untouched** — with `DEBUG_MCP_MAX_CHILD_SESSIONS=0` every fork is still attached and then released, and the guide now says what a release can cost: on a Node without the inspector fix `nodejs/node#64209` (it is in 24.19.0, 26.5.0 and from 27; no 22.x release carries it) a released child can die with an access violation, measured at 44 of 259 releases on Node 24.14.1 and 13 of 256 on 22.23.5 on one Windows machine (closing a child session with `close_debug_session` releases it the same way and met the same crash); and on any Node a child that is starting worker threads when the debugger detaches can be left with a worker that waits for a debugger and never runs. To avoid releases, raise the cap to cover the children, or pass `dapLaunchArgs: { autoAttachChildProcesses: false }`, which stops child processes from being followed at all. No server behaviour changes: three workarounds were built or designed, and none was safe. (#1119) +**The JavaScript guide no longer says that a child-session cap of 0 leaves child processes untouched** — with `DEBUG_MCP_MAX_CHILD_SESSIONS=0` every fork is still attached and then released, and the guide now says what a release can cost: on a Node without the inspector fix `nodejs/node#64209` (it is in 24.19.0, 26.5.0 and from 27; no 22.x release carries it) a released child can die with an access violation, measured at 44 of 259 releases on Node 24.14.1 and 13 of 256 on 22.23.5 on one Windows machine. Closing a child session with `close_debug_session` detaches its existing connection and met the same crash. A plain `detach_from_process` on an attached root releases its children before detaching the root; it is refused on child sessions and on a launched root with an active proxy. A terminating detach requests termination instead. On any Node a child that is starting worker threads when the debugger detaches can be left with a worker that waits for a debugger and never runs. To avoid cap-overflow releases, raise the cap to cover the children, or pass `dapLaunchArgs: { autoAttachChildProcesses: false }` on a launch to stop following child processes at all. Raising the cap does not prevent explicit releases. No server behaviour changes: three workarounds were built or designed, and none was safe. (#1119) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 485c76ee2..b0efd5c9a 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -353,8 +353,12 @@ of 12 runs, the binding not yet in), and is now delivered on the debugger's chan A release detaches the debugger from a child so it can run undebugged; a child beyond `DEBUG_MCP_MAX_CHILD_SESSIONS` is released by a throwaway attach followed immediately by a detach. -`close_debug_session` on a child session releases it the same way, and `detach_from_process` -releases a tree's children. +`close_debug_session` on a child session detaches its existing connection so the child can run on. +On an attached root, `detach_from_process` without `terminateProcess: true` releases the tree's +children, deepest first, before detaching the root. It is refused on child sessions and, without +`terminateProcess: true`, on a launched root with an active proxy. With `terminateProcess: true`, +it closes the tree with termination requested instead of releasing it to run on. +Closing an attached root with `close_debug_session` also releases its children. On Node without [nodejs/node#64209](https://github.com/nodejs/node/pull/64209), a released child can die with an access violation when the debugger detaches while the child's inspector is writing. The fix is in Node 24 from 24.19.0, Node 26 from 26.5.0, and Node 27 and later; no Node 22 release @@ -367,8 +371,11 @@ On any Node version, releasing a child that is starting worker threads at detach worker waiting for a debugger and never running: measured at engine level, a worker parked by the inspector stays parked after the debugger disconnects (#1119). -Avoid releases by raising `DEBUG_MCP_MAX_CHILD_SESSIONS` to cover the children, or pass -`dapLaunchArgs: { autoAttachChildProcesses: false }` to stop following child processes at all. +Avoid cap-overflow releases by raising `DEBUG_MCP_MAX_CHILD_SESSIONS` to cover the children, or pass +`dapLaunchArgs: { autoAttachChildProcesses: false }` on a launch to stop following child processes +at all. Raising the cap does not prevent releases from closing a child or detaching/closing an +attached root. For an attach, child following is off by default; its setting is +`adapterConfig: { autoAttachChildProcesses: false }`. Setting `DEBUG_MCP_MAX_CHILD_SESSIONS=0` still adopts the program's own target and releases every fork; it does not avoid these detach limits. With child following off, their output is on the parent's buffer where the parent's pipes carry it. diff --git a/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts index e638aae8c..16393d0a7 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts @@ -12,7 +12,8 @@ * `get_output` carries its own lines and no `outputOn` pointer (an attach does * not own the process pipes the way a launch does). The cascades on an attach * root release its targets: detach keeps the rows, close removes them, and the - * target runs to its end either way. The last case is #501's wedge guard on + * target ends either way (a released fork can crash on affected Node, #1119). + * The last case is #501's wedge guard on * the fork target the e2e attach smoke uses, here so CI runs it. */ import { describe, it, expect, beforeEach, afterEach, afterAll } from 'vitest'; @@ -21,6 +22,7 @@ import path from 'node:path'; import { spawn, type ChildProcess } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; +import { releasedForkRanOrEngineCrashed } from '../../../test-utils/helpers/released-fork-outcome.js'; const root = fileURLToPath(new URL('../../../../', import.meta.url)); const treeDir = path.join(root, 'tests/fixtures/javascript/subprocess-tree'); @@ -111,16 +113,22 @@ async function startTarget(script: string): Promise { return target; } -/** The target's exit, with its own pipes' last lines: the proof that nothing killed it. */ -async function targetRanToItsEnd(target: Target): Promise { +/** The target's exit and final output; release cases also recognize #1119's native crash status. */ +async function targetRanToItsEnd(target: Target, options: { releasedFork?: boolean } = {}): Promise { let timer: ReturnType | undefined; try { - const exit = await Promise.race([target.exited, new Promise((resolve) => { - timer = setTimeout(() => resolve('still running'), 20000); + const exit = await Promise.race([target.exited, new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`target still running: ${target.output()}`)), 20000); })]); - expect(exit, target.output()).toBe(0); - expect(target.output()).toContain('child done 3'); - expect(target.output()).toContain('parent child exit 0'); + if (options.releasedFork) { + // startTarget uses process.execPath; its fork inherits that same Node, + // so the shared check's process.version is the target's version too. + releasedForkRanOrEngineCrashed({ output: target.output(), exitCode: exit }); + } else { + expect(exit, target.output()).toBe(0); + expect(target.output()).toContain('child done 3'); + expect(target.output()).toContain('parent child exit 0'); + } } finally { clearTimeout(timer); } @@ -288,8 +296,8 @@ describe('JavaScript session tree over a by-port attach (issue #1082)', () => { expect(childEnd.state, JSON.stringify(childEnd)).toBe('stopped'); expect(childEnd.released, JSON.stringify(childEnd)).toBe(true); - // Nothing was killed: the released fork finished its ticks and the parent exited with its code. - await targetRanToItsEnd(target); + // The parent forwards the released fork's clean end or native crash status. + await targetRanToItsEnd(target, { releasedFork: true }); }, 120_000); it('closing the attach root releases the paused fork and removes both rows; the target runs on to its end', async () => { @@ -308,7 +316,7 @@ describe('JavaScript session tree over a by-port attach (issue #1082)', () => { const ids = (await rows()).map((row) => row.id); expect(ids).not.toContain(rootId); expect(ids).not.toContain(childId); - await targetRanToItsEnd(target); + await targetRanToItsEnd(target, { releasedFork: true }); }, 120_000); it('never scans an existing child with its parent inspector port, with future child debugging off or on (#1286)', async () => { diff --git a/tests/adapters/javascript/integration/javascript-subprocess-cascade.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-cascade.test.ts index c197b3ca1..0edb54c45 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-cascade.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-cascade.test.ts @@ -10,6 +10,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; +import { releasedForkRanOrEngineCrashed } from '../../../test-utils/helpers/released-fork-outcome.js'; const root = fileURLToPath(new URL('../../../../', import.meta.url)); const treeDir = path.join(root, 'tests/fixtures/javascript/subprocess-tree'); @@ -153,7 +154,8 @@ describe('JavaScript session-tree lifecycle rows (issue #1082)', () => { } const [closedChild, survivor] = children; - // js-debug cannot end a target it adopted: the close releases the fork, which runs on undebugged. + // js-debug cannot end a target it adopted: the close releases the fork. + // On affected Node it can crash during the detach instead (issue #1119). const closed = await call('close_debug_session', { sessionId: closedChild.id }); expect(closed.success, JSON.stringify(closed)).toBe(true); expect(closed.released, JSON.stringify(closed)).toBe(true); @@ -180,10 +182,24 @@ describe('JavaScript session-tree lifecycle rows (issue #1082)', () => { const ended = await call('wait_for_stop', { sessionId: rootId, timeout: 30000 }); expect(ended.state, JSON.stringify(ended)).toBe('stopped'); expect(ended.sessionId).toBe(rootId); - expect(ended.exitCode).toBe(0); expect(ended.children).toEqual([expect.objectContaining({ sessionId: survivor.id, state: 'stopped' })]); - const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent done 0'), 5000); - expect(output).toContain('parent done 0'); + const output = await pollUntil(() => outputText(rootId), (text) => /^parent done -?\d+\r?\n/m.test(text), 5000); + const pidOf = (row: Row): number => { + const match = /\[(\d+)\]$/.exec(row.name); + expect(match, JSON.stringify(row)).not.toBeNull(); + return Number(match![1]); + }; + // Only the closed fork may crash. Its sibling must finish normally, after + // the three breakpoint stops above, and both exits must reach the parent. + expect(output).toMatch(new RegExp(`^parent child exit 0 \\(${pidOf(survivor)}\\)\\r?$`, 'm')); + expect(output.match(/^parent child exit .*$/gm), output).toHaveLength(2); + const outcome = releasedForkRanOrEngineCrashed({ + output, exitCode: ended.exitCode, childPid: pidOf(closedChild), parentExitMode: 'maximum' + }); + expect(output).toMatch(/^child done 3\r?$/m); + if (outcome === 'ran') { + expect(output.match(/^child done 3\r?$/gm), output).toHaveLength(2); + } }, 120_000); it("a cluster primary's workers each become a child session and stop on the breakpoint in the worker branch", async () => { diff --git a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts index 7ee5649a6..29f079af1 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts @@ -18,7 +18,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; -import { hasInspectorSocketCrashFix } from '../../../test-utils/helpers/node-inspector-version.js'; +import { releasedForkRanOrEngineCrashed } from '../../../test-utils/helpers/released-fork-outcome.js'; const root = fileURLToPath(new URL('../../../../', import.meta.url)); const treeDir = path.join(root, 'tests/fixtures/javascript/subprocess-tree'); @@ -96,44 +96,14 @@ async function pollUntil(read: () => Promise, accept: (value: T) => boolea } /** - * Issue #1119. On a Node without nodejs/node#64209 (it is in 24.19.0, 26.5.0 - * and from 27), the inspector can crash when it writes to its socket just - * after a detach closed it. That is the engine's defect, and no server-side - * workaround was found that is safe. The fork then dies of an access - * violation (Windows) or of a fatal signal (elsewhere), and parent.js ends - * with the fork's exit code, or with 1 when a signal killed it. Windows - * reports 0xC0000005 unsigned or as a signed 32-bit number. - * * Which Node runs the debuggee: these .js launches name no runtime, so the * adapter uses the Node that runs the server (startStdioClient starts it with * process.execPath), and parent.js's fork inherits it. process.version is the * debuggee's version. */ -const WINDOWS_ACCESS_VIOLATION = 0xC0000005; -const ENGINE_CRASH_EXIT_CODES = process.platform === 'win32' - ? [WINDOWS_ACCESS_VIOLATION, WINDOWS_ACCESS_VIOLATION | 0] - : [1]; -/** parent.js saw its fork die of the access violation, or of a memory-fault signal: never of a signal sent from outside. */ -const ENGINE_CRASH_LINE = process.platform === 'win32' - ? new RegExp(`parent child exit (${WINDOWS_ACCESS_VIOLATION}|${WINDOWS_ACCESS_VIOLATION | 0}) \\(`) - : /parent child exit null \(\d+\) signal (SIGSEGV|SIGBUS|SIGABRT|SIGILL)/; - -/** - * What a fork the debugger has just detached from did: it ran to its end, or, - * only on a Node without the fix, the engine crashed it. Nothing else passes. - */ -async function releasedForkRanOrEngineCrashed(rootId: string): Promise<'ran' | 'engine-crash'> { - const settled = (text: string): boolean => text.includes('parent child exit 0') || ENGINE_CRASH_LINE.test(text); - const output = await pollUntil(() => outputText(rootId), settled, 5000); - if (output.includes('parent child exit 0')) { - expect(output).toContain('child done 3'); - return 'ran'; - } - expect(hasInspectorSocketCrashFix(process.version), `a released fork did not finish on a Node that has the fix: ${output}`).toBe(false); - expect(output).toMatch(ENGINE_CRASH_LINE); - // A tolerated crash stays visible in the run's output. - console.warn(`[released fork] Node ${process.version} lacks nodejs/node#64209: the fork crashed when the debugger detached`); - return 'engine-crash'; +async function checkReleasedFork(rootId: string, exitCode: number | undefined): Promise { + const output = await pollUntil(() => outputText(rootId), (text) => /^parent child exit [^\n]*\n/m.test(text), 5000); + releasedForkRanOrEngineCrashed({ output, exitCode }); } async function launch(scriptPath: string, extra: Record = {}): Promise { @@ -328,7 +298,7 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(ended.message, JSON.stringify(ended)).toContain('Its child sessions stopped 1 time during this run.'); expect(ended.message).not.toContain('without hitting any breakpoint'); expect(ended.unhitBreakpoints).toBeUndefined(); - await releasedForkRanOrEngineCrashed(rootId); + await checkReleasedFork(rootId, ended.exitCode); }, 120_000); it("restarting the parent closes the previous run's fork, and closing the parent takes the fork with it", async () => { @@ -388,12 +358,6 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( } // A launch answer carries the exit code under `data`; a wait answer hoists it. const exitCode = ended.exitCode ?? (ended as { data?: { exitCode?: number } }).data?.exitCode; - // A clean exit, or (only on a Node without the fix) the engine's own crash: issue #1119, above. - if (hasInspectorSocketCrashFix(process.version)) { - expect(exitCode, JSON.stringify(ended)).toBe(0); - } else { - expect([0, ...ENGINE_CRASH_EXIT_CODES], JSON.stringify(ended)).toContain(exitCode); - } expect(ended.childrenReleased, JSON.stringify(ended)).toBe(1); expect(ended.children).toBeUndefined(); // The count is explained where it appears (issue #1137): what it means, @@ -413,7 +377,7 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( } expect((await rows()).filter((row) => row.parentSessionId === rootId)).toEqual([]); // The launch's exit code and what parent.js saw agree: 0 with a fork that ran, the crash code with one that crashed. - expect(await releasedForkRanOrEngineCrashed(rootId), JSON.stringify(ended)).toBe(exitCode === 0 ? 'ran' : 'engine-crash'); + await checkReleasedFork(rootId, exitCode); }, 120_000); /** diff --git a/tests/fixtures/javascript/subprocess-tree/attach_parent.js b/tests/fixtures/javascript/subprocess-tree/attach_parent.js index 0a0747f77..b31e319e7 100644 --- a/tests/fixtures/javascript/subprocess-tree/attach_parent.js +++ b/tests/fixtures/javascript/subprocess-tree/attach_parent.js @@ -51,8 +51,8 @@ process.stdin.once('data', (line) => { // The product no longer scans existing children (#1286); the fixture // retains this historical setup to isolate bootloader reports. const child = fork(join(here, 'child.js'), [], { execArgv: [], stdio: 'inherit', windowsHide: true }); - child.on('exit', (code) => { - console.log(`parent child exit ${code}`); + child.on('exit', (code, signal) => { + console.log(`parent child exit ${code}${signal ? ` signal ${signal}` : ''}`); process.exit(code ?? 1); }); }; diff --git a/tests/fixtures/javascript/subprocess-tree/parent_two.js b/tests/fixtures/javascript/subprocess-tree/parent_two.js index a31aa23cb..d227058da 100644 --- a/tests/fixtures/javascript/subprocess-tree/parent_two.js +++ b/tests/fixtures/javascript/subprocess-tree/parent_two.js @@ -13,10 +13,10 @@ const children = [0, 1].map(() => fork(join(here, 'child.js'), [], { stdio: 'inh let worst = 0; let exited = 0; for (const child of children) { - child.on('exit', (code) => { + child.on('exit', (code, signal) => { worst = Math.max(worst, code ?? 1); exited += 1; - console.log(`parent child exit ${code}`); + console.log(`parent child exit ${code} (${child.pid})${signal ? ` signal ${signal}` : ''}`); if (exited === children.length) { console.log(`parent done ${worst}`); process.exit(worst); diff --git a/tests/test-utils/helpers/released-fork-outcome.ts b/tests/test-utils/helpers/released-fork-outcome.ts new file mode 100644 index 000000000..4716bac4d --- /dev/null +++ b/tests/test-utils/helpers/released-fork-outcome.ts @@ -0,0 +1,64 @@ +import { expect } from 'vitest'; +import { hasInspectorSocketCrashFix } from './node-inspector-version.js'; + +const WINDOWS_ACCESS_VIOLATION = 0xC0000005; +const WINDOWS_CRASH_EXIT_CODES = [WINDOWS_ACCESS_VIOLATION, WINDOWS_ACCESS_VIOLATION | 0]; +// These statuses match native faults, including arm64 traps. They cannot prove +// where a signal originated; SIGKILL, SIGTERM and SIGINT do not pass. +const ENGINE_CRASH_SIGNAL = /^(SIGSEGV|SIGBUS|SIGABRT|SIGILL|SIGTRAP)$/; +// The fixtures share this prefix; parent.js and parent_two.js also name a PID. +const CHILD_EXIT_LINE = /^parent child exit (-?\d+|null)(?: \((\d+)\))?(?: signal (SIG[A-Z0-9]+))?\r?$/gm; + +interface ReleasedForkObservation { + output: string; + /** The launch/wait exit code, or the harness's attached-parent exit code. */ + exitCode: number | null | undefined; + /** Select the released fork when parent_two.js also reports its sibling. */ + childPid?: number; + /** parent_two.js uses Math.max(0, ...codes); the caller checks its other fork exited 0. */ + parentExitMode?: 'forward' | 'maximum'; + nodeVersion?: string; + platform?: NodeJS.Platform; +} + +/** + * Issue #1119: nodejs/node#64209 fixes an inspector write to a socket closed by + * detach (Node 24 from 24.19.0, Node 26 from 26.5.0, and 27+). On older Node, + * accept a native crash status only with matching fixture output and parent + * exit code. Windows can report the same 0xC0000005 status unsigned or signed; + * a signal gives the fork a null code, which these parents map to 1. + */ +export function releasedForkRanOrEngineCrashed({ + output, exitCode, childPid, parentExitMode = 'forward', + nodeVersion = process.version, platform = process.platform +}: ReleasedForkObservation): 'ran' | 'engine-crash' { + const exits = [...output.matchAll(CHILD_EXIT_LINE)].filter((match) => + childPid === undefined || Number(match[2]) === childPid + ); + expect(exits, output).toHaveLength(1); + const [, codeText, , signal] = exits[0]; + const code = codeText === 'null' ? null : Number(codeText); + const ran = code === 0 && signal === undefined; + if (ran) { + expect(output, output).toMatch(/^child done 3\r?$/m); + } else { + expect(hasInspectorSocketCrashFix(nodeVersion), `a released fork did not finish on fixed Node ${nodeVersion}: ${output}`).toBe(false); + const engineCrash = platform === 'win32' + ? code !== null && WINDOWS_CRASH_EXIT_CODES.includes(code) && signal === undefined + : code === null && signal !== undefined && ENGINE_CRASH_SIGNAL.test(signal); + expect(engineCrash, `not an engine crash status: ${output}`).toBe(true); + } + + const forwardedCode = code ?? 1; + const parentCode = parentExitMode === 'maximum' ? Math.max(0, forwardedCode) : forwardedCode; + const expectedCodes = platform === 'win32' && WINDOWS_CRASH_EXIT_CODES.includes(parentCode) + ? WINDOWS_CRASH_EXIT_CODES : [parentCode]; + expect(expectedCodes, `parent exit code ${exitCode} disagrees with its fork: ${output}`).toContain(exitCode); + if (parentExitMode === 'maximum') { + expect(output, output).toMatch(new RegExp(`^parent done ${parentCode}\\r?$`, 'm')); + } + if (!ran) { + console.warn(`[released fork] Node ${nodeVersion} lacks nodejs/node#64209: native crash status after detach (parent exitCode=${exitCode})`); + } + return ran ? 'ran' : 'engine-crash'; +} diff --git a/tests/unit/test-utils/released-fork-outcome.test.ts b/tests/unit/test-utils/released-fork-outcome.test.ts new file mode 100644 index 000000000..7c323970d --- /dev/null +++ b/tests/unit/test-utils/released-fork-outcome.test.ts @@ -0,0 +1,106 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { releasedForkRanOrEngineCrashed } from '../../test-utils/helpers/released-fork-outcome.js'; + +type Observation = Parameters[0]; +interface Case { + name: string; + observation: Observation; + outcome: 'ran' | 'engine-crash' | 'reject'; +} + +const clean = 'child done 3\nparent child exit 0 (123)\n'; +const unsignedCrash = 'parent child exit 3221225477 (123)\n'; +const signedCrash = 'parent child exit -1073741819 (123)\n'; +const observation = (output: string, exitCode: number | null | undefined, + extra: Partial = {}): Observation => ({ + output, exitCode, platform: 'win32', nodeVersion: 'v24.14.1', ...extra +}); + +const cases: Case[] = [ + { name: 'clean end on affected Node', observation: observation(clean, 0), outcome: 'ran' }, + { name: 'clean end on fixed Node', observation: observation(clean, 0, { nodeVersion: 'v24.19.0' }), outcome: 'ran' }, + { name: 'attach fixture has no PID', observation: observation('child done 3\nparent child exit 0\n', 0), outcome: 'ran' }, + { name: 'unsigned Windows crash', observation: observation(unsignedCrash, 3221225477), outcome: 'engine-crash' }, + { name: 'signed Windows crash', observation: observation(signedCrash, -1073741819), outcome: 'engine-crash' }, + { name: 'unsigned child code and signed launch code', observation: observation(unsignedCrash, -1073741819), outcome: 'engine-crash' }, + { name: 'signed child code and unsigned launch code', observation: observation(signedCrash, 3221225477), outcome: 'engine-crash' }, + { name: 'Windows crash on fixed Node', observation: observation(unsignedCrash, -1073741819, { nodeVersion: 'v26.5.0' }), outcome: 'reject' }, + { name: 'clean output but crash exit code', observation: observation(clean, -1073741819), outcome: 'reject' }, + { name: 'crash output but clean exit code', observation: observation(unsignedCrash, 0), outcome: 'reject' }, + { name: 'missing exit code', observation: observation(clean, undefined), outcome: 'reject' }, + { name: 'parent killed by signal', observation: observation(unsignedCrash, null), outcome: 'reject' }, + { name: 'unrelated parent exit code', observation: observation(unsignedCrash, 2), outcome: 'reject' }, + { name: 'ordinary child error', observation: observation('parent child exit 1 (123)\n', 1), outcome: 'reject' }, + { name: 'missing completion evidence', observation: observation('parent child exit 0 (123)\n', 0), outcome: 'reject' }, + { name: 'missing exit line', observation: observation('child done 3\n', 0), outcome: 'reject' }, + { name: 'duplicate exit lines', observation: observation(clean + unsignedCrash, 0), outcome: 'reject' }, + { name: 'signal without its full name', observation: observation('parent child exit null signal SIGSEGVE\n', 1, { platform: 'linux' }), outcome: 'reject' }, + { name: 'POSIX crash code without signal', observation: observation('parent child exit null\n', 1, { platform: 'linux' }), outcome: 'reject' }, + { name: 'POSIX crash output but clean exit code', observation: observation('parent child exit null signal SIGSEGV\n', 0, { platform: 'linux' }), outcome: 'reject' }, + { name: 'Windows code on POSIX', observation: observation(unsignedCrash, -1073741819, { platform: 'linux' }), outcome: 'reject' }, + { name: 'POSIX signal on Windows', observation: observation('parent child exit null signal SIGSEGV\n', 1), outcome: 'reject' }, + { + name: 'two clean forks with a selected PID', + observation: observation(clean + 'child done 3\nparent child exit 0 (456)\nparent done 0\n', 0, + { childPid: 123, parentExitMode: 'maximum' }), outcome: 'ran' + }, + { + name: 'selected fork crashes and sibling exits cleanly', + observation: observation(unsignedCrash + 'child done 3\nparent child exit 0 (456)\nparent done 3221225477\n', -1073741819, + { childPid: 123, parentExitMode: 'maximum' }), outcome: 'engine-crash' + }, + { + name: 'Math.max preserves 0 for a signed negative child status', + observation: observation(signedCrash + 'child done 3\nparent child exit 0 (456)\nparent done 0\n', 0, + { childPid: 123, parentExitMode: 'maximum' }), outcome: 'engine-crash' + }, + { + name: 'aggregate parent done line disagrees', + observation: observation(unsignedCrash + 'parent done 0\n', -1073741819, + { childPid: 123, parentExitMode: 'maximum' }), outcome: 'reject' + }, + { + name: 'two forks with a POSIX crash', + observation: observation('parent child exit null (123) signal SIGSEGV\nchild done 3\nparent child exit 0 (456)\nparent done 1\n', 1, + { platform: 'linux', childPid: 123, parentExitMode: 'maximum' }), outcome: 'engine-crash' + }, + { + name: 'selected PID is absent', + observation: observation(clean, 0, { childPid: 456 }), outcome: 'reject' + } +]; + +for (const platform of ['linux', 'darwin'] as const) { + for (const signal of ['SIGSEGV', 'SIGBUS', 'SIGABRT', 'SIGILL', 'SIGTRAP', 'SIGKILL', 'SIGTERM', 'SIGINT']) { + for (const withPid of [true, false]) { + cases.push({ + name: `${platform} ${signal}, PID ${withPid ? 'present' : 'absent'}`, + observation: observation(`parent child exit null${withPid ? ' (123)' : ''} signal ${signal}\n`, 1, { platform }), + outcome: ['SIGKILL', 'SIGTERM', 'SIGINT'].includes(signal) ? 'reject' : 'engine-crash' + }); + } + } + cases.push({ + name: `${platform} signal rejected on fixed Node`, + observation: observation('parent child exit null signal SIGTRAP\n', 1, { platform, nodeVersion: 'v27.0.0' }), + outcome: 'reject' + }); +} + +afterEach(() => vi.restoreAllMocks()); + +describe('releasedForkRanOrEngineCrashed (issue #1119)', () => { + it.each(cases)('$name', ({ observation: observed, outcome }) => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + if (outcome === 'reject') { + expect(() => releasedForkRanOrEngineCrashed(observed)).toThrow(); + expect(warning).not.toHaveBeenCalled(); + } else { + expect(releasedForkRanOrEngineCrashed(observed)).toBe(outcome); + expect(warning).toHaveBeenCalledTimes(outcome === 'engine-crash' ? 1 : 0); + if (outcome === 'engine-crash') { + expect(warning).toHaveBeenCalledWith(expect.stringContaining('native crash status after detach')); + } + } + }); +});