Skip to content
19 changes: 16 additions & 3 deletions src/js/node/worker_threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@
}
port.on("message", onAck);
port.unref();
return new Writable({
const stream = new Writable({
decodeStrings: false,
writev(chunks, cb) {
const payload = new Array(chunks.length);
Expand Down Expand Up @@ -442,26 +442,39 @@
cb(err);
},
});
stream.flushInFlightForExit = onAck;
return stream;

Check warning on line 446 in src/js/node/worker_threads.ts

View check run for this annotation

Claude / Claude Code Review

flushInFlightForExit exposed as public string property on process.stdout/stderr and worker.stdin

`flushInFlightForExit` is stored as a plain string-keyed property on the same Writable objects installed as `process.stdout`/`process.stderr` (and on parent-side `worker.stdin`, since `makePortWritable` is shared), and the exit handler then routes through that user-overridable property. This violates the `src/js/` tamper-resistance rule ("never route internal logic through user-overridable machinery") and diverges from the Node reference this PR cites, which keys the same hook via the module-pri
Comment thread
robobun marked this conversation as resolved.
Resolved
}

function setupWorkerStdio(stdio) {
const { stdin, stdout, stderr } = stdio;
let stdoutStream;
let stderrStream;
if (stdout) {
stdoutStream = makePortWritable(stdout);
Object.defineProperty(process, "stdout", {
value: makePortWritable(stdout),
value: stdoutStream,
writable: true,
configurable: true,
enumerable: true,
});
}
if (stderr) {
stderrStream = makePortWritable(stderr);
Object.defineProperty(process, "stderr", {
value: makePortWritable(stderr),
value: stderrStream,
writable: true,
configurable: true,
enumerable: true,
});
}
if (stdoutStream || stderrStream) {
// node's flushSync (internal/bootstrap/switches/is_not_main_thread)
process.on("exit", function flushSync() {
stdoutStream?.flushInFlightForExit();
stderrStream?.flushInFlightForExit();
});
}
// node always replaces a worker's process.stdin: port-backed when { stdin: true },
// otherwise an immediately-EOF'd stream — never the process-wide fd 0, which
// would race the main thread (and hang on a TTY).
Expand Down
167 changes: 167 additions & 0 deletions test/js/node/worker_threads/worker-stdio-exit-drain.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { once } from "node:events";
import { Worker } from "worker_threads";

// A writev issued before process.exit() parks its cb awaiting a reader ack that
// never arrives; without an exit-time flush every chunk buffered after the first
// batch is dropped (node registers a process.on('exit') that completes the cb).
describe.concurrent("captured stdio drains on synchronous process.exit()", () => {
async function collect(worker: Worker, stream: "stdout" | "stderr") {
worker[stream].setEncoding("utf8");
let out = "";
worker[stream].on("data", d => (out += d));
const ended = once(worker[stream], "end");
const [code] = await once(worker, "exit");
await ended;
return { out, code };
}

test.each(["stdout", "stderr"] as const)("console.%s output is not lost", async stream => {
const method = stream === "stdout" ? "log" : "error";
const worker = new Worker(
`console.${method}("A"); console.${method}("B"); console.${method}("C"); process.exit(0);`,
{ eval: true, [stream]: true },
);
const { out, code } = await collect(worker, stream);
expect({ out, code }).toEqual({ out: "A\nB\nC\n", code: 0 });
});

test.each(["stdout", "stderr"] as const)("raw process.%s.write output is not lost", async stream => {
const worker = new Worker(
`process.${stream}.write("A\\n"); process.${stream}.write("B\\n"); process.${stream}.write("C\\n"); process.exit(0);`,
{ eval: true, [stream]: true },
);
const { out, code } = await collect(worker, stream);
expect({ out, code }).toEqual({ out: "A\nB\nC\n", code: 0 });
});

test("many writes before exit all reach the parent", async () => {
const worker = new Worker(`for (let i = 0; i < 100; i++) console.log("line", i); process.exit(0);`, {
eval: true,
stdout: true,
});
const { out, code } = await collect(worker, "stdout");
const lines = out.split("\n").filter(Boolean);
expect({ first: lines[0], last: lines.at(-1), count: lines.length, code }).toEqual({
first: "line 0",
last: "line 99",
count: 100,
code: 0,
});
});

test("writes from a user process.on('exit') handler reach the parent", async () => {
const worker = new Worker(
`
process.on("exit", () => { console.log("from-exit"); process.stdout.write("tail\\n"); });
console.log("before");
process.exit(0);
`,
{ eval: true, stdout: true },
);
const { out, code } = await collect(worker, "stdout");
expect({ out, code }).toEqual({ out: "before\nfrom-exit\ntail\n", code: 0 });
});
});

// Default worker stdio (no { stdout: true }) is also port-backed and auto-pipes
// to the parent's stdout/stderr: the same parked-writev drop applies, so a
// worker that logs N lines then calls process.exit() must surface all N.
describe.concurrent("auto-piped stdio drains on synchronous process.exit()", () => {
const N = 300;
function parentScript(exitCall: string) {
const workerBody = `for (let i = 0; i < ${N}; i++) console.log("W" + i);` + `console.error("WERR");` + exitCall;
return (
`const { Worker } = require("node:worker_threads");` +
`const w = new Worker(${JSON.stringify(workerBody)}, { eval: true });` +
`w.on("exit", c => console.error("[worker exit " + c + "]"));`
);
}

test("worker console.log lines all reach the parent's stdout", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", parentScript("process.exit(0);")],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const lines = stdout.split("\n").filter(Boolean);
expect({
first: lines[0],
last: lines.at(-1),
count: lines.length,
stderr: stderr.split("\n").filter(Boolean).sort(),
}).toEqual({
first: "W0",
last: `W${N - 1}`,
count: N,
stderr: ["WERR", "[worker exit 0]"],
});
expect(exitCode).toBe(0);
});

test("without process.exit() all lines already arrive", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", parentScript("")],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, , exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout.split("\n").filter(Boolean).length).toBe(N);
expect(exitCode).toBe(0);
});
});

