Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,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();
}
Expand Down Expand Up @@ -2882,6 +2892,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]
Expand Down Expand Up @@ -3058,7 +3077,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: &[u8],
Expand Down Expand Up @@ -3089,7 +3108,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))
Expand Down
28 changes: 23 additions & 5 deletions src/jsc/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1109,19 +1109,37 @@ 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::<false>(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::<true>(jsc::AnyPromise::Internal(promise))
}

fn wait_for_promise_impl<const UNTIL_FATAL_ERROR: bool>(
&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()
{
return Err(jsc::Stopped);
}
self.tick();
if promise.status() == PromiseStatus::Pending {
if waiting(self) {
self.auto_tick();
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
&& (vm.is_event_loop_alive() || vm.event_loop_ref().tick_concurrent_with_count() > 0)
Comment thread
robobun marked this conversation as resolved.
Resolved
{
vm.global().vm().release_weak_refs();
Expand Down Expand Up @@ -1519,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,
Comment thread
robobun marked this conversation as resolved.
Resolved
PromiseStatus::Pending => {
// C-ABI shims are emitted by
// `generate-host-exports.ts` into
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down
150 changes: 148 additions & 2 deletions test/js/bun/spawn/exit-code.test.ts
Original file line number Diff line number Diff line change
@@ -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"]);
Expand All @@ -26,3 +26,149 @@ 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<string, string>, ...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",
);
Comment thread
robobun marked this conversation as resolved.
Resolved
expect(stderr).toContain("error: boom");
expect({ stdout, exitCode }).toEqual({ stdout: "exit 1\n", exitCode: 1 });
});
Comment thread
robobun marked this conversation as resolved.
Resolved

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 { <pending> }\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 });
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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);
Comment thread
robobun marked this conversation as resolved.
Resolved
});
});
61 changes: 37 additions & 24 deletions test/js/workerd/html-rewriter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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("<p>x</p>"));
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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
e.setInnerContent("ok");
} })
.transform(new Response("<p>x</p>"));
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:<p>ok</p>",
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:<p>ok</p>",
reported: false,
exitCode: 0,
});
});
});

Expand Down
Loading