Repository navigation
worker_threads: drain port-backed stdio on process.exit() #34340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4e45a6c
worker_threads: drain port-backed stdio on process.exit()
robobun d61c940
Move exit-drain tests to their own file
robobun 46448d6
Add auto-pipe (default stdio) coverage for the exit drain
robobun 9b6e5b0
[autofix.ci] apply automated fixes
autofix-ci[bot] 6d608c5
ci: retrigger gate (release build infra failure)
robobun f213db8
Cover the uncaught-exception and unhandled-rejection exit paths
robobun a68b244
Trim redundant comments on the exit-flush path
robobun 2d1bef9
Reduce flushSync comment to the Node reference only
robobun accf6bb
Run the exit-drain tests concurrently
robobun 3ff7865
Key the exit-flush hook by a module-local Symbol
robobun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
test/js/node/worker_threads/worker-stdio-exit-drain.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.