diff --git a/changelog.d/1119.fixed.md b/changelog.d/1119.fixed.md new file mode 100644 index 000000000..64179ef1b --- /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. 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 44bf565e2..b0efd5c9a 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -351,10 +351,34 @@ 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. +`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 +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. 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 +the inspector stays parked after the debugger disconnects (#1119). + +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. ```javascript // parent.js 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 ca03fa02e..29f079af1 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 { 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'); @@ -94,6 +95,17 @@ async function pollUntil(read: () => Promise, accept: (value: T) => boolea return last; } +/** + * 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. + */ +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 { const started = await call('start_debugging', { scriptPath, @@ -275,7 +287,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); @@ -284,8 +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(); - const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent child exit 0'), 5000); - expect(output).toContain('child done 3'); + 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 () => { @@ -335,8 +348,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 +357,17 @@ 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; 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 +376,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([]); - const output = await pollUntil(() => outputText(rootId), (text) => text.includes('parent child exit 0'), 5000); - expect(output).toContain('child done 3'); + // The launch's exit code and what parent.js saw agree: 0 with a fork that ran, the crash code with one that crashed. + 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.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/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/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/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/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); + }); +}); 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')); + } + } + }); +});