diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index 869f8eb4b873..bc1481b833d5 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1835,6 +1835,16 @@ impl VirtualMachine { || !el.next_immediate_tasks.is_empty() } + /// 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) + } + + /// [`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() + } + pub fn wakeup(&mut self) { self.event_loop_mut().wakeup(); } @@ -3516,6 +3526,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] @@ -3704,7 +3723,7 @@ impl VirtualMachine { } /// `loadEntryPoint(entry_path)` — `reload_entry_point` + spin until the - /// returned promise settles. + /// returned promise settles or, outside watch mode, a fatal error ends the run. pub fn load_entry_point( &mut self, entry_path: Option<&[u8]>, @@ -3735,7 +3754,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 1763863bc57b..309fe9044878 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1134,11 +1134,29 @@ 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) + } + + /// [`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, + ) -> 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 { + // 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 + && !(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() @@ -1146,7 +1164,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 b5080b7f7ddc..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,14 +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. + // The tick would resume a top-level await that a fatal error cut short. if vm.standalone_module_graph.is_none() + && !entry_cut_short && (vm.is_event_loop_alive() || vm.event_loop_ref().tick_concurrent_with_count() > 0) { vm.global().vm().release_weak_refs(); @@ -1663,6 +1668,8 @@ impl Run<'_> { .unwrap_or(JSValue::UNDEFINED); if let Some(promise) = result.as_any_promise() { match promise.status() { + // 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/module-graph/module-graph-isolation.test.ts b/test/js/bun/module-graph/module-graph-isolation.test.ts index 4e1ecf891b3e..fed0a89badce 100644 --- a/test/js/bun/module-graph/module-graph-isolation.test.ts +++ b/test/js/bun/module-graph/module-graph-isolation.test.ts @@ -1106,6 +1106,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++) { diff --git a/test/js/bun/spawn/exit-code.test.ts b/test/js/bun/spawn/exit-code.test.ts index c0510ced6a49..1d8a79fac860 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,156 @@ 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"; + import { getEventLoopStats } from "bun:internal-for-testing"; + ${exitListeners} + const { promise, resolve } = Promise.withResolvers(); + setTimeout(() => { + stat(".").then(resolve); + // 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; + console.log("after"); + `, + }, + "entry.mjs", + ); + expect(stderr).toContain("error: boom"); + 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 () => { + const { stdout, stderr, exitCode } = await run( + {}, + "--print", + // 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 }); + }); + + 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"); + // 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); + }); +}); diff --git a/test/js/workerd/html-rewriter.test.js b/test/js/workerd/html-rewriter.test.js index 9260f59efc23..a71951eae717 100644 --- a/test/js/workerd/html-rewriter.test.js +++ b/test/js/workerd/html-rewriter.test.js @@ -1150,31 +1150,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, + }); }); });