Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1119.fixed.md
Original file line number Diff line number Diff line change
@@ -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)
32 changes: 28 additions & 4 deletions docs/javascript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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');
Expand Down Expand Up @@ -111,16 +113,22 @@ async function startTarget(script: string): Promise<Target> {
return target;
}

/** The target's exit, with its own pipes' last lines: the proof that nothing killed it. */
async function targetRanToItsEnd(target: Target): Promise<void> {
/** 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<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const exit = await Promise.race([target.exited, new Promise<string>((resolve) => {
timer = setTimeout(() => resolve('still running'), 20000);
const exit = await Promise.race([target.exited, new Promise<never>((_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);
}
Expand Down Expand Up @@ -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 () => {
Expand All @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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<Closed>('close_debug_session', { sessionId: closedChild.id });
expect(closed.success, JSON.stringify(closed)).toBe(true);
expect(closed.released, JSON.stringify(closed)).toBe(true);
Expand All @@ -180,10 +182,24 @@ describe('JavaScript session-tree lifecycle rows (issue #1082)', () => {
const ended = await call<Stop>('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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -94,6 +95,17 @@ async function pollUntil<T>(read: () => Promise<T>, 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<void> {
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<string, unknown> = {}): Promise<Stop> {
const started = await call<Stop>('start_debugging', {
scriptPath,
Expand Down Expand Up @@ -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<Stop>('wait_for_stop', { sessionId: rootId, timeout: 30000 });
expect(ended.state, JSON.stringify(ended)).toBe('stopped');
expect(ended.sessionId).toBe(rootId);
Expand All @@ -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 () => {
Expand Down Expand Up @@ -335,24 +348,26 @@ 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<Stop>('wait_for_stop', { sessionId: rootId, timeout: 30000 });
expect(ended.state, JSON.stringify(ended)).toBe('stopped');
if (ended !== started) {
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
Expand All @@ -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);

/**
Expand Down
4 changes: 2 additions & 2 deletions tests/fixtures/javascript/subprocess-tree/attach_parent.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
};
Expand Down
5 changes: 3 additions & 2 deletions tests/fixtures/javascript/subprocess-tree/parent.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
4 changes: 2 additions & 2 deletions tests/fixtures/javascript/subprocess-tree/parent_two.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
9 changes: 9 additions & 0 deletions tests/test-utils/helpers/node-inspector-version.ts
Original file line number Diff line number Diff line change
@@ -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);
}
Loading
Loading