Skip to content
12 changes: 9 additions & 3 deletions src/js/node/child_process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ var StringPrototypeIncludes = String.prototype.includes;
var StringPrototypeStartsWith = String.prototype.startsWith;
var Uint8ArrayPrototypeIncludes = Uint8Array.prototype.includes;

// Not the globals, which user code and fake timers replace: https://github.com/nodejs/node/blob/v26.12.1/lib/child_process.js#L76
const setTimeout: typeof globalThis.setTimeout = $newCppFunction("node/NodeTimers.cpp", "functionSetTimeout", 1);
const clearTimeout: typeof globalThis.clearTimeout = $newCppFunction("node/NodeTimers.cpp", "functionClearTimeout", 1);
Comment thread
robobun marked this conversation as resolved.
Resolved

const MAX_BUFFER = 1024 * 1024;

interface ExecException extends Error {
Expand Down Expand Up @@ -179,14 +183,15 @@ function spawn(file, args, options) {
child.emit("error", err);
}
}
}, timeout).unref();
}, timeout);

const clear = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
// Node clears on 'close' alone (https://github.com/nodejs/node/blob/v26.12.1/lib/child_process.js#L874-L880). Here 'exit' is not always followed by 'close'.
child.once("exit", clear);
child.once("close", clear);
}
Expand Down Expand Up @@ -262,7 +267,6 @@ function execFile(file, args, options?, callback?) {
const child = spawn(file, args, {
cwd: options.cwd,
env: options.env,
timeout: options.timeout,
killSignal: options.killSignal,
uid: options.uid,
gid: options.gid,
Expand Down Expand Up @@ -368,7 +372,9 @@ function execFile(file, args, options?, callback?) {
timeoutId = setTimeout(function delayedKill() {
timeoutId = null;
kill();
}, optionsTimeout).unref();
}, optionsTimeout);
Comment thread
robobun marked this conversation as resolved.
Resolved
// Past 'exit' the deadline only bounds the wait for 'close', which Bun can lose, so it stops holding the process.
child.once("exit", () => timeoutId?.unref());
}

function addOnDataListener(child_buffer, _buffer, kind) {
Expand Down
95 changes: 95 additions & 0 deletions test/js/node/child_process/child_process.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1696,6 +1696,101 @@ describe("spawn/execFile({signal}) does not leak abort listeners on spawn failur
});
});

// `timeout` is one timer per call, and it calls child.kill(): spawn() arms it
// for spawn and fork, execFile() for execFile and exec. As in Node, it keeps the
// parent alive until it fires or the child is gone, child.unref() or not.
describe("options.timeout", () => {
const fixture = path.join(import.meta.dir, "fixtures", "child-process-timeout-fixture.js");

// What the parent in the fixture reports as it exits, and whether the child
// it started is still there afterwards.
type Expected = { killed?: boolean; kills: number; events?: string[]; callback?: unknown; alive?: boolean };
const cases: Record<string, Expected> = {
// Only the deadline keeps the parent alive. It waits, signals once, and exits.
"spawn": { killed: true, kills: 1, alive: false },
"fork": { killed: true, kills: 1, alive: false },
"execFile": { killed: true, kills: 1, alive: false },
"exec": { killed: true, kills: 1, alive: false },
"execFile, pipes open at the deadline": {
killed: true,
kills: 1,
events: ["exit", "close"],
callback: { killed: true },
},
// The callback has its error, so the deadline is over. The child ends by itself.
"execFile, 'error' before the deadline": {
killed: false,
kills: 0,
events: ["error", "exit", "close"],
callback: { killed: false },
},
// The child is gone before the deadline. The parent hears of it, and the timer does not keep it.
"spawn, child exits first": { kills: 0, events: ["exit", "close"] },
"fork, child exits first": { kills: 0, events: ["exit", "close"] },
"execFile, child exits first": { kills: 0, events: ["exit", "close"], callback: "no error" },
// No 'close' comes after these 'exit's (Node emits one), so the events are not part of the cases.
"spawn, 'exit' listener pauses stdout": { killed: false, kills: 0 },
"execFile, 'exit' listener pauses the pipes": { killed: false, kills: 0 },
"spawn of a missing file": { kills: 0, events: ["error", "close"] },
// The timers are not the globals, which a fake-timers library replaces.
"spawn, timers replaced after the module loaded": { kills: 0, events: ["exit", "close"] },
Comment thread
robobun marked this conversation as resolved.
Resolved
"execFile, timers replaced after the module loaded": { kills: 0, events: ["exit", "close"], callback: "no error" },
"timers replaced while the module loads, then restored": { killed: true, kills: 1, alive: false },
// No timeout, no timer: the parent leaves at once and the child stays.
"no timeout": { killed: false, kills: 0, events: [], alive: true },
// The graph ends its child and its timers. No 'close' comes to clear the deadline.
"spawn in a Bun.ModuleGraph that is disposed": { killed: false, kills: 0, alive: false },
};

const isAlive = (pid: number) => {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
};

// One at a time: a case is two processes, and a debug build that starts
// them all together needs the whole test timeout for the slowest.
it.each(Object.entries(cases))("%s", async (mode, expected) => {
await using parent = Bun.spawn({
cmd: [bunExe(), fixture, mode],
// The runner sets this flag on ASAN lanes. With it the parent kills its
// child as it exits, whether or not the deadline was reached.
env: { ...bunEnv, BUN_FEATURE_FLAG_NO_ORPHANS: undefined },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([parent.stdout.text(), parent.stderr.text(), parent.exited]);
const report = stdout ? JSON.parse(stdout) : {};
const pid: number | undefined = report.pid;
try {
let alive = pid !== undefined && isAlive(pid);
Comment thread
robobun marked this conversation as resolved.
Resolved
// The parent signals the child and exits. The child dies a moment later.
for (let i = 0; alive && expected.alive === false && i < 200; i++) {
await Bun.sleep(10);
alive = isAlive(pid!);
}
const reported = Object.fromEntries(
Object.keys(expected).map(key => [key, key === "alive" ? alive : report[key]]),
);
expect({ stderr, ...reported, exitCode, signalCode: parent.signalCode }).toEqual({
stderr: "",
...expected,
exitCode: 0,
signalCode: null,
});
} finally {
if (pid !== undefined) {
try {
process.kill(pid, "SIGKILL");
} catch {}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
});
});

// A 'data' handler runs inside the native read loop that delivered its chunk,
// and node streams pull again from there, so that pull reads synchronously,
// nested in the outer loop, and can run all the way to EOF. The reader used to
Expand Down
134 changes: 134 additions & 0 deletions test/js/node/child_process/fixtures/child-process-timeout-fixture.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

// Measures the child's actual exit time, not just its 'error' event.
// The outer spawnSync timeout catches a leaked inner timer.

const common = require('../common');
const { spawnSyncAndExitWithoutError } = require('../common/child_process');

const bugStallMs = common.platformTimeout(10000);
const outerTimeoutMs = common.platformTimeout(2000);

spawnSyncAndExitWithoutError(process.execPath, ['-e', `
const { spawn } = require('child_process');
const cp = spawn(process.execPath, ['--version'], {
cwd: '/nonexistent/path/that/should/never/exist',
timeout: ${bugStallMs},
});
cp.on('error', () => {});
`], { timeout: outerTimeoutMs });
Loading