From b54d4b22cb281a1f957dd8a6c41b7b30e8013b03 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 10 Sep 2026 10:27:35 +0000 Subject: [PATCH 01/16] shell: reject the ShellPromise when a state throws after the first suspension A `${value}` redirect that the command cannot use (an in-memory Blob or Response as stdout) throws a JS exception from inside the shell state machine and the state returns Yield::Failed. The trampoline treated Failed like Suspended, so only run_from_js (the first synchronous stretch of the script) ever looked at the VM afterwards. Raised from any other driver (a previous command's exit, a pipe or task callback) the exception stayed pending on the VM with no JS frame to take it: the next event-loop tick hit 'a task returned Ok with a JS exception pending' in debug builds and abort() in release builds, and the ShellPromise never settled. Even in the first-command case the interpreter was never finished, so its keep-alive held the process open. Yield::Failed is now terminal for the interpreter under every driver: Yield::run takes the pending exception, rejects the ShellPromise with it, releases the keep-alive and lets the interpreter be collected. The Failed producers that did not throw (the WaitingWriteErr arms of the builtins and the Windows IOReader start error) return Suspended, which is what they meant. --- src/js/builtins/shell.ts | 4 +- src/runtime/shell/IOReader.rs | 3 +- src/runtime/shell/Yield.rs | 13 ++- src/runtime/shell/builtin/cat.rs | 2 +- src/runtime/shell/builtin/cp.rs | 2 +- src/runtime/shell/builtin/ls.rs | 2 +- src/runtime/shell/builtin/mkdir.rs | 2 +- src/runtime/shell/builtin/mv.rs | 2 +- src/runtime/shell/builtin/touch.rs | 2 +- src/runtime/shell/interpreter.rs | 98 ++++++++++++++++++- src/runtime/shell/subproc.rs | 2 +- .../bun/shell/redirect-js-value-error.test.ts | 65 ++++++++++++ 12 files changed, 184 insertions(+), 13 deletions(-) create mode 100644 test/js/bun/shell/redirect-js-value-error.test.ts diff --git a/src/js/builtins/shell.ts b/src/js/builtins/shell.ts index eb40883e52ed..f01bd294bdf8 100644 --- a/src/js/builtins/shell.ts +++ b/src/js/builtins/shell.ts @@ -131,7 +131,9 @@ export function createBunShellTemplateFunction(createShellInterpreter_, createPa res(out); } }; - // Only for a failure to build the output buffers; exit codes go through `resolve`. + // A JS error raised by the interpreter itself (an unusable `${value}` + // redirect, a failure to build the output buffers). Exit codes go + // through `resolve`. reject = error => { potentialError = undefined; rej(error); diff --git a/src/runtime/shell/IOReader.rs b/src/runtime/shell/IOReader.rs index 0484e6ed5c2b..fd551e82a3a4 100644 --- a/src/runtime/shell/IOReader.rs +++ b/src/runtime/shell/IOReader.rs @@ -230,8 +230,9 @@ impl IOReader { } s.is_reading = true; if let Err(e) = self.reader().start_with_current_pipe() { + // Completes every registered reader with the error, as the + // POSIX arm does; nothing is left for this Yield to drive. self.on_reader_error(&e); - return Yield::failed(); } Yield::suspended() } diff --git a/src/runtime/shell/Yield.rs b/src/runtime/shell/Yield.rs index 351032832410..983b46ffebdd 100644 --- a/src/runtime/shell/Yield.rs +++ b/src/runtime/shell/Yield.rs @@ -37,7 +37,10 @@ pub enum Yield { /// Execution is waiting on async IO (epoll/kqueue/uv). The caller's task /// callback will resume by calling `.run()` again later. Suspended, - /// Threw a JS error. + /// A JS exception is pending on the VM and the state cannot continue. + /// Terminal for the whole interpreter: the trampoline takes the exception + /// and rejects the `ShellPromise` with it + /// (`Interpreter::reject_with_pending_exception`), whichever driver ran it. Failed, Done, } @@ -131,7 +134,13 @@ impl Yield { written, err, } => crate::shell::io_writer::on_io_writer_chunk(interp, child, written, err), - Yield::Suspended | Yield::Failed | Yield::Done => { + Yield::Failed => { + // No `drain_pipelines`: the script is over, so the rest of + // a pipeline's members are not started. + interp.reject_with_pending_exception(); + return; + } + Yield::Suspended | Yield::Done => { if let Some(y) = Self::drain_pipelines(interp, &mut pipeline_stack) { y } else { diff --git a/src/runtime/shell/builtin/cat.rs b/src/runtime/shell/builtin/cat.rs index ef09d1f66a76..f1b338640653 100644 --- a/src/runtime/shell/builtin/cat.rs +++ b/src/runtime/shell/builtin/cat.rs @@ -232,7 +232,7 @@ impl Cat { }); reader.start() } - Branch::WaitingErr => Yield::failed(), + Branch::WaitingErr => Yield::suspended(), } } diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index f51257afdfcd..13ea496977f8 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -144,7 +144,7 @@ impl Cp { } #[cfg(windows)] State::Ebusy(_) => return Self::ignore_ebusy_error_if_possible(interp, cmd), - State::WaitingWriteErr => return Yield::failed(), + State::WaitingWriteErr => return Yield::suspended(), State::Done => return Builtin::done(interp, cmd, 0), }; match action { diff --git a/src/runtime/shell/builtin/ls.rs b/src/runtime/shell/builtin/ls.rs index 082c052687a8..887352e0bf7b 100644 --- a/src/runtime/shell/builtin/ls.rs +++ b/src/runtime/shell/builtin/ls.rs @@ -168,7 +168,7 @@ impl Ls { } Yield::suspended() } - Tag::WaitingWriteErr => Yield::failed(), + Tag::WaitingWriteErr => Yield::suspended(), Tag::Done => Builtin::done(interp, cmd, 0), } } diff --git a/src/runtime/shell/builtin/mkdir.rs b/src/runtime/shell/builtin/mkdir.rs index df2515693382..a444fe3e6637 100644 --- a/src/runtime/shell/builtin/mkdir.rs +++ b/src/runtime/shell/builtin/mkdir.rs @@ -107,7 +107,7 @@ impl Mkdir { NextAction::Schedule(exec.args_start) } } - State::WaitingWriteErr => return Yield::failed(), + State::WaitingWriteErr => return Yield::suspended(), State::Done => return Builtin::done(interp, cmd, 0), }; match action { diff --git a/src/runtime/shell/builtin/mv.rs b/src/runtime/shell/builtin/mv.rs index ef318c0037e0..bfbce264cbe8 100644 --- a/src/runtime/shell/builtin/mv.rs +++ b/src/runtime/shell/builtin/mv.rs @@ -271,7 +271,7 @@ impl Mv { // Shouldn't happen — driven by batchedMoveTaskDone. Yield::suspended() } - Tag::WaitingWriteErr => Yield::failed(), + Tag::WaitingWriteErr => Yield::suspended(), Tag::Done => Builtin::done(interp, cmd, 0), Tag::Err => Builtin::done(interp, cmd, 1), } diff --git a/src/runtime/shell/builtin/touch.rs b/src/runtime/shell/builtin/touch.rs index c4ef56c0ff31..8a5ef6b02c76 100644 --- a/src/runtime/shell/builtin/touch.rs +++ b/src/runtime/shell/builtin/touch.rs @@ -95,7 +95,7 @@ impl Touch { Action::Schedule(exec.args_start) } } - State::WaitingWriteErr => return Yield::failed(), + State::WaitingWriteErr => return Yield::suspended(), State::Done => return Builtin::done(interp, cmd, 0), }; match action { diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 3cdf1eba50c1..1e7e183779a4 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -332,6 +332,14 @@ impl InterpreterFlags { pub(crate) fn set_quiet(&mut self, v: bool) { if v { self.0 |= 0b10 } else { self.0 &= !0b10 } } + /// A state threw a JS exception (`Yield::Failed`) and the `ShellPromise` + /// was rejected with it; see [`Interpreter::reject_with_pending_exception`]. + pub(crate) const fn failed(self) -> bool { + self.0 & 0b100 != 0 + } + pub(crate) fn set_failed(&mut self, v: bool) { + if v { self.0 |= 0b100 } else { self.0 &= !0b100 } + } } #[repr(u8)] @@ -1332,6 +1340,89 @@ impl Interpreter { Yield::done() } + /// The `Yield::Failed` arm of the trampoline: a state threw a JS + /// exception and cannot continue. Terminal under every driver (the JS + /// host call, a process exit, a pipe or task callback): the exception is + /// taken off the VM here and the `ShellPromise` is rejected with it, so no + /// driver returns to the event loop with the exception still pending and + /// the promise unsettled. + /// + /// The failed node never reports to its parent, so `finish` does not run + /// afterwards. The remaining nodes are left for the GC finalizer + /// (`CleanupState::NeedsFullCleanup`), which is why nothing is freed here: + /// a pipeline sibling that is still running reads its `Cmd` node, the AST + /// arena and the root `ShellExecEnv` when its exit or pipe close arrives. + pub(crate) fn reject_with_pending_exception(&self) { + use crate::jsc::JSValue; + use crate::jsc::generated::JSShellInterpreter; + + // Mini event loop: `Interpreter::throw` prints and exits instead. + let Some(global_this) = self.global_this_ref() else { + return; + }; + log!( + "Interpreter(0x{:x}) reject with pending exception", + std::ptr::from_ref(self) as usize + ); + + // A termination exception (`worker.terminate()`) is not the script's + // error and cannot be taken; it keeps unwinding on its own. + let terminating = global_this.has_pending_termination_exception(); + let exception = if terminating { + None + } else { + global_this.try_take_exception() + }; + + if self.flags.get().failed() { + // Another pipeline member, started before the first one failed, + // failed too. The promise is already rejected; the exception taken + // above is dropped. + return; + } + self.update_flags(|f| f.set_failed(true)); + self.keep_alive.with_mut(|k| k.disable()); + + let this_jsvalue = self.this_jsvalue.get(); + if this_jsvalue != JSValue::ZERO && !terminating { + if let Some(reject) = JSShellInterpreter::reject_get_cached(this_jsvalue) { + debug_assert!( + exception.is_some(), + "Yield::Failed without a pending JS exception" + ); + let error = match exception { + Some(exception) => exception.to_error().unwrap_or(exception), + None => global_this + .create_error_instance(format_args!("The shell interpreter failed")), + }; + let _entered = self.event_loop.entered(); + global_this.bun_vm().event_loop_mut().run_callback( + reject, + global_this, + JSValue::UNDEFINED, + &[error], + ); + } + JSShellInterpreter::resolve_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + } + + // Paired with the increment in `run_from_js`: lets the GC collect the + // wrapper and finalize the interpreter. A pipeline or `&` command runs + // its members concurrently, so one of them can still have a process, + // pipe or task in flight whose callback reaches back into this + // interpreter. The finalizer's in-flight teardown is only safe at VM + // shutdown, so in that case the interpreter stays alive until then. + let concurrent = self + .nodes + .get() + .iter() + .any(|n| matches!(n.kind(), StateKind::Pipeline | StateKind::Async)); + if !concurrent { + Self::decr_pending_activity_flag(&self.has_pending_activity); + } + } + /// JS-host entrypoint — sets up root IO /// (unless quiet), spawns the root `Script` node, and starts ticking. pub(crate) fn run_from_js( @@ -1441,8 +1532,11 @@ impl Interpreter { match this.cleanup_state.get() { CleanupState::NeedsFullCleanup => { - // The script is still in flight (e.g. `worker.terminate()` - // mid-command) and `Node` has no `Drop` for its raw-pointer + // The script did not finish: it is still in flight + // (`worker.terminate()` mid-command), or a state threw and the + // promise was rejected (`reject_with_pending_exception`, which + // keeps the wrapper alive instead when a pipeline member may + // still be running). `Node` has no `Drop` for its raw-pointer // resources: deinit every live `Cmd` (kills the child, frees // the `ShellSubprocess`, readers, redirection fd). Slots stay // occupied so the env walk below still sees pipeline-duped diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index a7a6afd18b58..96a931236618 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -1688,7 +1688,7 @@ impl PipeReader { fn run_yield_with(interp: *mut crate::shell::interpreter::Interpreter, y: Yield) { if interp.is_null() { debug_assert!( - matches!(y, Yield::Done | Yield::Suspended | Yield::Failed), + matches!(y, Yield::Done | Yield::Suspended), "PipeReader async callback fired without interp backref" ); return; diff --git a/test/js/bun/shell/redirect-js-value-error.test.ts b/test/js/bun/shell/redirect-js-value-error.test.ts new file mode 100644 index 000000000000..41c70c243ba2 --- /dev/null +++ b/test/js/bun/shell/redirect-js-value-error.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +// A `${value}` redirect target that the command cannot use (an in-memory Blob +// or Response as stdout) is reported as a JS error. When that command is not +// the first thing the script runs, the error is raised from an event-loop +// callback (the previous command's exit) instead of from the `.run()` host +// call. The ShellPromise must still reject with it, no exception may be left +// pending on the VM, and the process must be able to exit afterwards. Each +// case runs in its own process so that a hang or crash stays contained. +describe("a redirect to a JS value the command cannot use rejects the shell promise", () => { + async function run(shell: string) { + const script = /* js */ ` + import { $ } from "bun"; + const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); + const bun = process.execPath; + const out = []; + out.push(await settle(${shell})); + // The VM is still usable afterwards: nothing was left pending on it. + out.push(await settle($\`echo ok\`.quiet())); + console.log(JSON.stringify(out)); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { out: stdout.trim() === "" ? stderr : JSON.parse(stdout.trim()), exitCode }; + } + + const external = "rejected TypeError: Blobs are immutable, and cannot be used for stdout/stderr"; + const builtin = "rejected Error: Cannot redirect stdout/stderr to an immutable blob. Expected a file"; + + test.concurrent("external command after another command", async () => { + expect(await run("$`${bun} --version; ${bun} --version > ${new Response('r')}`.quiet().nothrow()")).toEqual({ + out: [external, "resolved 0"], + exitCode: 0, + }); + }); + + test.concurrent("builtin after another command", async () => { + expect(await run("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()")).toEqual({ + out: [builtin, "resolved 0"], + exitCode: 0, + }); + }); + + test.concurrent("inside && after another command", async () => { + expect(await run("$`${bun} --version && echo hi > ${new Response('r')} && echo no`.quiet()")).toEqual({ + out: [builtin, "resolved 0"], + exitCode: 0, + }); + }); + + // This already rejected (the error comes straight out of `.run()`), but the + // interpreter was never finished, so it kept the event loop alive forever. + test.concurrent("as the first command, and the process still exits", async () => { + expect(await run("$`echo hi > ${new Response('r')}; echo no`.quiet().nothrow()")).toEqual({ + out: [builtin, "resolved 0"], + exitCode: 0, + }); + }); +}); From 861f7f9450839155c50153bbb483c7eb9d04f3e7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 10 Sep 2026 10:30:53 +0000 Subject: [PATCH 02/16] test: use a Blob target for the builtin cases --- test/js/bun/shell/redirect-js-value-error.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/js/bun/shell/redirect-js-value-error.test.ts b/test/js/bun/shell/redirect-js-value-error.test.ts index 41c70c243ba2..da6e3162403b 100644 --- a/test/js/bun/shell/redirect-js-value-error.test.ts +++ b/test/js/bun/shell/redirect-js-value-error.test.ts @@ -48,7 +48,7 @@ describe("a redirect to a JS value the command cannot use rejects the shell prom }); test.concurrent("inside && after another command", async () => { - expect(await run("$`${bun} --version && echo hi > ${new Response('r')} && echo no`.quiet()")).toEqual({ + expect(await run("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()")).toEqual({ out: [builtin, "resolved 0"], exitCode: 0, }); @@ -57,7 +57,7 @@ describe("a redirect to a JS value the command cannot use rejects the shell prom // This already rejected (the error comes straight out of `.run()`), but the // interpreter was never finished, so it kept the event loop alive forever. test.concurrent("as the first command, and the process still exits", async () => { - expect(await run("$`echo hi > ${new Response('r')}; echo no`.quiet().nothrow()")).toEqual({ + expect(await run("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()")).toEqual({ out: [builtin, "resolved 0"], exitCode: 0, }); From e10e83e7520bc987590853cd4ab45159155a441e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 10 Sep 2026 23:59:48 +0000 Subject: [PATCH 03/16] shell: move the Failed tests into yield.test.ts, tidy the reject path The tests exercise the Yield::run trampoline, so they live with the other trampoline tests. Adds a pipeline case. The exception-to-error conversion has one fallback, and finish() asserts that it cannot run after a rejection. --- src/runtime/shell/interpreter.rs | 36 +++++----- .../bun/shell/redirect-js-value-error.test.ts | 65 ----------------- test/js/bun/shell/yield.test.ts | 72 +++++++++++++++++++ 3 files changed, 92 insertions(+), 81 deletions(-) delete mode 100644 test/js/bun/shell/redirect-js-value-error.test.ts diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 1e7e183779a4..58b57ef18705 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -1257,6 +1257,9 @@ impl Interpreter { std::ptr::from_ref(self) as usize, exit_code ); + // A node that returned `Yield::Failed` never reports to its parent, so + // the root script cannot complete after the promise was rejected. + debug_assert!(!self.flags.get().failed()); // Decrement pending activity unconditionally on exit. Paired with the // increment in `run_from_js`; harmless wrap on the mini path (flag is // only read from the JS GC `hasPendingActivity()` hook). @@ -1365,18 +1368,26 @@ impl Interpreter { std::ptr::from_ref(self) as usize ); - // A termination exception (`worker.terminate()`) is not the script's - // error and cannot be taken; it keeps unwinding on its own. - let terminating = global_this.has_pending_termination_exception(); - let exception = if terminating { + // The VM's termination (`worker.terminate()`) is not the script's + // error: it stays pending and keeps unwinding, and settles nothing. + let error = if global_this.has_pending_termination_exception() { None } else { - global_this.try_take_exception() + Some( + global_this + .try_take_exception() + .and_then(JSValue::to_error) + .unwrap_or_else(|| { + debug_assert!(false, "Yield::Failed without a pending JS exception"); + global_this + .create_error_instance(format_args!("The shell interpreter failed")) + }), + ) }; if self.flags.get().failed() { // Another pipeline member, started before the first one failed, - // failed too. The promise is already rejected; the exception taken + // failed too. The promise is already rejected; the error taken // above is dropped. return; } @@ -1384,17 +1395,10 @@ impl Interpreter { self.keep_alive.with_mut(|k| k.disable()); let this_jsvalue = self.this_jsvalue.get(); - if this_jsvalue != JSValue::ZERO && !terminating { + if let Some(error) = error + && this_jsvalue != JSValue::ZERO + { if let Some(reject) = JSShellInterpreter::reject_get_cached(this_jsvalue) { - debug_assert!( - exception.is_some(), - "Yield::Failed without a pending JS exception" - ); - let error = match exception { - Some(exception) => exception.to_error().unwrap_or(exception), - None => global_this - .create_error_instance(format_args!("The shell interpreter failed")), - }; let _entered = self.event_loop.entered(); global_this.bun_vm().event_loop_mut().run_callback( reject, diff --git a/test/js/bun/shell/redirect-js-value-error.test.ts b/test/js/bun/shell/redirect-js-value-error.test.ts deleted file mode 100644 index da6e3162403b..000000000000 --- a/test/js/bun/shell/redirect-js-value-error.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe } from "harness"; - -// A `${value}` redirect target that the command cannot use (an in-memory Blob -// or Response as stdout) is reported as a JS error. When that command is not -// the first thing the script runs, the error is raised from an event-loop -// callback (the previous command's exit) instead of from the `.run()` host -// call. The ShellPromise must still reject with it, no exception may be left -// pending on the VM, and the process must be able to exit afterwards. Each -// case runs in its own process so that a hang or crash stays contained. -describe("a redirect to a JS value the command cannot use rejects the shell promise", () => { - async function run(shell: string) { - const script = /* js */ ` - import { $ } from "bun"; - const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); - const bun = process.execPath; - const out = []; - out.push(await settle(${shell})); - // The VM is still usable afterwards: nothing was left pending on it. - out.push(await settle($\`echo ok\`.quiet())); - console.log(JSON.stringify(out)); - `; - await using proc = Bun.spawn({ - cmd: [bunExe(), "-e", script], - env: bunEnv, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { out: stdout.trim() === "" ? stderr : JSON.parse(stdout.trim()), exitCode }; - } - - const external = "rejected TypeError: Blobs are immutable, and cannot be used for stdout/stderr"; - const builtin = "rejected Error: Cannot redirect stdout/stderr to an immutable blob. Expected a file"; - - test.concurrent("external command after another command", async () => { - expect(await run("$`${bun} --version; ${bun} --version > ${new Response('r')}`.quiet().nothrow()")).toEqual({ - out: [external, "resolved 0"], - exitCode: 0, - }); - }); - - test.concurrent("builtin after another command", async () => { - expect(await run("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()")).toEqual({ - out: [builtin, "resolved 0"], - exitCode: 0, - }); - }); - - test.concurrent("inside && after another command", async () => { - expect(await run("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()")).toEqual({ - out: [builtin, "resolved 0"], - exitCode: 0, - }); - }); - - // This already rejected (the error comes straight out of `.run()`), but the - // interpreter was never finished, so it kept the event loop alive forever. - test.concurrent("as the first command, and the process still exits", async () => { - expect(await run("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()")).toEqual({ - out: [builtin, "resolved 0"], - exitCode: 0, - }); - }); -}); diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 1a47205ff514..d70822e18168 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -101,4 +101,76 @@ describe("yield", async () => { exitCode: 0, }); }); + + // A `${value}` redirect target the command cannot use (an in-memory Blob or + // Response as stdout) is a JS error thrown inside the state machine. When the + // command is not the first thing the script runs, the trampoline is driven + // by an event-loop callback (the previous command's exit), not by the + // `.run()` host call. The promise must still reject with the error, nothing + // may stay pending on the VM, and the process must exit on its own. + describe("a state that throws a JS error rejects the shell promise", () => { + async function run(shell: string) { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + import { $ } from "bun"; + const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); + const bun = process.execPath; + const out = [await settle(${shell})]; + // The VM is still usable: no exception was left pending on it. + out.push(await settle($\`echo ok\`.quiet())); + console.log(JSON.stringify(out)); + `, + "--debug-crash-handler-use-trace-string", + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { out: stdout.trim() === "" ? stderr : JSON.parse(stdout.trim()), exitCode }; + } + + const external = "rejected TypeError: Blobs are immutable, and cannot be used for stdout/stderr"; + const builtin = "rejected Error: Cannot redirect stdout/stderr to an immutable blob. Expected a file"; + + test.concurrent("external command after another command", async () => { + expect(await run("$`${bun} --version; ${bun} --version > ${new Response('r')}`.quiet().nothrow()")).toEqual({ + out: [external, "resolved 0"], + exitCode: 0, + }); + }); + + test.concurrent("builtin after another command", async () => { + expect(await run("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()")).toEqual({ + out: [builtin, "resolved 0"], + exitCode: 0, + }); + }); + + test.concurrent("in an && chain after another command", async () => { + expect(await run("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()")).toEqual({ + out: [builtin, "resolved 0"], + exitCode: 0, + }); + }); + + test.concurrent("last member of a pipeline", async () => { + expect(await run("$`${bun} --version | ${bun} --version > ${new Response('r')}`.quiet().nothrow()")).toEqual({ + out: [external, "resolved 0"], + exitCode: 0, + }); + }); + + // This one always rejected (the error comes straight out of `.run()`), but + // the interpreter was never finished and kept the event loop alive forever. + test.concurrent("first command, and the process still exits", async () => { + expect(await run("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()")).toEqual({ + out: [builtin, "resolved 0"], + exitCode: 0, + }); + }); + }); }); From 81cf1060fc9062dec8b076d2eefa06a5f343a605 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 01:09:12 +0000 Subject: [PATCH 04/16] test: assert the child's stderr in the shell rejection cases --- test/js/bun/shell/yield.test.ts | 38 ++++++++++++++------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index d70822e18168..10bab9d37ed7 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -109,7 +109,7 @@ describe("yield", async () => { // `.run()` host call. The promise must still reject with the error, nothing // may stay pending on the VM, and the process must exit on its own. describe("a state that throws a JS error rejects the shell promise", () => { - async function run(shell: string) { + async function expectRejection(shell: string, rejection: string) { await using proc = Bun.spawn({ cmd: [ bunExe(), @@ -129,48 +129,42 @@ describe("yield", async () => { stdout: "pipe", stderr: "pipe", }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { out: stdout.trim() === "" ? stderr : JSON.parse(stdout.trim()), exitCode }; + + expect({ result: stdout.trim(), stderr, exitCode }).toEqual({ + result: JSON.stringify([rejection, "resolved 0"]), + stderr: "", + exitCode: 0, + }); } const external = "rejected TypeError: Blobs are immutable, and cannot be used for stdout/stderr"; const builtin = "rejected Error: Cannot redirect stdout/stderr to an immutable blob. Expected a file"; test.concurrent("external command after another command", async () => { - expect(await run("$`${bun} --version; ${bun} --version > ${new Response('r')}`.quiet().nothrow()")).toEqual({ - out: [external, "resolved 0"], - exitCode: 0, - }); + await expectRejection("$`${bun} --version; ${bun} --version > ${new Response('r')}`.quiet().nothrow()", external); }); test.concurrent("builtin after another command", async () => { - expect(await run("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()")).toEqual({ - out: [builtin, "resolved 0"], - exitCode: 0, - }); + await expectRejection("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()", builtin); }); test.concurrent("in an && chain after another command", async () => { - expect(await run("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()")).toEqual({ - out: [builtin, "resolved 0"], - exitCode: 0, - }); + await expectRejection("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()", builtin); }); test.concurrent("last member of a pipeline", async () => { - expect(await run("$`${bun} --version | ${bun} --version > ${new Response('r')}`.quiet().nothrow()")).toEqual({ - out: [external, "resolved 0"], - exitCode: 0, - }); + await expectRejection( + "$`${bun} --version | ${bun} --version > ${new Response('r')}`.quiet().nothrow()", + external, + ); }); // This one always rejected (the error comes straight out of `.run()`), but // the interpreter was never finished and kept the event loop alive forever. test.concurrent("first command, and the process still exits", async () => { - expect(await run("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()")).toEqual({ - out: [builtin, "resolved 0"], - exitCode: 0, - }); + await expectRejection("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()", builtin); }); }); }); From ddc4fae1319dc9d64f072036e45a8b95cc3f8eea Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 01:46:09 +0000 Subject: [PATCH 05/16] shell: cut the new comments down to one line each --- src/js/builtins/shell.ts | 4 +-- src/runtime/shell/IOReader.rs | 2 -- src/runtime/shell/Yield.rs | 8 ++---- src/runtime/shell/interpreter.rs | 48 +++++++++----------------------- 4 files changed, 16 insertions(+), 46 deletions(-) diff --git a/src/js/builtins/shell.ts b/src/js/builtins/shell.ts index f01bd294bdf8..f4780c796db5 100644 --- a/src/js/builtins/shell.ts +++ b/src/js/builtins/shell.ts @@ -131,9 +131,7 @@ export function createBunShellTemplateFunction(createShellInterpreter_, createPa res(out); } }; - // A JS error raised by the interpreter itself (an unusable `${value}` - // redirect, a failure to build the output buffers). Exit codes go - // through `resolve`. + // Only for a JS error raised by the interpreter itself; exit codes go through `resolve`. reject = error => { potentialError = undefined; rej(error); diff --git a/src/runtime/shell/IOReader.rs b/src/runtime/shell/IOReader.rs index fd551e82a3a4..110d85cab602 100644 --- a/src/runtime/shell/IOReader.rs +++ b/src/runtime/shell/IOReader.rs @@ -230,8 +230,6 @@ impl IOReader { } s.is_reading = true; if let Err(e) = self.reader().start_with_current_pipe() { - // Completes every registered reader with the error, as the - // POSIX arm does; nothing is left for this Yield to drive. self.on_reader_error(&e); } Yield::suspended() diff --git a/src/runtime/shell/Yield.rs b/src/runtime/shell/Yield.rs index 983b46ffebdd..b7f465b6c17a 100644 --- a/src/runtime/shell/Yield.rs +++ b/src/runtime/shell/Yield.rs @@ -37,10 +37,7 @@ pub enum Yield { /// Execution is waiting on async IO (epoll/kqueue/uv). The caller's task /// callback will resume by calling `.run()` again later. Suspended, - /// A JS exception is pending on the VM and the state cannot continue. - /// Terminal for the whole interpreter: the trampoline takes the exception - /// and rejects the `ShellPromise` with it - /// (`Interpreter::reject_with_pending_exception`), whichever driver ran it. + /// A JS exception is pending; terminal (`Interpreter::reject_with_pending_exception`). Failed, Done, } @@ -135,8 +132,7 @@ impl Yield { err, } => crate::shell::io_writer::on_io_writer_chunk(interp, child, written, err), Yield::Failed => { - // No `drain_pipelines`: the script is over, so the rest of - // a pipeline's members are not started. + // The script is over: the rest of a pipeline's members are not started. interp.reject_with_pending_exception(); return; } diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 58b57ef18705..91b6027fa8ab 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -332,8 +332,7 @@ impl InterpreterFlags { pub(crate) fn set_quiet(&mut self, v: bool) { if v { self.0 |= 0b10 } else { self.0 &= !0b10 } } - /// A state threw a JS exception (`Yield::Failed`) and the `ShellPromise` - /// was rejected with it; see [`Interpreter::reject_with_pending_exception`]. + /// Set by [`Interpreter::reject_with_pending_exception`]. pub(crate) const fn failed(self) -> bool { self.0 & 0b100 != 0 } @@ -1257,9 +1256,10 @@ impl Interpreter { std::ptr::from_ref(self) as usize, exit_code ); - // A node that returned `Yield::Failed` never reports to its parent, so - // the root script cannot complete after the promise was rejected. - debug_assert!(!self.flags.get().failed()); + debug_assert!( + !self.flags.get().failed(), + "a failed node never reports to its parent, so the root script cannot complete" + ); // Decrement pending activity unconditionally on exit. Paired with the // increment in `run_from_js`; harmless wrap on the mini path (flag is // only read from the JS GC `hasPendingActivity()` hook). @@ -1343,18 +1343,7 @@ impl Interpreter { Yield::done() } - /// The `Yield::Failed` arm of the trampoline: a state threw a JS - /// exception and cannot continue. Terminal under every driver (the JS - /// host call, a process exit, a pipe or task callback): the exception is - /// taken off the VM here and the `ShellPromise` is rejected with it, so no - /// driver returns to the event loop with the exception still pending and - /// the promise unsettled. - /// - /// The failed node never reports to its parent, so `finish` does not run - /// afterwards. The remaining nodes are left for the GC finalizer - /// (`CleanupState::NeedsFullCleanup`), which is why nothing is freed here: - /// a pipeline sibling that is still running reads its `Cmd` node, the AST - /// arena and the root `ShellExecEnv` when its exit or pipe close arrives. + /// `Yield::Failed` is terminal: take the pending JS exception and reject the `ShellPromise` with it. pub(crate) fn reject_with_pending_exception(&self) { use crate::jsc::JSValue; use crate::jsc::generated::JSShellInterpreter; @@ -1368,8 +1357,7 @@ impl Interpreter { std::ptr::from_ref(self) as usize ); - // The VM's termination (`worker.terminate()`) is not the script's - // error: it stays pending and keeps unwinding, and settles nothing. + // A pending termination (`worker.terminate()`) keeps unwinding and settles nothing. let error = if global_this.has_pending_termination_exception() { None } else { @@ -1385,10 +1373,8 @@ impl Interpreter { ) }; + // A second pipeline member failed: the promise is already rejected. if self.flags.get().failed() { - // Another pipeline member, started before the first one failed, - // failed too. The promise is already rejected; the error taken - // above is dropped. return; } self.update_flags(|f| f.set_failed(true)); @@ -1411,18 +1397,13 @@ impl Interpreter { JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); } - // Paired with the increment in `run_from_js`: lets the GC collect the - // wrapper and finalize the interpreter. A pipeline or `&` command runs - // its members concurrently, so one of them can still have a process, - // pipe or task in flight whose callback reaches back into this - // interpreter. The finalizer's in-flight teardown is only safe at VM - // shutdown, so in that case the interpreter stays alive until then. - let concurrent = self + // The nodes are freed by the finalizer, which must not run while a pipeline member's callbacks can still fire. + let members_in_flight = self .nodes .get() .iter() .any(|n| matches!(n.kind(), StateKind::Pipeline | StateKind::Async)); - if !concurrent { + if !members_in_flight { Self::decr_pending_activity_flag(&self.has_pending_activity); } } @@ -1536,11 +1517,8 @@ impl Interpreter { match this.cleanup_state.get() { CleanupState::NeedsFullCleanup => { - // The script did not finish: it is still in flight - // (`worker.terminate()` mid-command), or a state threw and the - // promise was rejected (`reject_with_pending_exception`, which - // keeps the wrapper alive instead when a pipeline member may - // still be running). `Node` has no `Drop` for its raw-pointer + // The script never reached `finish` (e.g. `worker.terminate()` + // mid-command) and `Node` has no `Drop` for its raw-pointer // resources: deinit every live `Cmd` (kills the child, frees // the `ShellSubprocess`, readers, redirection fd). Slots stay // occupied so the env walk below still sees pipeline-duped From 664b62f6a9978c65ea0603364cf235f36da7327c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 06:58:11 +0000 Subject: [PATCH 06/16] shell: keep waiting when Failed carries no exception, test GC and more drivers A Failed yield without a pending exception now behaves as it did before Failed became terminal (debug builds assert), so a producer that uses it as a wait state cannot cause a spurious rejection. Tests: force a GC after each rejection, reach the failing command from a thread-pool task driver, cover the failed write of a command-not-found message, and check that failed sequential scripts are collected. --- src/runtime/shell/interpreter.rs | 18 +++--- test/js/bun/shell/yield.test.ts | 99 +++++++++++++++++++++++++++----- 2 files changed, 92 insertions(+), 25 deletions(-) diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 91b6027fa8ab..258177baf65b 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -1361,16 +1361,14 @@ impl Interpreter { let error = if global_this.has_pending_termination_exception() { None } else { - Some( - global_this - .try_take_exception() - .and_then(JSValue::to_error) - .unwrap_or_else(|| { - debug_assert!(false, "Yield::Failed without a pending JS exception"); - global_this - .create_error_instance(format_args!("The shell interpreter failed")) - }), - ) + let error = global_this.try_take_exception().and_then(JSValue::to_error); + debug_assert!( + error.is_some(), + "Yield::Failed without a pending JS exception" + ); + // Nothing was thrown: keep waiting, as the trampoline did for `Failed` before it was terminal. + let Some(error) = error else { return }; + Some(error) }; // A second pipeline member failed: the promise is already rejected. diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 10bab9d37ed7..9e611c0a7011 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -102,29 +102,39 @@ describe("yield", async () => { }); }); - // A `${value}` redirect target the command cannot use (an in-memory Blob or - // Response as stdout) is a JS error thrown inside the state machine. When the + // A state can throw a JS error (here: a `${value}` redirect target the command + // cannot use, or a failed write of a "command not found" message). When the // command is not the first thing the script runs, the trampoline is driven - // by an event-loop callback (the previous command's exit), not by the - // `.run()` host call. The promise must still reject with the error, nothing - // may stay pending on the VM, and the process must exit on its own. + // by an event-loop callback (a process exit, a thread-pool task, a pipe + // write), not by the `.run()` host call. The promise must still reject with + // the error, nothing may stay pending on the VM, a GC afterwards must be + // safe, and the process must exit on its own. describe("a state that throws a JS error rejects the shell promise", () => { + function child(body: string) { + return [ + bunExe(), + "-e", + ` + import { $ } from "bun"; + import { heapStats } from "bun:jsc"; + const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); + const bun = process.execPath; + ${body} + `, + "--debug-crash-handler-use-trace-string", + ]; + } + async function expectRejection(shell: string, rejection: string) { await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - ` - import { $ } from "bun"; - const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); - const bun = process.execPath; + cmd: child(` const out = [await settle(${shell})]; + Bun.gc(true); // The VM is still usable: no exception was left pending on it. out.push(await settle($\`echo ok\`.quiet())); + Bun.gc(true); console.log(JSON.stringify(out)); - `, - "--debug-crash-handler-use-trace-string", - ], + `), env: bunEnv, stdout: "pipe", stderr: "pipe", @@ -150,6 +160,10 @@ describe("yield", async () => { await expectRejection("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()", builtin); }); + test.concurrent("builtin after a builtin that ran on the thread pool", async () => { + await expectRejection("$`ls .; echo hi > ${new Blob(['x'])}`.quiet().nothrow()", builtin); + }); + test.concurrent("in an && chain after another command", async () => { await expectRejection("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()", builtin); }); @@ -166,5 +180,60 @@ describe("yield", async () => { test.concurrent("first command, and the process still exits", async () => { await expectRejection("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()", builtin); }); + + // No misuse of the API here: the shell's own stderr is full, so the write + // of "bun: command not found" fails, and that failure is thrown. + test.concurrent.if(isLinux)("a failed write of the command-not-found message", async () => { + await using proc = Bun.spawn({ + cmd: child(` + const out = [await settle($\`\${bun} --version > /dev/null; command-that-does-not-exist-xyz\`)]; + Bun.gc(true); + out.push(await settle($\`echo ok\`.quiet())); + console.log(JSON.stringify(out)); + `), + env: bunEnv, + stdout: "pipe", + stderr: Bun.file("/dev/full"), + }); + + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + + expect({ result: stdout.trim(), exitCode }).toEqual({ + result: JSON.stringify(["rejected Error: No space left on device", "resolved 0"]), + exitCode: 0, + }); + }); + + // Without a pipeline nothing else is in flight when the command fails, so + // the interpreter must become collectable, not stay pinned until exit. + test.concurrent("failed scripts are collected", async () => { + await using proc = Bun.spawn({ + cmd: child(` + let rejected = 0; + for (let i = 0; i < 10; i++) { + await $\`ls .; echo hi > \${new Blob(["x"])}\`.quiet().then(() => {}, () => rejected++); + } + let live; + for (let i = 0; i < 10; i++) { + Bun.gc(true); + live = heapStats().objectTypeCounts.ShellInterpreter ?? 0; + if (live <= 3) break; + await new Promise(resolve => setImmediate(resolve)); + } + console.log(JSON.stringify({ rejected, collected: live <= 3 ? true : live })); + `), + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect({ result: stdout.trim(), stderr, exitCode }).toEqual({ + result: JSON.stringify({ rejected: 10, collected: true }), + stderr: "", + exitCode: 0, + }); + }); }); }); From 8dca1e017b4804abbe46f09e658f5e0a00512bde Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 07:41:41 +0000 Subject: [PATCH 07/16] shell: wind down a pipeline whose member throws a JS error A state that throws returned Yield::Failed with no node, so the failed member never reported to its parent. Its pipe ends stayed open, the members after it were never started, and the started members kept running. A producer that wrote more than the pipe buffer blocked forever and the process did not exit. Yield::Failed now carries the node. The trampoline calls Interpreter::fail, which rejects the promise, kills every subprocess, and reports the node to its parent as finished with exit code 1. The sequencing states stop on the failed flag, a pipeline frees the members it did not start, and finish settles nothing once every member has exited. --- src/runtime/shell/Builtin.rs | 14 ++-- src/runtime/shell/Yield.rs | 15 +--- src/runtime/shell/interpreter.rs | 72 +++++++++++------ src/runtime/shell/states/Binary.rs | 3 +- src/runtime/shell/states/Cmd.rs | 20 ++++- src/runtime/shell/states/CondExpr.rs | 5 +- src/runtime/shell/states/Expansion.rs | 13 ++- src/runtime/shell/states/Pipeline.rs | 110 ++++++++++++++++++-------- test/js/bun/shell/yield.test.ts | 41 ++++++++++ 9 files changed, 214 insertions(+), 79 deletions(-) diff --git a/src/runtime/shell/Builtin.rs b/src/runtime/shell/Builtin.rs index 3504a9a802ea..44220d935e84 100644 --- a/src/runtime/shell/Builtin.rs +++ b/src/runtime/shell/Builtin.rs @@ -689,7 +689,7 @@ impl Builtin { .to_vec() .into_boxed_slice(), )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; let jsval = interp.jsobjs[idx]; @@ -705,19 +705,19 @@ impl Builtin { let me = Self::of_mut(interp, cmd); if redirect.stdin() { let Some(buf) = root() else { - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; me.stdin = BuiltinInput::ArrayBuf { buf, i: 0 }; } if redirect.stdout() { let Some(buf) = root() else { - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; me.stdout = BuiltinIO::ArrayBuf { buf, i: 0 }; } if redirect.stderr() { let Some(buf) = root() else { - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; me.stderr = BuiltinIO::ArrayBuf { buf, i: 0 }; } @@ -733,7 +733,7 @@ impl Builtin { let _ = global.throw(format_args!( "Cannot redirect stdout/stderr to an immutable blob. Expected a file" )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); } let original_blob = body.use_(); if !redirect.stdin() && !redirect.stdout() && !redirect.stderr() { @@ -759,7 +759,7 @@ impl Builtin { let _ = global.throw(format_args!( "Cannot redirect stdout/stderr to an immutable blob. Expected a file" )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); } let theblob = Arc::new(BuiltinBlob { blob: blob_ref.dupe(), @@ -777,7 +777,7 @@ impl Builtin { "Unknown JS value used in shell: {}", jsval.fmt_string(global) )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); } } None if redirect.duplicate_out() => { diff --git a/src/runtime/shell/Yield.rs b/src/runtime/shell/Yield.rs index b7f465b6c17a..91907f13362d 100644 --- a/src/runtime/shell/Yield.rs +++ b/src/runtime/shell/Yield.rs @@ -37,8 +37,9 @@ pub enum Yield { /// Execution is waiting on async IO (epoll/kqueue/uv). The caller's task /// callback will resume by calling `.run()` again later. Suspended, - /// A JS exception is pending; terminal (`Interpreter::reject_with_pending_exception`). - Failed, + /// The node threw a JS exception (`Interpreter::fail`). The script is over: + /// the promise is rejected and the tree winds down through `child_done`. + Failed(NodeId), Done, } @@ -51,10 +52,6 @@ impl Yield { pub(crate) const fn done() -> Yield { Yield::Done } - #[inline] - pub(crate) const fn failed() -> Yield { - Yield::Failed - } } thread_local! { @@ -131,11 +128,7 @@ impl Yield { written, err, } => crate::shell::io_writer::on_io_writer_chunk(interp, child, written, err), - Yield::Failed => { - // The script is over: the rest of a pipeline's members are not started. - interp.reject_with_pending_exception(); - return; - } + Yield::Failed(id) => interp.fail(id), Yield::Suspended | Yield::Done => { if let Some(y) = Self::drain_pipelines(interp, &mut pipeline_stack) { y diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 258177baf65b..9712f37c6a3c 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -932,10 +932,11 @@ impl Interpreter { } } - /// For sequencing states' `child_done`: an interrupted pipeline member stops - /// where it is instead of running its next command. + /// For sequencing states' `child_done`: an interrupted pipeline member, or + /// any node once the script failed (`fail`), stops where it is instead of + /// running its next command. pub(crate) fn interrupted(&self, id: NodeId) -> bool { - self.node(id).base().is_some_and(|b| b.interrupted) + self.failed() || self.node(id).base().is_some_and(|b| b.interrupted) } /// Some ancestor is a member of a multi-command pipeline. @@ -1029,11 +1030,11 @@ impl Interpreter { Ok(id) => id, Err(e) => { self.throw(ShellErr::new_sys(&e)); - // Callers fall through as if the subshell exited 0. + // No child exists, so `parent` is the node that failed. // Return `None` so callers leave `currently_executing` // unset (no `NodeId::NONE` sentinel needed in // `deinit_node`/`free_node` for this path). - return (None, Yield::failed()); + return (None, Yield::Failed(parent)); } } } @@ -1256,10 +1257,6 @@ impl Interpreter { std::ptr::from_ref(self) as usize, exit_code ); - debug_assert!( - !self.flags.get().failed(), - "a failed node never reports to its parent, so the root script cannot complete" - ); // Decrement pending activity unconditionally on exit. Paired with the // increment in `run_from_js`; harmless wrap on the mini path (flag is // only read from the JS GC `hasPendingActivity()` hook). @@ -1277,7 +1274,12 @@ impl Interpreter { self.exit_code.set(Some(exit_code)); let this_jsvalue = self.this_jsvalue.get(); if this_jsvalue != JSValue::ZERO { - if let Some(resolve) = JSShellInterpreter::resolve_get_cached(this_jsvalue) { + if self.failed() { + // `fail` rejected the promise. Every member has exited, so the + // interpreter can let go of the event loop and be collected. + self.keep_alive.with_mut(|k| k.disable()); + self.deref_root_shell_and_io_if_needed(true); + } else if let Some(resolve) = JSShellInterpreter::resolve_get_cached(this_jsvalue) { let loop_ = self.event_loop; // `global_this` is `Some` on the `EventLoopHandle::Js` path // (set by `create_shell_interpreter`); see `global_this_ref`. @@ -1343,8 +1345,39 @@ impl Interpreter { Yield::done() } - /// `Yield::Failed` is terminal: take the pending JS exception and reject the `ShellPromise` with it. - pub(crate) fn reject_with_pending_exception(&self) { + /// The script failed with a JS error (`Yield::Failed`). The sequencing + /// states stop where they are (see `interrupted`), a pipeline frees the + /// members it did not start, and `finish` settles nothing. + #[inline] + pub(crate) fn failed(&self) -> bool { + self.flags.get().failed() + } + + /// `Yield::Failed(id)`: node `id` threw a JS exception and holds nothing + /// in flight. Reject the promise, stop every subprocess, and report `id` + /// to its parent as finished. The tree then winds down through the + /// normal `child_done` path, so every member that still runs reaches + /// `finish` before the interpreter lets go of the event loop. + pub(crate) fn fail(&self, id: NodeId) -> Yield { + self.reject_with_pending_exception(); + if self.failed() { + let node_count = self.nodes.get().len(); + for i in 0..node_count { + let cmd = NodeId(i as u32); + if matches!(self.node(cmd).kind(), StateKind::Cmd) { + Cmd::kill_subprocess(self, cmd); + } + } + } + let parent = self + .node(id) + .base() + .map_or(NodeId::INTERPRETER, |b| b.parent); + self.child_done(parent, id, 1) + } + + /// Take the pending JS exception and reject the `ShellPromise` with it. + fn reject_with_pending_exception(&self) { use crate::jsc::JSValue; use crate::jsc::generated::JSShellInterpreter; @@ -1366,17 +1399,16 @@ impl Interpreter { error.is_some(), "Yield::Failed without a pending JS exception" ); - // Nothing was thrown: keep waiting, as the trampoline did for `Failed` before it was terminal. + // Nothing was thrown: the node finishes with exit code 1 and the script goes on. let Some(error) = error else { return }; Some(error) }; // A second pipeline member failed: the promise is already rejected. - if self.flags.get().failed() { + if self.failed() { return; } self.update_flags(|f| f.set_failed(true)); - self.keep_alive.with_mut(|k| k.disable()); let this_jsvalue = self.this_jsvalue.get(); if let Some(error) = error @@ -1394,16 +1426,6 @@ impl Interpreter { JSShellInterpreter::resolve_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); } - - // The nodes are freed by the finalizer, which must not run while a pipeline member's callbacks can still fire. - let members_in_flight = self - .nodes - .get() - .iter() - .any(|n| matches!(n.kind(), StateKind::Pipeline | StateKind::Async)); - if !members_in_flight { - Self::decr_pending_activity_flag(&self.has_pending_activity); - } } /// JS-host entrypoint — sets up root IO diff --git a/src/runtime/shell/states/Binary.rs b/src/runtime/shell/states/Binary.rs index 7a536ca667cd..29ebc2d39624 100644 --- a/src/runtime/shell/states/Binary.rs +++ b/src/runtime/shell/states/Binary.rs @@ -77,10 +77,11 @@ impl Binary { exit_code: ExitCode, ) -> Yield { interp.deinit_node(child); + let stop = interp.interrupted(this); { let me = interp.as_binary_mut(this); me.currently_executing = None; - if me.left.is_none() && !me.base.interrupted { + if me.left.is_none() && !stop { me.left = Some(exit_code); } else { me.right = Some(exit_code); diff --git a/src/runtime/shell/states/Cmd.rs b/src/runtime/shell/states/Cmd.rs index 893313e8f953..1f85126fc3c4 100644 --- a/src/runtime/shell/states/Cmd.rs +++ b/src/runtime/shell/states/Cmd.rs @@ -300,7 +300,7 @@ impl Cmd { ) -> Yield { if let Some(err) = e { interp.throw(crate::shell::ShellErr::from_system(err)); - return Yield::failed(); + return Yield::Failed(this); } debug_assert!(matches!( interp.as_cmd(this).state, @@ -552,7 +552,7 @@ impl Cmd { Err(_) => { drop(spawn_args); drop(arena); - return Yield::failed(); + return Yield::Failed(this); } } @@ -879,6 +879,22 @@ impl Cmd { Self::deinit(interp, this); } + /// The script failed (`Interpreter::fail`): stop a subprocess that still + /// runs. Its exit then reaches `on_exit` and finishes the Cmd through + /// the normal path, so its pipe ends close once nothing can call back. + pub(crate) fn kill_subprocess(interp: &Interpreter, this: NodeId) { + let Exec::Subproc(sub) = &interp.as_cmd(this).exec else { + return; + }; + if sub.child.is_null() { + return; + } + // SAFETY: `child` was set by `spawn_async` from a + // `heap::alloc(ShellSubprocess)` and stays valid until `deinit` + // reclaims the box. Single-threaded. + let _ = unsafe { (*sub.child).try_kill(bun_core::SignalCode::SIGKILL as i32) }; + } + pub(crate) fn deinit(interp: &Interpreter, this: NodeId) { log!("Cmd {} deinit", this); let exec = { diff --git a/src/runtime/shell/states/CondExpr.rs b/src/runtime/shell/states/CondExpr.rs index a2cb9913f7a8..98b0862599c1 100644 --- a/src/runtime/shell/states/CondExpr.rs +++ b/src/runtime/shell/states/CondExpr.rs @@ -235,7 +235,10 @@ impl CondExpr { return Self::write_failing_error(interp, this, format_args!("{}\n", err)); } // Defensive fallback — finish via `writeFailingError` with exit 1. - debug_assert!(false, "Expansion child failed without an error"); + debug_assert!( + interp.failed(), + "Expansion child failed without an error" + ); let parent = interp.as_condexpr(this).base.parent; return interp.child_done(parent, this, 1); } diff --git a/src/runtime/shell/states/Expansion.rs b/src/runtime/shell/states/Expansion.rs index c3a181cd3302..9798fc045cd5 100644 --- a/src/runtime/shell/states/Expansion.rs +++ b/src/runtime/shell/states/Expansion.rs @@ -215,7 +215,7 @@ impl Expansion { Err(e) => { drop(io); interp.throw(ShellErr::new_sys(&e)); - return Yield::failed(); + return Yield::Failed(this); } }; let script = Script::init(interp, duped, script_ast, this, io); @@ -600,6 +600,17 @@ impl Expansion { // Child is a Script (command substitution). Its captured stdout lives // in the duped `ShellExecEnv` it owns; read it before deinit. debug_assert!(matches!(interp.node(child).kind(), StateKind::Script)); + if interp.failed() { + // The script failed: the rest of the word is not expanded. + { + let me = interp.as_expansion_mut(this); + me.state = ExpansionState::Done; + me.child_script = None; + } + interp.deinit_node(child); + let parent = interp.as_expansion(this).base.parent; + return interp.child_done(parent, this, 1); + } // SAFETY: single trampoline frame; the child script's env (and its // parent buffer in the `Borrowed` case) has no other live borrow. let stdout = unsafe { diff --git a/src/runtime/shell/states/Pipeline.rs b/src/runtime/shell/states/Pipeline.rs index 8e15a78e31dd..165f42f89b0e 100644 --- a/src/runtime/shell/states/Pipeline.rs +++ b/src/runtime/shell/states/Pipeline.rs @@ -96,6 +96,15 @@ impl Pipeline { /// Starts ONE child per call; `drain_pipelines` (Yield.rs) re-enters /// `Pipeline::next` for the next one once the current child suspends. fn next_starting(interp: &Interpreter, this: NodeId, idx: u32) -> Yield { + if interp.failed() { + // A member of a nested pipeline failed while this one was still + // starting its members (`drain_pipelines` resumes us). + if interp.as_pipeline(this).cmds.is_none() { + return Self::finish(interp, this, 1); + } + Self::release_unstarted(interp, this); + return Self::finish_if_all_exited(interp, this); + } if interp.as_pipeline(this).cmds.is_none() { debug_assert_eq!(idx, 0); if let Some(y) = Self::setup_commands(interp, this) { @@ -331,44 +340,83 @@ impl Pipeline { exit_code ); // Find the child in `cmds` and replace with its result. - let (all_done, n) = { - let me = interp.as_pipeline_mut(this); - me.exited_count += 1; - let n = me.cmds.as_ref().map(|c| c.len() as u32).unwrap_or(0); - if let Some(cmds) = &mut me.cmds { - for slot in cmds.iter_mut() { - if matches!(slot, CmdOrResult::Cmd(id) if *id == child) { - *slot = CmdOrResult::Result(exit_code); - break; - } - } - } - (me.exited_count >= n && n > 0, n) - }; + Self::record_result(interp, this, child, exit_code); // We duped a ShellExecEnv per child in `next_starting`. Cmd/If/CondExpr // do NOT free `base.shell` in their own `deinit`, so free it here. // Subshell frees its own; Assigns is skipped. Self::deinit_child_duped_env(interp, child); interp.deinit_node(child); - if all_done { - // Exit code = last command's exit code (bash semantics). - // For a single-runnable pipeline `last_exit_code` stays 0: only - // inspect `cmds[len-1]` when `len >= 2`. - let exit = { - let me = interp.as_pipeline(this); - match me.cmds.as_ref() { - Some(c) if c.len() >= 2 => match c.last() { - Some(CmdOrResult::Result(e)) => *e, - _ => 0, - }, - _ => 0, + if interp.failed() { + Self::release_unstarted(interp, this); + } + Self::finish_if_all_exited(interp, this) + } + + /// `Done` once every member reported, else keep waiting for the rest. + fn finish_if_all_exited(interp: &Interpreter, this: NodeId) -> Yield { + let me = interp.as_pipeline(this); + let Some(cmds) = me.cmds.as_deref() else { + return Yield::suspended(); + }; + if cmds.is_empty() || (me.exited_count as usize) < cmds.len() { + return Yield::suspended(); + } + // Exit code = last command's exit code (bash semantics). + // For a single-runnable pipeline `last_exit_code` stays 0: only + // inspect `cmds[len-1]` when `len >= 2`. + let exit = if cmds.len() >= 2 { + match cmds.last() { + Some(CmdOrResult::Result(e)) => *e, + _ => 0, + } + } else { + 0 + }; + interp.as_pipeline_mut(this).state = PipelineState::Done { exit_code: exit }; + Yield::Next(this) + } + + fn record_result(interp: &Interpreter, this: NodeId, child: NodeId, exit_code: ExitCode) { + let me = interp.as_pipeline_mut(this); + me.exited_count += 1; + if let Some(cmds) = &mut me.cmds { + for slot in cmds.iter_mut() { + if matches!(slot, CmdOrResult::Cmd(id) if *id == child) { + *slot = CmdOrResult::Result(exit_code); + break; } - }; - interp.as_pipeline_mut(this).state = PipelineState::Done { exit_code: exit }; - return Yield::Next(this); + } + } + } + + /// The script failed (`Interpreter::fail`): the members that did not + /// start never will. Free them now so the pipe ends they hold close and + /// the members that run see EOF or EPIPE instead of blocking forever. + fn release_unstarted(interp: &Interpreter, this: NodeId) { + let PipelineState::StartingCmds { idx } = interp.as_pipeline(this).state else { + return; + }; + let unstarted: Vec = interp + .as_pipeline(this) + .cmds + .as_deref() + .map(|cmds| { + cmds.iter() + .skip(idx as usize) + .filter_map(|slot| match slot { + CmdOrResult::Cmd(id) => Some(*id), + CmdOrResult::Result(_) => None, + }) + .collect() + }) + .unwrap_or_default(); + for child in unstarted { + log!("Pipeline {} release unstarted child {}", this, child); + Self::record_result(interp, this, child, 1); + Self::deinit_child_duped_env(interp, child); + interp.deinit_node(child); } - let _ = n; - Yield::suspended() + interp.as_pipeline_mut(this).state = PipelineState::Pending; } /// Free the per-child env duped in `next_starting` for child kinds that diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 9e611c0a7011..9ed50e160c71 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -235,5 +235,46 @@ describe("yield", async () => { exitCode: 0, }); }); + + // When the member that throws is part of a pipeline, the members that + // already run must stop and the members after it must never start. Until + // that happened, a producer that wrote more than the pipe buffer blocked + // on a pipe end nobody closed, and the process never exited. + describe("the other members of the pipeline stop", () => { + // 1 MiB: more than the pipe buffer, so the write blocks until the read end closes. + const producer = "${bun} -e ${'process.stdout.write(Buffer.alloc(1 << 20, \"a\"))'}"; + const sleeper = "${bun} -e ${'setTimeout(() => {}, 100_000)'}"; + const bad = "${bun} --version > ${new Response('r')}"; + + test.concurrent("a producer that writes more than the pipe buffer", async () => { + await expectRejection(`$\`${producer} | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("a member that never touches the pipe is killed", async () => { + await expectRejection(`$\`${sleeper} | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("the members after the failed one never start", async () => { + await expectRejection(`$\`${producer} | ${bad} | ${sleeper} | \${bun} --version\`.quiet().nothrow()`, external); + }); + + test.concurrent("the failed member is the first one", async () => { + await expectRejection(`$\`${bad} | ${sleeper}\`.quiet().nothrow()`, external); + }); + + test.concurrent("a member inside a subshell is killed", async () => { + await expectRejection(`$\`(${sleeper}; echo no) | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("a command substitution in another member is stopped", async () => { + await expectRejection(`$\`echo $(${sleeper}) | ${bad}\`.quiet().nothrow()`, external); + }); + + // The thread-pool task of `ls` completes after the failure and writes + // to a pipe whose read end is closed by then. + test.concurrent("a builtin producer on the thread pool", async () => { + await expectRejection(`$\`ls ${"${" + JSON.stringify(import.meta.dir) + "}"} | ${bad}\`.quiet().nothrow()`, external); + }); + }); }); }); From 2155923c6490d4c1ad2ac63b35829d6a162cb18a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 08:01:42 +0000 Subject: [PATCH 08/16] test: collect a failed pipeline, format --- src/runtime/shell/states/CondExpr.rs | 5 +---- test/js/bun/shell/yield.test.ts | 12 ++++++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/runtime/shell/states/CondExpr.rs b/src/runtime/shell/states/CondExpr.rs index 98b0862599c1..67d98f160790 100644 --- a/src/runtime/shell/states/CondExpr.rs +++ b/src/runtime/shell/states/CondExpr.rs @@ -235,10 +235,7 @@ impl CondExpr { return Self::write_failing_error(interp, this, format_args!("{}\n", err)); } // Defensive fallback — finish via `writeFailingError` with exit 1. - debug_assert!( - interp.failed(), - "Expansion child failed without an error" - ); + debug_assert!(interp.failed(), "Expansion child failed without an error"); let parent = interp.as_condexpr(this).base.parent; return interp.child_done(parent, this, 1); } diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 9ed50e160c71..b903aeb4629e 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -204,14 +204,15 @@ describe("yield", async () => { }); }); - // Without a pipeline nothing else is in flight when the command fails, so - // the interpreter must become collectable, not stay pinned until exit. + // Once every member of a failed script has exited, the interpreter must + // become collectable, not stay pinned until the process exits. test.concurrent("failed scripts are collected", async () => { await using proc = Bun.spawn({ cmd: child(` let rejected = 0; for (let i = 0; i < 10; i++) { await $\`ls .; echo hi > \${new Blob(["x"])}\`.quiet().then(() => {}, () => rejected++); + await $\`\${bun} --version | echo hi > \${new Blob(["x"])}\`.quiet().then(() => {}, () => rejected++); } let live; for (let i = 0; i < 10; i++) { @@ -230,7 +231,7 @@ describe("yield", async () => { const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect({ result: stdout.trim(), stderr, exitCode }).toEqual({ - result: JSON.stringify({ rejected: 10, collected: true }), + result: JSON.stringify({ rejected: 20, collected: true }), stderr: "", exitCode: 0, }); @@ -273,7 +274,10 @@ describe("yield", async () => { // The thread-pool task of `ls` completes after the failure and writes // to a pipe whose read end is closed by then. test.concurrent("a builtin producer on the thread pool", async () => { - await expectRejection(`$\`ls ${"${" + JSON.stringify(import.meta.dir) + "}"} | ${bad}\`.quiet().nothrow()`, external); + await expectRejection( + `$\`ls ${"${" + JSON.stringify(import.meta.dir) + "}"} | ${bad}\`.quiet().nothrow()`, + external, + ); }); }); }); From 0b3d66f2eaf9e3ecb2ce62ca0b47143c3e291d33 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:47:46 +0000 Subject: [PATCH 09/16] shell: a command whose expansion completes after the script failed does not spawn --- src/runtime/shell/states/Cmd.rs | 13 +++++++++++++ test/js/bun/shell/yield.test.ts | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/src/runtime/shell/states/Cmd.rs b/src/runtime/shell/states/Cmd.rs index 1f85126fc3c4..4608a73d1d07 100644 --- a/src/runtime/shell/states/Cmd.rs +++ b/src/runtime/shell/states/Cmd.rs @@ -235,6 +235,19 @@ impl Cmd { this, <&'static str>::from(&interp.as_cmd(this).state) ); + if interp.failed() + && !matches!( + interp.as_cmd(this).state, + CmdState::WaitingWriteErr | CmdState::Done + ) + { + // The script failed while an expansion of this command was in + // flight: do not expand the rest or spawn the command. + let me = interp.as_cmd_mut(this); + me.exit_code = Some(1); + me.state = CmdState::Done; + continue; + } match interp.as_cmd(this).state { CmdState::Idle => { if !n.assigns.is_empty() { diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index b903aeb4629e..859aaf6c3138 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -263,6 +263,12 @@ describe("yield", async () => { await expectRejection(`$\`${bad} | ${sleeper}\`.quiet().nothrow()`, external); }); + // The glob runs on the thread pool. When it completes, the member must + // not spawn its command. + test.concurrent("a member whose glob expansion completes after the failure", async () => { + await expectRejection(`$\`${sleeper} * | ${bad}\`.quiet().nothrow()`, external); + }); + test.concurrent("a member inside a subshell is killed", async () => { await expectRejection(`$\`(${sleeper}; echo no) | ${bad}\`.quiet().nothrow()`, external); }); From 812cc6e86272f0df1f9dfaf1cf9d3bf9118ebd5a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:49:30 +0000 Subject: [PATCH 10/16] shell: shorter comments, test that nothing more of a failed script runs --- src/runtime/shell/Yield.rs | 3 +-- src/runtime/shell/interpreter.rs | 20 +++++++------------- src/runtime/shell/states/Cmd.rs | 7 ++----- src/runtime/shell/states/Pipeline.rs | 7 ++----- test/js/bun/shell/yield.test.ts | 26 +++++++++++++++++++++++++- 5 files changed, 37 insertions(+), 26 deletions(-) diff --git a/src/runtime/shell/Yield.rs b/src/runtime/shell/Yield.rs index 91907f13362d..50b2215143f0 100644 --- a/src/runtime/shell/Yield.rs +++ b/src/runtime/shell/Yield.rs @@ -37,8 +37,7 @@ pub enum Yield { /// Execution is waiting on async IO (epoll/kqueue/uv). The caller's task /// callback will resume by calling `.run()` again later. Suspended, - /// The node threw a JS exception (`Interpreter::fail`). The script is over: - /// the promise is rejected and the tree winds down through `child_done`. + /// The node threw a JS exception; `Interpreter::fail` winds the script down. Failed(NodeId), Done, } diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 9712f37c6a3c..5fc39e78b761 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -932,9 +932,8 @@ impl Interpreter { } } - /// For sequencing states' `child_done`: an interrupted pipeline member, or - /// any node once the script failed (`fail`), stops where it is instead of - /// running its next command. + /// A sequencing state stops instead of running its next command: Ctrl+C + /// cut the member short, or the script failed (`fail`). pub(crate) fn interrupted(&self, id: NodeId) -> bool { self.failed() || self.node(id).base().is_some_and(|b| b.interrupted) } @@ -1275,8 +1274,7 @@ impl Interpreter { let this_jsvalue = self.this_jsvalue.get(); if this_jsvalue != JSValue::ZERO { if self.failed() { - // `fail` rejected the promise. Every member has exited, so the - // interpreter can let go of the event loop and be collected. + // `fail` already rejected the promise. self.keep_alive.with_mut(|k| k.disable()); self.deref_root_shell_and_io_if_needed(true); } else if let Some(resolve) = JSShellInterpreter::resolve_get_cached(this_jsvalue) { @@ -1345,19 +1343,15 @@ impl Interpreter { Yield::done() } - /// The script failed with a JS error (`Yield::Failed`). The sequencing - /// states stop where they are (see `interrupted`), a pipeline frees the - /// members it did not start, and `finish` settles nothing. + /// A node threw a JS error (`fail`): the script winds down and `finish` settles nothing. #[inline] pub(crate) fn failed(&self) -> bool { self.flags.get().failed() } - /// `Yield::Failed(id)`: node `id` threw a JS exception and holds nothing - /// in flight. Reject the promise, stop every subprocess, and report `id` - /// to its parent as finished. The tree then winds down through the - /// normal `child_done` path, so every member that still runs reaches - /// `finish` before the interpreter lets go of the event loop. + /// Node `id` threw a JS exception and holds nothing in flight: reject the + /// promise, kill the subprocesses, and report `id` as finished so the tree + /// winds down through `child_done` into `finish`. pub(crate) fn fail(&self, id: NodeId) -> Yield { self.reject_with_pending_exception(); if self.failed() { diff --git a/src/runtime/shell/states/Cmd.rs b/src/runtime/shell/states/Cmd.rs index 4608a73d1d07..374c4731b8d7 100644 --- a/src/runtime/shell/states/Cmd.rs +++ b/src/runtime/shell/states/Cmd.rs @@ -241,8 +241,7 @@ impl Cmd { CmdState::WaitingWriteErr | CmdState::Done ) { - // The script failed while an expansion of this command was in - // flight: do not expand the rest or spawn the command. + // The script failed: expand nothing more and do not spawn. let me = interp.as_cmd_mut(this); me.exit_code = Some(1); me.state = CmdState::Done; @@ -892,9 +891,7 @@ impl Cmd { Self::deinit(interp, this); } - /// The script failed (`Interpreter::fail`): stop a subprocess that still - /// runs. Its exit then reaches `on_exit` and finishes the Cmd through - /// the normal path, so its pipe ends close once nothing can call back. + /// The script failed: stop the subprocess. Its exit finishes the Cmd through `on_exit`. pub(crate) fn kill_subprocess(interp: &Interpreter, this: NodeId) { let Exec::Subproc(sub) = &interp.as_cmd(this).exec else { return; diff --git a/src/runtime/shell/states/Pipeline.rs b/src/runtime/shell/states/Pipeline.rs index 165f42f89b0e..143286399a2e 100644 --- a/src/runtime/shell/states/Pipeline.rs +++ b/src/runtime/shell/states/Pipeline.rs @@ -97,8 +97,7 @@ impl Pipeline { /// `Pipeline::next` for the next one once the current child suspends. fn next_starting(interp: &Interpreter, this: NodeId, idx: u32) -> Yield { if interp.failed() { - // A member of a nested pipeline failed while this one was still - // starting its members (`drain_pipelines` resumes us). + // A nested pipeline's member failed while this one was still starting. if interp.as_pipeline(this).cmds.is_none() { return Self::finish(interp, this, 1); } @@ -389,9 +388,7 @@ impl Pipeline { } } - /// The script failed (`Interpreter::fail`): the members that did not - /// start never will. Free them now so the pipe ends they hold close and - /// the members that run see EOF or EPIPE instead of blocking forever. + /// The script failed: free the members that never started so their pipe ends close. fn release_unstarted(interp: &Interpreter, this: NodeId) { let PipelineState::StartingCmds { idx } = interp.as_pipeline(this).state else { return; diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 859aaf6c3138..db5988edc008 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isLinux } from "harness"; +import { bunEnv, bunExe, isLinux, tempDir } from "harness"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -117,6 +117,7 @@ describe("yield", async () => { ` import { $ } from "bun"; import { heapStats } from "bun:jsc"; + import { readdirSync } from "node:fs"; const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); const bun = process.execPath; ${body} @@ -285,6 +286,29 @@ describe("yield", async () => { external, ); }); + + test.concurrent("nothing more of the script runs", async () => { + using dir = tempDir("shell-failed-pipeline", {}); + await using proc = Bun.spawn({ + cmd: child(` + const out = [await settle($\`(${sleeper}; touch a) | ${bad}; touch b\`.quiet().nothrow())]; + out.push(JSON.stringify(readdirSync("."))); + console.log(JSON.stringify(out)); + `), + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect({ result: stdout.trim(), stderr, exitCode }).toEqual({ + result: JSON.stringify([external, "[]"]), + stderr: "", + exitCode: 0, + }); + }); }); }); }); From 5c065dc42ad790e216b2fbd9fa30a286f479d11a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:50:00 +0000 Subject: [PATCH 11/16] shell: one-line doc for interrupted --- src/runtime/shell/interpreter.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 5fc39e78b761..cfa8235e02bf 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -932,8 +932,7 @@ impl Interpreter { } } - /// A sequencing state stops instead of running its next command: Ctrl+C - /// cut the member short, or the script failed (`fail`). + /// A sequencing state stops early: Ctrl+C cut the member short, or the script failed. pub(crate) fn interrupted(&self, id: NodeId) -> bool { self.failed() || self.node(id).base().is_some_and(|b| b.interrupted) } From 3ac7879c90e5bdb47e4374bd81d50df4546766e0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 07:41:26 +0000 Subject: [PATCH 12/16] shell: reject after the kills and the wind-down, test the killed member is reaped The rejection runs user JS and drains microtasks. It now comes last in Interpreter::fail, so a catch handler sees the kills sent and the tree settled. New tests: the killed member is gone after the rejection, two members fail, a non-quiet pipeline, and worker.terminate() while a failed pipeline winds down. --- src/runtime/shell/interpreter.rs | 61 +++++++++--------- .../shell/shell-worker-terminate-leak.test.ts | 18 ++++++ test/js/bun/shell/yield.test.ts | 62 +++++++++++++++++++ 3 files changed, 113 insertions(+), 28 deletions(-) diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index cfa8235e02bf..d1dcd65f3148 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -1348,11 +1348,12 @@ impl Interpreter { self.flags.get().failed() } - /// Node `id` threw a JS exception and holds nothing in flight: reject the - /// promise, kill the subprocesses, and report `id` as finished so the tree - /// winds down through `child_done` into `finish`. + /// Node `id` threw a JS exception and holds nothing in flight: kill the + /// subprocesses, report `id` as finished so the tree winds down through + /// `child_done` into `finish`, then reject the promise. The rejection runs + /// JS, so it comes last: user code sees the kills sent and the tree settled. pub(crate) fn fail(&self, id: NodeId) -> Yield { - self.reject_with_pending_exception(); + let rejection = self.take_failure(); if self.failed() { let node_count = self.nodes.get().len(); for i in 0..node_count { @@ -1366,20 +1367,32 @@ impl Interpreter { .node(id) .base() .map_or(NodeId::INTERPRETER, |b| b.parent); - self.child_done(parent, id, 1) + let y = self.child_done(parent, id, 1); + if let Some((reject, error)) = rejection { + let global_this = self + .global_this_ref() + .expect("take_failure returned a rejection on the Js path"); + let _entered = self.event_loop.entered(); + global_this.bun_vm().event_loop_mut().run_callback( + reject, + global_this, + crate::jsc::JSValue::UNDEFINED, + &[error], + ); + } + y } - /// Take the pending JS exception and reject the `ShellPromise` with it. - fn reject_with_pending_exception(&self) { + /// Take the pending JS exception and mark the script failed. Returns the + /// cached `reject` and the error when the promise still has to settle. + fn take_failure(&self) -> Option<(crate::jsc::JSValue, crate::jsc::JSValue)> { use crate::jsc::JSValue; use crate::jsc::generated::JSShellInterpreter; // Mini event loop: `Interpreter::throw` prints and exits instead. - let Some(global_this) = self.global_this_ref() else { - return; - }; + let global_this = self.global_this_ref()?; log!( - "Interpreter(0x{:x}) reject with pending exception", + "Interpreter(0x{:x}) take failure", std::ptr::from_ref(self) as usize ); @@ -1393,32 +1406,24 @@ impl Interpreter { "Yield::Failed without a pending JS exception" ); // Nothing was thrown: the node finishes with exit code 1 and the script goes on. - let Some(error) = error else { return }; - Some(error) + Some(error?) }; // A second pipeline member failed: the promise is already rejected. if self.failed() { - return; + return None; } self.update_flags(|f| f.set_failed(true)); + let error = error?; let this_jsvalue = self.this_jsvalue.get(); - if let Some(error) = error - && this_jsvalue != JSValue::ZERO - { - if let Some(reject) = JSShellInterpreter::reject_get_cached(this_jsvalue) { - let _entered = self.event_loop.entered(); - global_this.bun_vm().event_loop_mut().run_callback( - reject, - global_this, - JSValue::UNDEFINED, - &[error], - ); - } - JSShellInterpreter::resolve_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); - JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + if this_jsvalue == JSValue::ZERO { + return None; } + let reject = JSShellInterpreter::reject_get_cached(this_jsvalue); + JSShellInterpreter::resolve_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + Some((reject?, error)) } /// JS-host entrypoint — sets up root IO diff --git a/test/js/bun/shell/shell-worker-terminate-leak.test.ts b/test/js/bun/shell/shell-worker-terminate-leak.test.ts index 3e7f274078bc..834015b1cf95 100644 --- a/test/js/bun/shell/shell-worker-terminate-leak.test.ts +++ b/test/js/bun/shell/shell-worker-terminate-leak.test.ts @@ -165,6 +165,24 @@ test.skipIf(!isASAN || isWindows)( LEAK_TEST_TIMEOUT, ); +test.skipIf(!isASAN || isWindows)( + "worker.terminate() while a failed Bun.$ pipeline winds down does not leak or crash", + async () => { + // The second member throws a JS error as soon as it starts. The shell + // kills the first member and rejects the promise before the child's exit + // reaches the event loop, so the terminate races the wind-down: the + // finalizer either finds the pipeline still in flight or already finished. + await runTerminateScenario(` + const running = Bun.$\`sh -c "exec sleep 100" | sh -c "true" > \${new Response("r")}\`.nothrow(); + running.then( + () => postMessage("resolved"), + () => postMessage("ok"), + ); + `); + }, + LEAK_TEST_TIMEOUT, +); + test.skipIf(!isLinux)( "worker.terminate() kills a live Bun.$ subprocess", async () => { diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index db5988edc008..1a0e214ad495 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from "bun:test"; +import { $ } from "bun"; import { bunEnv, bunExe, isLinux, tempDir } from "harness"; +import { join } from "node:path"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -309,6 +311,66 @@ describe("yield", async () => { exitCode: 0, }); }); + + // A ShellPromise starts when `then` is called. `expect().rejects` does + // not call it, so await the promise here. + async function rejectionOf(promise: Promise): Promise { + try { + await promise; + } catch (e) { + return e; + } + throw new Error("the shell promise resolved"); + } + + // The member that does not touch the pipe writes its pid first, and the + // failing member waits for that file in a command substitution before it + // throws. So the sleeper is alive when the script fails, and the test + // can check that it is killed and reaped afterwards. + test.concurrent("the killed member is gone after the rejection", async () => { + using dir = tempDir("shell-failed-pipeline-pid", {}); + const bun = process.execPath; + const writePid = 'require("fs").writeFileSync("pid", String(process.pid)); setTimeout(() => {}, 100_000)'; + const waitForPid = + 'while (!require("fs").existsSync("pid")) Bun.sleepSync(5); process.stdout.write("--version")'; + expect( + await rejectionOf( + $`${bun} -e ${writePid} | ${bun} $(${bun} -e ${waitForPid}) > ${new Response("r")}` + .cwd(String(dir)) + .quiet(), + ), + ).toMatchObject({ message: "Blobs are immutable, and cannot be used for stdout/stderr" }); + const pid = Number(await Bun.file(join(String(dir), "pid")).text()); + expect(pid).toBeGreaterThan(0); + // The kill is sent before the promise rejects. The shell reaps the + // child when its exit reaches the event loop, so poll for that. + const alive = () => { + try { + process.kill(pid, 0); + return true; + } catch (e) { + expect(e).toMatchObject({ code: "ESRCH" }); + return false; + } + }; + for (let i = 0; i < 1000 && alive(); i++) await Bun.sleep(10); + expect(alive()).toBe(false); + }); + + test.concurrent("two members fail: the first error rejects, the shell stays usable", async () => { + expect(await rejectionOf($`echo a > ${new Blob(["x"])} | echo b > ${new Blob(["x"])}`.quiet())).toMatchObject({ + message: "Cannot redirect stdout/stderr to an immutable blob. Expected a file", + }); + expect((await $`echo ok`.quiet().text()).trim()).toBe("ok"); + }); + + test.concurrent("not quiet: the promise rejects and the shell stays usable", async () => { + const bun = process.execPath; + expect( + await rejectionOf($`${bun} -e ${"setTimeout(() => {}, 100_000)"} | ${bun} --version > ${new Response("r")}`), + ).toMatchObject({ message: "Blobs are immutable, and cannot be used for stdout/stderr" }); + expect((await $`echo ok`.text()).trim()).toBe("ok"); + }); }); }); }); From a20fee4ee59fc331fac5bd2b717be3dae873343d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 07:41:59 +0000 Subject: [PATCH 13/16] shell: one-line docs for fail and take_failure --- src/runtime/shell/interpreter.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index d1dcd65f3148..d6a2a02bc0ab 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -1348,10 +1348,7 @@ impl Interpreter { self.flags.get().failed() } - /// Node `id` threw a JS exception and holds nothing in flight: kill the - /// subprocesses, report `id` as finished so the tree winds down through - /// `child_done` into `finish`, then reject the promise. The rejection runs - /// JS, so it comes last: user code sees the kills sent and the tree settled. + /// Node `id` threw and holds nothing in flight: kill the subprocesses, wind the tree down, then reject (the rejection runs JS, so it comes last). pub(crate) fn fail(&self, id: NodeId) -> Yield { let rejection = self.take_failure(); if self.failed() { @@ -1383,8 +1380,7 @@ impl Interpreter { y } - /// Take the pending JS exception and mark the script failed. Returns the - /// cached `reject` and the error when the promise still has to settle. + /// Take the pending exception and set `failed`; `Some` when the promise still has to be rejected. fn take_failure(&self) -> Option<(crate::jsc::JSValue, crate::jsc::JSValue)> { use crate::jsc::JSValue; use crate::jsc::generated::JSShellInterpreter; From 14d7fb5e0a7100bda89b4136cdbbd9aabc3a2110 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 07:44:36 +0000 Subject: [PATCH 14/16] [autofix.ci] apply automated fixes --- test/js/bun/shell/yield.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 1a0e214ad495..5ec31b1ededc 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, test } from "bun:test"; import { $ } from "bun"; +import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isLinux, tempDir } from "harness"; import { join } from "node:path"; import { createTestBuilder } from "./test_builder"; From 7719a8fed537b4d769d8e73ed26b56fec88f96b5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 08:11:03 +0000 Subject: [PATCH 15/16] shell: point the failed flag doc at take_failure --- src/runtime/shell/interpreter.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index d6a2a02bc0ab..a93ab5bd1b77 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -332,7 +332,7 @@ impl InterpreterFlags { pub(crate) fn set_quiet(&mut self, v: bool) { if v { self.0 |= 0b10 } else { self.0 &= !0b10 } } - /// Set by [`Interpreter::reject_with_pending_exception`]. + /// Set by [`Interpreter::take_failure`]. pub(crate) const fn failed(self) -> bool { self.0 & 0b100 != 0 } From 97ddd85d0a0972371148aab3c0d5a6bdfc87880d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 08:50:06 +0000 Subject: [PATCH 16/16] ci: retrigger