From 698b9fb8e059f4fe259a7bc9e303911082a0351f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 13 Sep 2026 19:31:40 +0000 Subject: [PATCH 1/9] bun run: end the entry's top-level await when a fatal error ends the run An uncaught exception or an unhandled rejection stops the run loop of bun run: is_event_loop_alive() is false once an error nothing handled is counted. load_entry_point waits for the entry's top-level await with the generic wait_for_promise, which does not look at that counter. So the module kept running to its end after the error was printed, and forever with the loop in #22546. Wait with wait_for_module_promise there. It is wait_for_promise plus one stop condition: a fatal error counted during the wait. Both share one loop. Run::start also skips its post-load GC and tick after a fatal error, because that tick resumed the await when its wakeup was already queued from another thread. Watch mode counts errors too and keeps going, so has_fatal_error() is false there. Fixes #22546 --- src/jsc/VirtualMachine.rs | 26 +++++- src/jsc/event_loop.rs | 30 +++++- src/runtime/cli/run_command.rs | 2 + test/js/bun/spawn/exit-code.test.ts | 140 +++++++++++++++++++++++++++- 4 files changed, 189 insertions(+), 9 deletions(-) diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index 769b4cb550b0..d25c6a44cf8c 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1407,6 +1407,18 @@ impl VirtualMachine { || !el.next_immediate_tasks.is_empty() } + /// For `bun run`: an error nothing handled has been counted, which ends the run (its run loop + /// stops on `is_event_loop_alive()`). Watch mode counts errors too, and keeps going. + pub fn has_fatal_error(&self) -> bool { + self.has_fatal_error_since(0) + } + + /// [`has_fatal_error`](Self::has_fatal_error), for errors counted since + /// `unhandled_error_counter` was `count`. + pub fn has_fatal_error_since(&self, count: usize) -> bool { + self.unhandled_error_counter > count && !self.is_watcher_enabled() + } + pub fn wakeup(&mut self) { self.event_loop_mut().wakeup(); } @@ -2882,6 +2894,15 @@ impl VirtualMachine { self.event_loop_mut().wait_for_promise(promise) } + /// Thin forwarder; body lives in [`crate::event_loop::EventLoop::wait_for_module_promise`]. + #[inline] + pub fn wait_for_module_promise( + &mut self, + promise: *mut JSInternalPromise, + ) -> Result<(), jsc::Stopped> { + self.event_loop_mut().wait_for_module_promise(promise) + } + /// `eventLoop().autoTick()` — dispatched through the runtime hook /// (needs `Timer::All` for the poll timeout). #[inline] @@ -3058,7 +3079,8 @@ impl VirtualMachine { } /// `loadEntryPoint(entry_path)` — `reload_entry_point` + spin until the - /// returned promise settles. + /// returned promise settles, or a fatal error counted meanwhile ends the run. Watch + /// mode waits on: `Run::start` keeps ticking there whatever the error counter says. pub fn load_entry_point( &mut self, entry_path: &[u8], @@ -3089,7 +3111,7 @@ impl VirtualMachine { if crate::JSPromise::status_ptr(promise) == crate::js_promise::Status::Rejected { return Ok(promise); } - let _ = self.wait_for_promise(jsc::AnyPromise::Internal(promise)); + let _ = self.wait_for_module_promise(promise); } Ok(self.pending_internal_promise.unwrap_or(promise)) diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index e63b3583a000..6a266286a118 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1109,11 +1109,31 @@ impl EventLoop { /// `JsResult` function crosses explicitly with [`jsc::Stopped::throw`] (which, with /// the termination already pending, is just `Thrown`). pub fn wait_for_promise(&mut self, promise: jsc::AnyPromise) -> Result<(), jsc::Stopped> { + self.wait_for_promise_impl::(promise) + } + + /// [`wait_for_promise`](Self::wait_for_promise) for the entry module of `bun run`. Also returns + /// `Ok`, with `promise` still pending, when a fatal error is counted during the wait: that stops + /// the run loop, so it stops a top-level await too (#22546). An error counted before the wait + /// (by a `--preload`) does not end it: the entry still has to load and start. + pub fn wait_for_module_promise( + &mut self, + promise: *mut jsc::JSInternalPromise, + ) -> Result<(), jsc::Stopped> { + self.wait_for_promise_impl::(jsc::AnyPromise::Internal(promise)) + } + + fn wait_for_promise_impl( + &mut self, + promise: jsc::AnyPromise, + ) -> Result<(), jsc::Stopped> { let jsc_vm = self.vm_ref().jsc_vm(); - if promise.status() != PromiseStatus::Pending { - return Ok(()); - } - while promise.status() == PromiseStatus::Pending { + let errors_before = self.vm_ref().unhandled_error_counter; + let waiting = |this: &Self| { + promise.status() == PromiseStatus::Pending + && !(UNTIL_FATAL_ERROR && this.vm_ref().has_fatal_error_since(errors_before)) + }; + while waiting(self) { if jsc_vm.execution_forbidden() || !self.vm_ref().script_allowed() || self.global_ref().has_pending_termination_exception() @@ -1121,7 +1141,7 @@ impl EventLoop { return Err(jsc::Stopped); } self.tick(); - if promise.status() == PromiseStatus::Pending { + if waiting(self) { self.auto_tick(); } } diff --git a/src/runtime/cli/run_command.rs b/src/runtime/cli/run_command.rs index c0a303130aa4..3459767d089b 100644 --- a/src/runtime/cli/run_command.rs +++ b/src/runtime/cli/run_command.rs @@ -1470,7 +1470,9 @@ impl Run<'_> { // Drop what transpiling and linking the entry graph left behind before settling into the event loop. A // standalone executable has no transpiler garbage, and its unlinked code blocks came from the embedded bytecode // cache — deleting them here only means decoding them again on first call — so leave its heap to the collector. + // After a fatal error the run is over, and the tick would resume the top-level await that error cut short. if vm.standalone_module_graph.is_none() + && !vm.has_fatal_error() && (vm.is_event_loop_alive() || vm.event_loop_ref().tick_concurrent_with_count() > 0) { vm.global().vm().release_weak_refs(); diff --git a/test/js/bun/spawn/exit-code.test.ts b/test/js/bun/spawn/exit-code.test.ts index c0510ced6a49..a1bd7abc1e8c 100644 --- a/test/js/bun/spawn/exit-code.test.ts +++ b/test/js/bun/spawn/exit-code.test.ts @@ -1,6 +1,6 @@ import { spawnSync } from "bun"; -import { expect, it } from "bun:test"; -import { bunExe } from "harness"; +import { describe, expect, it } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; it("process.exit(1) works", () => { const { exitCode } = spawnSync([bunExe(), import.meta.dir + "/exit-code-1.js"]); @@ -26,3 +26,139 @@ it("process.exit(0) works", () => { const { exitCode } = spawnSync([bunExe(), import.meta.dir + "/exit-code-0.js"]); expect(exitCode).toBe(0); }); + +// https://github.com/oven-sh/bun/issues/22546 +describe.concurrent("a fatal error during a top-level await ends the run", () => { + // The error comes from a 1ms timer while the module awaits a chain of ten 5ms timers. + // "after" is printed only when the module kept running past the error. + const throws = `setTimeout(() => { throw new Error("boom"); }, 1);\n`; + const rejects = `setTimeout(() => void Promise.reject(new Error("boom")), 1);\n`; + const awaits = ` + for (let i = 0; i < 10; i++) await new Promise(resolve => setTimeout(resolve, 5)); + console.log("after"); + `; + const exitListeners = ` + process.on("beforeExit", () => console.log("beforeExit")); + process.on("exit", code => console.log("exit", code)); + `; + + async function run(files: Record, ...args: string[]) { + using dir = tempDir("tla-fatal-error", files); + await using proc = Bun.spawn({ + cmd: [bunExe(), ...args], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; + } + + it("an uncaught exception", async () => { + const { stdout, stderr, exitCode } = await run({ "entry.mjs": exitListeners + throws + awaits }, "entry.mjs"); + expect(stderr).toContain("error: boom"); + expect({ stdout, exitCode }).toEqual({ stdout: "exit 1\n", exitCode: 1 }); + }); + + it("an unhandled rejection", async () => { + const { stdout, stderr, exitCode } = await run({ "entry.mjs": rejects + awaits }, "entry.mjs"); + expect(stderr).toContain("error: boom"); + expect({ stdout, exitCode }).toEqual({ stdout: "", exitCode: 1 }); + }); + + it("the repro in #22546", async () => { + const { stdout, stderr, exitCode } = await run( + { + "entry.mjs": ` + import { setTimeout as sleep } from "node:timers/promises"; + + let x = 1; + async function erroringPromise() { + return new Promise((_res, rej) => { + rej("oops"); + }); + } + + async function main() { + global.setTimeout(() => erroringPromise(), 1); + + while (x < 10) { + x++; + await sleep(5); + } + console.log("after"); + } + + await main(); + `, + }, + "entry.mjs", + ); + expect(stderr).toContain("oops"); + expect({ stdout, exitCode }).toEqual({ stdout: "", exitCode: 1 }); + }); + + it("reportError(): as for the same code in an async function", async () => { + const reports = `setTimeout(() => reportError(new Error("boom")), 1);\n`; + const [topLevel, inFunction] = await Promise.all([ + run({ "entry.mjs": exitListeners + reports + awaits }, "entry.mjs"), + run({ "entry.mjs": exitListeners + reports + `(async () => {${awaits}})();` }, "entry.mjs"), + ]); + expect(topLevel.stderr).toContain("error: boom"); + expect({ stdout: topLevel.stdout, exitCode: topLevel.exitCode }).toEqual({ + stdout: inFunction.stdout, + exitCode: inFunction.exitCode, + }); + }); + + it("with the await's wakeup already queued from another thread", async () => { + const { stdout, stderr, exitCode } = await run( + { + "entry.mjs": ` + import { stat } from "node:fs/promises"; + ${exitListeners} + const { promise, resolve } = Promise.withResolvers(); + setTimeout(() => { + stat(".").then(resolve); + // Give the thread pool time to finish stat() and queue its result before the error. + const end = performance.now() + 100; + while (performance.now() < end); + throw new Error("boom"); + }, 1); + await promise; + console.log("after"); + `, + }, + "entry.mjs", + ); + expect(stderr).toContain("error: boom"); + expect({ stdout, exitCode }).toEqual({ stdout: "exit 1\n", exitCode: 1 }); + }); + + const onUncaughtException = `process.on("uncaughtException", e => console.log("caught", e.message));\n`; + const onUnhandledRejection = `process.on("unhandledRejection", e => console.log("caught", e.message));\n`; + it.each([ + ["an 'uncaughtException' listener", onUncaughtException + throws, [], "caught boom\n"], + ["an 'unhandledRejection' listener", onUnhandledRejection + rejects, [], "caught boom\n"], + ["--unhandled-rejections=warn", rejects, ["--unhandled-rejections=warn"], ""], + ])("is not fatal with %s", async (_, setup, flags, handled) => { + const { stdout, exitCode } = await run({ "entry.mjs": exitListeners + setup + awaits }, ...flags, "entry.mjs"); + expect({ stdout, exitCode }).toEqual({ stdout: handled + "after\nbeforeExit\nexit 0\n", exitCode: 0 }); + }); + + it("an error that a --preload left behind does not keep the entry from starting", async () => { + const { stdout, stderr, exitCode } = await run( + { + "preload.mjs": `Promise.reject(new Error("boom")); console.log("preload");`, + "entry.mjs": `console.log("entry");` + awaits, + }, + "--preload", + "./preload.mjs", + "entry.mjs", + ); + expect(stderr).toContain("error: boom"); + expect(stdout).toStartWith("preload\nentry\n"); + expect(exitCode).toBe(1); + }); +}); From addff0e3bf330b5e3290a0d42022515790b5c5c5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 14 Sep 2026 07:37:43 +0000 Subject: [PATCH 2/9] Skip the --print result turn after a fatal error; update the HTMLRewriter test Under bun --print a pending result promise gets one more loop turn. After a fatal error that turn resumed the top-level await. Print the promise as it is then. The HTMLRewriter test for a detached rejection expected the top-level await to finish after the fatal error (BODY printed, then exit 1). Split it: with no listener the error is fatal at once, and with an unhandledRejection listener the rewrite still succeeds. --- src/runtime/cli/run_command.rs | 2 + test/js/bun/spawn/exit-code.test.ts | 10 +++++ test/js/workerd/html-rewriter.test.js | 61 ++++++++++++++++----------- 3 files changed, 49 insertions(+), 24 deletions(-) diff --git a/src/runtime/cli/run_command.rs b/src/runtime/cli/run_command.rs index 3459767d089b..3b955f101e0e 100644 --- a/src/runtime/cli/run_command.rs +++ b/src/runtime/cli/run_command.rs @@ -1521,6 +1521,8 @@ impl Run<'_> { .unwrap_or(JSValue::UNDEFINED); if let Some(promise) = result.as_any_promise() { match promise.status() { + // After a fatal error the run is over: no turn that would resume the script. + PromiseStatus::Pending if vm.has_fatal_error() => break 'brk result, PromiseStatus::Pending => { // C-ABI shims are emitted by // `generate-host-exports.ts` into diff --git a/test/js/bun/spawn/exit-code.test.ts b/test/js/bun/spawn/exit-code.test.ts index a1bd7abc1e8c..aef1755a3db8 100644 --- a/test/js/bun/spawn/exit-code.test.ts +++ b/test/js/bun/spawn/exit-code.test.ts @@ -136,6 +136,16 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => expect({ stdout, exitCode }).toEqual({ stdout: "exit 1\n", exitCode: 1 }); }); + it("under --print: the result prints as the pending promise it is", async () => { + const { stdout, stderr, exitCode } = await run( + {}, + "--print", + throws + `await new Promise(resolve => setTimeout(resolve, 50)); console.log("after"); 5`, + ); + expect(stderr).toContain("error: boom"); + expect({ stdout, exitCode }).toEqual({ stdout: "Promise { }\n", exitCode: 1 }); + }); + const onUncaughtException = `process.on("uncaughtException", e => console.log("caught", e.message));\n`; const onUnhandledRejection = `process.on("unhandledRejection", e => console.log("caught", e.message));\n`; it.each([ diff --git a/test/js/workerd/html-rewriter.test.js b/test/js/workerd/html-rewriter.test.js index 1c775108f01d..6ef617fa0881 100644 --- a/test/js/workerd/html-rewriter.test.js +++ b/test/js/workerd/html-rewriter.test.js @@ -1024,31 +1024,44 @@ describe("HTMLRewriter", () => { // Fixture note: it has to be a real-await handler on a Response. A sync // handler on a string input behaves the same pre- and post-PR, so that // shape pins nothing. - it("a detached rejection inside a handler reaches unhandledRejection", async () => { - await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - `const r = new HTMLRewriter() - .on("p", { async element(e) { - (async () => { throw new Error("detached"); })(); - await Bun.sleep(5); - e.setInnerContent("ok"); - } }) - .transform(new Response("