// A worker that dies from an uncaught exception or unhandled rejection still
// runs process.on('exit') with _exiting === true, so the same flush applies:
// logs written before the crash must all reach the parent. Subprocess-spawned
// so the worker's uncaught-error handling is the runtime's, not bun:test's.
describe.concurrent("auto-piped stdio drains when a worker dies from an uncaught error", () => {
const N = 300;

async function run(trailer: string) {
const workerBody = `for (let i = 0; i < ${N}; i++) console.log("LINE-" + i); ${trailer}`;
const parent =
`const { Worker } = require("node:worker_threads");` +
`const w = new Worker(${JSON.stringify(workerBody)}, { eval: true });` +
`w.on("error", e => console.error("[worker error " + e.message + "]"));` +
`w.on("exit", c => console.error("[worker exit " + c + "]"));`;
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", parent],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return {
lines: stdout.split("\n").filter(Boolean),
stderr: stderr.split("\n").filter(Boolean).sort(),
exitCode,
};
}

test("uncaught exception after N logs", async () => {
const { lines, stderr, exitCode } = await run(`throw new Error("CRASH-AFTER-LOGS");`);
expect({ first: lines[0], last: lines.at(-1), count: lines.length, stderr }).toEqual({
first: "LINE-0",
last: `LINE-${N - 1}`,
count: N,
stderr: ["[worker error CRASH-AFTER-LOGS]", "[worker exit 1]"],
});
expect(exitCode).toBe(0);
});

test("unhandled rejection after N logs", async () => {
const { lines, stderr, exitCode } = await run(`Promise.reject(new Error("REJECT-AFTER-LOGS"));`);
expect({ first: lines[0], last: lines.at(-1), count: lines.length, stderr }).toEqual({
first: "LINE-0",
last: `LINE-${N - 1}`,
count: N,
stderr: ["[worker error REJECT-AFTER-LOGS]", "[worker exit 1]"],
});
expect(exitCode).toBe(0);
});
});
Loading