x

")); - console.log("BODY:" + (await r.text()));`, - ], - env: bunEnv, - stdout: "pipe", - stderr: "pipe", + describe("a detached rejection inside a handler reaches unhandledRejection", () => { + async function run(setup) { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `${setup} + const r = new HTMLRewriter() + .on("p", { async element(e) { + (async () => { throw new Error("detached"); })(); + await Bun.sleep(5); + e.setInnerContent("ok"); + } }) + .transform(new Response("

x

")); + console.log("BODY:" + (await r.text()));`, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout: stdout.trim(), reported: stderr.includes("detached"), exitCode }; + } + + // Reported, and it takes the process down at once (as in Node), rather + // than being captured by transform(). The top-level await does not resume. + it("with no listener, it is fatal", async () => { + expect(await run("")).toEqual({ stdout: "", reported: true, exitCode: 1 }); }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - // The rewrite itself succeeds; the detached rejection is reported and - // takes the process down, rather than being captured by transform(). - expect({ stdout: stdout.trim(), reported: stderr.includes("detached"), exitCode }).toEqual({ - stdout: "BODY:

ok

", - reported: true, - exitCode: 1, + + // The listener gets it, not transform(): the rewrite itself succeeds. + it("with a listener, the rewrite succeeds", async () => { + const listener = `process.on("unhandledRejection", e => console.log("UNHANDLED:" + e.message));`; + expect(await run(listener)).toEqual({ + stdout: "UNHANDLED:detached\nBODY:

ok

", + reported: false, + exitCode: 0, + }); }); }); From 4e83695cea0da865655a8d272bac0bc96311f549 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 14 Sep 2026 07:42:14 +0000 Subject: [PATCH 3/9] Shorten the new doc comments --- src/jsc/VirtualMachine.rs | 9 +++------ src/jsc/event_loop.rs | 7 +++---- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index d25c6a44cf8c..c0622f1dc9de 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1407,14 +1407,12 @@ impl VirtualMachine { || !el.next_immediate_tasks.is_empty() } - /// For `bun run`: an error nothing handled has been counted, which ends the run (its run loop - /// stops on `is_event_loop_alive()`). Watch mode counts errors too, and keeps going. + /// An unhandled error has ended this `bun run`. Watch mode counts errors too, and keeps going. pub fn has_fatal_error(&self) -> bool { self.has_fatal_error_since(0) } - /// [`has_fatal_error`](Self::has_fatal_error), for errors counted since - /// `unhandled_error_counter` was `count`. + /// [`Self::has_fatal_error`], for errors counted after `unhandled_error_counter` was `count`. pub fn has_fatal_error_since(&self, count: usize) -> bool { self.unhandled_error_counter > count && !self.is_watcher_enabled() } @@ -3079,8 +3077,7 @@ impl VirtualMachine { } /// `loadEntryPoint(entry_path)` — `reload_entry_point` + spin until the - /// returned promise settles, or a fatal error counted meanwhile ends the run. Watch - /// mode waits on: `Run::start` keeps ticking there whatever the error counter says. + /// returned promise settles or, outside watch mode, a fatal error ends the run. pub fn load_entry_point( &mut self, entry_path: &[u8], diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index 6a266286a118..79e5d0729959 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1112,10 +1112,8 @@ impl EventLoop { self.wait_for_promise_impl::(promise) } - /// [`wait_for_promise`](Self::wait_for_promise) for the entry module of `bun run`. Also returns - /// `Ok`, with `promise` still pending, when a fatal error is counted during the wait: that stops - /// the run loop, so it stops a top-level await too (#22546). An error counted before the wait - /// (by a `--preload`) does not end it: the entry still has to load and start. + /// [`Self::wait_for_promise`] for the entry of `bun run`: also `Ok`, with `promise` pending, + /// once a fatal error is counted during the wait. That ends the run loop too (#22546). pub fn wait_for_module_promise( &mut self, promise: *mut jsc::JSInternalPromise, @@ -1128,6 +1126,7 @@ impl EventLoop { promise: jsc::AnyPromise, ) -> Result<(), jsc::Stopped> { let jsc_vm = self.vm_ref().jsc_vm(); + // An error a `--preload` left behind does not count: the entry still has to load and start. let errors_before = self.vm_ref().unhandled_error_counter; let waiting = |this: &Self| { promise.status() == PromiseStatus::Pending From e546f9bb686dcdac03d0dda73d28a9f9a2a50a82 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 14 Sep 2026 07:44:16 +0000 Subject: [PATCH 4/9] Shorten the wait_for_module_promise doc comment --- src/jsc/event_loop.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index 79e5d0729959..afcb2d4d9200 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1112,8 +1112,7 @@ impl EventLoop { self.wait_for_promise_impl::(promise) } - /// [`Self::wait_for_promise`] for the entry of `bun run`: also `Ok`, with `promise` pending, - /// once a fatal error is counted during the wait. That ends the run loop too (#22546). + /// [`Self::wait_for_promise`], or until a fatal error is counted during the wait (#22546). pub fn wait_for_module_promise( &mut self, promise: *mut jsc::JSInternalPromise, From e091bc9db7f31a407fe8dddedafc38bfe6d2f525 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:09:52 +0000 Subject: [PATCH 5/9] Handle the rejection that the ModuleGraph body fixture expects response-bodies-of-disposed-graphs.mjs reads the body of a Response that a disposed graph was given. The promise rejects, and the fixture only peeks at its status at the end. The rejection was unhandled during the entry's top-level await, so the run now ends there. The host attaches a handler to the promise it expects to reject. --- test/js/bun/module-graph/module-graph-isolation.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/js/bun/module-graph/module-graph-isolation.test.ts b/test/js/bun/module-graph/module-graph-isolation.test.ts index 400d4c0722f1..793f191432f1 100644 --- a/test/js/bun/module-graph/module-graph-isolation.test.ts +++ b/test/js/bun/module-graph/module-graph-isolation.test.ts @@ -1101,6 +1101,8 @@ const dir = String( graph.dispose(); await hostTurn(); const text = app.response.text(); + // An unhandled rejection ends the run, so the host handles the one it expects. + text.catch(() => {}); await hostTurn(); // Graphs disposed while their script awaits a body. for (let i = 0; i < 20; i++) { From 5c3293b09d4fadb1212156d476663f05de58bb07 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:27:29 +0000 Subject: [PATCH 6/9] test: make the --print case independent of a stalled first timer drain The script awaited one 50ms timer after a 1ms timer that throws. When the first timer drain comes 49ms late, both timers are due in that one drain, the module resumes, and the test sees "after" and "5". Let the callback that throws arm the timer the module waits for. That timer cannot be due in the drain that runs the callback. The extra loop turn that --print gives a pending result still fires it, so the test fails without the guard in Run::start. Also say why the --preload control pins only the start of the entry. --- test/js/bun/spawn/exit-code.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/js/bun/spawn/exit-code.test.ts b/test/js/bun/spawn/exit-code.test.ts index aef1755a3db8..8f2aa30b2005 100644 --- a/test/js/bun/spawn/exit-code.test.ts +++ b/test/js/bun/spawn/exit-code.test.ts @@ -140,7 +140,11 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => const { stdout, stderr, exitCode } = await run( {}, "--print", - throws + `await new Promise(resolve => setTimeout(resolve, 50)); console.log("after"); 5`, + // The callback that throws arms the timer the module waits for. So that timer is never due in + // the same timer drain as the error: only the extra turn --print gives a pending result fires it. + `const { promise, resolve } = Promise.withResolvers(); + setTimeout(() => { setTimeout(resolve, 1); throw new Error("boom"); }, 1); + await promise; console.log("after"); 5`, ); expect(stderr).toContain("error: boom"); expect({ stdout, exitCode }).toEqual({ stdout: "Promise { }\n", exitCode: 1 }); @@ -168,6 +172,7 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => "entry.mjs", ); expect(stderr).toContain("error: boom"); + // Node ends this run before "after", so only the start of the entry is pinned. expect(stdout).toStartWith("preload\nentry\n"); expect(exitCode).toBe(1); }); From 76df83aac61b380c1b3f91bcb00d7e94c8f86c19 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:47:43 +0000 Subject: [PATCH 7/9] Gate the post-load tick and the --print turn on the entry's await being cut short Both gates in Run::start asked has_fatal_error(), which is true for any error counted in the run. The entry's wait counts only the errors during the wait, so that an error a --preload left behind lets the entry run. The gates did not agree with that: with such a preload, a pending result of --print lost its extra turn and printed as a pending promise, where main prints its value. Run::start now records that load_entry_point returned with the entry promise pending after a fatal error, and both gates use that. Tests: the queued-wakeup case waits until the event loop reports a queued concurrent task and prints that it saw one, so it cannot pass without its precondition. A new --print case covers the preload error. --- src/runtime/cli/run_command.rs | 17 ++++++++++------- test/js/bun/spawn/exit-code.test.ts | 22 ++++++++++++++++++---- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/runtime/cli/run_command.rs b/src/runtime/cli/run_command.rs index 43ba5ec9f1ad..02fc91899be0 100644 --- a/src/runtime/cli/run_command.rs +++ b/src/runtime/cli/run_command.rs @@ -1566,8 +1566,9 @@ impl Run<'_> { } }; let loaded = (!has_type_errors).then(|| vm.load_entry_point(entry)); - match loaded { - None => {} + // A fatal error during the entry's top-level await: its wait returned with the promise pending. + let entry_cut_short = match loaded { + None => false, Some(Ok(promise)) => { // SAFETY: `promise` is a live GC cell returned by the module loader. let promise = unsafe { &mut *promise }; @@ -1605,16 +1606,18 @@ impl Run<'_> { dump_build_error(vm); log_clear_msgs(vm); } + + promise.status() == PromiseStatus::Pending && vm.has_fatal_error() } Some(Err(err)) => entry_point_load_failed(vm, &err.into()), - } + }; // Drop what transpiling and linking the entry graph left behind before settling into the event loop. A // standalone executable has no transpiler garbage, and its unlinked code blocks came from the embedded bytecode // cache — deleting them here only means decoding them again on first call — so leave its heap to the collector. - // After a fatal error the run is over, and the tick would resume the top-level await that error cut short. + // The tick would resume a top-level await that a fatal error cut short. if vm.standalone_module_graph.is_none() - && !vm.has_fatal_error() + && !entry_cut_short && (vm.is_event_loop_alive() || vm.event_loop_ref().tick_concurrent_with_count() > 0) { vm.global().vm().release_weak_refs(); @@ -1665,8 +1668,8 @@ impl Run<'_> { .unwrap_or(JSValue::UNDEFINED); if let Some(promise) = result.as_any_promise() { match promise.status() { - // After a fatal error the run is over: no turn that would resume the script. - PromiseStatus::Pending if vm.has_fatal_error() => break 'brk result, + // No turn that would resume the top-level await a fatal error cut short. + PromiseStatus::Pending if entry_cut_short => break 'brk result, PromiseStatus::Pending => { // C-ABI shims are emitted by // `generate-host-exports.ts` into diff --git a/test/js/bun/spawn/exit-code.test.ts b/test/js/bun/spawn/exit-code.test.ts index 8f2aa30b2005..2a0162724daa 100644 --- a/test/js/bun/spawn/exit-code.test.ts +++ b/test/js/bun/spawn/exit-code.test.ts @@ -117,13 +117,15 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => { "entry.mjs": ` import { stat } from "node:fs/promises"; + import { getEventLoopStats } from "bun:internal-for-testing"; ${exitListeners} const { promise, resolve } = Promise.withResolvers(); setTimeout(() => { stat(".").then(resolve); - // Give the thread pool time to finish stat() and queue its result before the error. - const end = performance.now() + 100; - while (performance.now() < end); + // The error has to find the result of stat() queued by the thread pool. + const deadline = performance.now() + 3000; + while (getEventLoopStats().concurrentTasksEmpty && performance.now() < deadline); + console.log("queued", !getEventLoopStats().concurrentTasksEmpty); throw new Error("boom"); }, 1); await promise; @@ -133,7 +135,7 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => "entry.mjs", ); expect(stderr).toContain("error: boom"); - expect({ stdout, exitCode }).toEqual({ stdout: "exit 1\n", exitCode: 1 }); + expect({ stdout, exitCode }).toEqual({ stdout: "queued true\nexit 1\n", exitCode: 1 }); }); it("under --print: the result prints as the pending promise it is", async () => { @@ -150,6 +152,18 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => expect({ stdout, exitCode }).toEqual({ stdout: "Promise { }\n", exitCode: 1 }); }); + it("under --print: an error that a --preload left behind leaves the result its turn", async () => { + const { stdout, stderr, exitCode } = await run( + { "preload.mjs": `queueMicrotask(() => { throw new Error("boom"); });` }, + "--preload", + "./preload.mjs", + "--print", + `Bun.sleep(10).then(() => 5)`, + ); + expect(stderr).toContain("error: boom"); + expect({ stdout, exitCode }).toEqual({ stdout: "5\n", exitCode: 1 }); + }); + const onUncaughtException = `process.on("uncaughtException", e => console.log("caught", e.message));\n`; const onUnhandledRejection = `process.on("unhandledRejection", e => console.log("caught", e.message));\n`; it.each([ From afa786d2f5c661bda4d5f4e7b24e642878ce2f41 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:13:23 +0000 Subject: [PATCH 8/9] test: drop the --print control for an error left by a preload The case ran main's own path for a pending --print result after an error, and that path is not stable enough to pin here: - The extra loop turn does not wait for a 10ms timer on macOS and Windows, so the result prints as a pending promise there. - The reaction that prints the result exits without the VM teardown. With the ASAN lane's options LeakSanitizer then reports a source map and aborts (exit 134). Both happen on main without this branch. --- test/js/bun/spawn/exit-code.test.ts | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/test/js/bun/spawn/exit-code.test.ts b/test/js/bun/spawn/exit-code.test.ts index 2a0162724daa..1d8a79fac860 100644 --- a/test/js/bun/spawn/exit-code.test.ts +++ b/test/js/bun/spawn/exit-code.test.ts @@ -152,18 +152,6 @@ describe.concurrent("a fatal error during a top-level await ends the run", () => expect({ stdout, exitCode }).toEqual({ stdout: "Promise { }\n", exitCode: 1 }); }); - it("under --print: an error that a --preload left behind leaves the result its turn", async () => { - const { stdout, stderr, exitCode } = await run( - { "preload.mjs": `queueMicrotask(() => { throw new Error("boom"); });` }, - "--preload", - "./preload.mjs", - "--print", - `Bun.sleep(10).then(() => 5)`, - ); - expect(stderr).toContain("error: boom"); - expect({ stdout, exitCode }).toEqual({ stdout: "5\n", exitCode: 1 }); - }); - const onUncaughtException = `process.on("uncaughtException", e => console.log("caught", e.message));\n`; const onUnhandledRejection = `process.on("unhandledRejection", e => console.log("caught", e.message));\n`; it.each([ From 951a5fa4b2ac57cc67037a1aa29cdd28e1930add Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:59:14 +0000 Subject: [PATCH 9/9] ci: retrigger