From 36145c7d12c6e537ab736deab0a0a58aabb6acd1 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 12 Aug 2026 02:42:47 +0000 Subject: [PATCH 01/12] shell: fail every queued chunk when an IOWriter dies, not one per child When a write fails (EPIPE because the reader of stdout went away, for example), IOWriter::on_error and the EndOfFile arm of on_write_pollable delivered one error completion per distinct child and dropped the rest of that child's queued chunks. rm and the OutputTask builtins (ls, mkdir, touch, cp) queue one chunk per argument under the same ChildPtr and finish once every chunk has completed, so with two or more chunks queued they waited forever and the awaited `$` never settled. fail_pending_writers now hands every still-queued chunk its own error completion, walking the queue in place so that a child which stops at its first error can cancel_chunks() the rest from inside the callback. The two children that do stop early, cat and the subprocess CapturedWriter, now do that; the CapturedWriter in particular can be freed by its first error completion, so a second one would be a use-after-free. The EndOfFile path shares the same function instead of its own per-child copy, and on_sync_error withholds the enqueuing child's own chunk as before. --- src/runtime/shell/IOWriter.rs | 164 ++++++++++++++----------------- src/runtime/shell/builtin/cat.rs | 17 +++- src/runtime/shell/subproc.rs | 20 +++- test/js/bun/shell/epipe.test.ts | 93 +++++++++++++++++- 4 files changed, 196 insertions(+), 98 deletions(-) diff --git a/src/runtime/shell/IOWriter.rs b/src/runtime/shell/IOWriter.rs index ef004501d537..ebc4fed1531e 100644 --- a/src/runtime/shell/IOWriter.rs +++ b/src/runtime/shell/IOWriter.rs @@ -514,7 +514,10 @@ impl IOWriter { // ── queue management ──────────────────────────────────────────────── - /// Cancel the chunks enqueued by the given child by marking them as dead. + /// Cancel the chunks enqueued by the given child by marking them as dead: + /// they are skipped without a callback, both when the queue drains and + /// when it fails (`fail_pending_writers`), so a child that is about to + /// finish with chunks still queued calls this first. pub(crate) fn cancel_chunks(&self, ptr: ChildPtr) { let s = self.state(); if s.writers.is_empty() { @@ -762,11 +765,9 @@ impl IOWriter { if !not_fully_written { return; } - // Other end of the socket/pipe closed and we got EPIPE - // (e.g. `ls | echo`). Quick hack: have all writers see an - // error. - s.flags.broken_pipe = true; - self.broken_pipe_for_writers(); + // Other end of the socket/pipe closed (e.g. `ls | echo`): + // everything still queued fails with EPIPE. + self.fail_pending_writers(&sys::Error::from_code(E::EPIPE, sys::Tag::write), None); return; } if s.writers[idx].written >= s.writers[idx].len { @@ -794,86 +795,89 @@ impl IOWriter { } } - fn broken_pipe_for_writers(&self) { - let s = self.state(); - debug_assert!(s.flags.broken_pipe); - // NOTE: reshaped for borrowck — collect targets first so we don't - // hold `&mut s.writers` across `cancel_chunks`/`run_yield`. - let mut targets: Vec = Vec::new(); - for w in &s.writers[s.writer_idx..] { - if w.is_dead() { - continue; - } - if !targets.contains(&w.ptr) { - targets.push(w.ptr); - } - } - for ptr in targets { - let err = sys::Error::from_code(E::EPIPE, sys::Tag::write).to_system_error(); - self.run_yield(Yield::OnIoWriterChunk { - child: ptr, - written: 0, - err: Some(err), - }); - self.cancel_chunks(ptr); - } - let s = self.state(); - s.total_bytes_written = 0; - s.writers.clear(); - s.buf.clear(); - s.writer_idx = 0; - } - - /// Shared failure bookkeeping: mark broken pipes, reset the queue, and - /// return the still-pending children that have to be told their chunk - /// failed. The queue is reset *before* any of them runs so that a child - /// re-enqueueing from its callback is not wiped afterwards. - fn fail_pending_writers(&self, err: &sys::Error) -> Vec { + /// Shared failure path: record the error, then fail every chunk that is + /// still queued, oldest first, with its own error completion. + /// + /// One completion per *chunk*, not per child. `rm` and the `OutputTask` + /// builtins (`ls`, `mkdir`, `touch`, `cp`) queue one chunk per task under + /// the same `ChildPtr` and finish once they have counted a completion for + /// each, so a single per-child error left them waiting for the rest + /// forever. A child that stops at its first error while more of its + /// chunks are queued (`cat`, the subprocess `CapturedWriter`) calls + /// `cancel_chunks` from that callback; that is why the queue is walked in + /// place, each entry re-checked right before its callback, and only + /// cleared after the last completion. Nothing is appended meanwhile: + /// `err`/`broken_pipe` are set before the first callback, so a child that + /// enqueues from its callback (the next statement, the RHS of `&&`, ...) + /// is answered by `handle_dead_writer` instead of being queued onto a + /// writer whose handle the error path is tearing down. + /// + /// `withhold` is the child whose `enqueue` is still on the stack (see + /// `on_sync_error`): the first of its chunks is not dispatched here but + /// returned, provided it is still live once everything else has run. + fn fail_pending_writers(&self, err: &sys::Error, withhold: Option) -> Option { + // A completion may drop the last external `Arc` to this writer. + let _keepalive = self.keepalive(); self.set_writing(false); let s = self.state(); if err.get_errno() == E::EPIPE { s.flags.broken_pipe = true; } - // Mark the writer dead before any completion below runs: a child that - // enqueues from its callback (the next statement, the RHS of `&&`, ...) - // must be rejected by `handle_dead_writer`, not queued onto a writer - // whose handle the error path is tearing down. s.err = Some(err.clone()); + crate::shell_log!( + "IOWriter(fd={}) failing {} queued chunk(s): {:?}", + s.fd, + s.writers.len().saturating_sub(s.writer_idx), + err.get_errno() + ); // Writers before writer_idx have already had their callback fired and - // may have been freed; only notify the still-pending ones, dedup'd. - let mut pending: Vec = Vec::new(); - for w in &s.writers[s.writer_idx..] { - if !w.is_dead() && !pending.contains(&w.ptr) { - pending.push(w.ptr); + // may have been freed; only the still-pending ones are notified. + let mut idx = s.writer_idx; + let mut withheld: Option = None; + // Re-derived every iteration: a callback may `cancel_chunks`. + while let Some(w) = self.state().writers.get(idx) { + let (dead, child, this_idx) = (w.is_dead(), w.ptr, idx); + idx += 1; + if dead { + continue; } + if withheld.is_none() && withhold == Some(child) { + withheld = Some(this_idx); + continue; + } + // `SystemError` owns its strings by value, so derive a fresh one + // per callee instead of cloning the stored error. + self.run_yield(Yield::OnIoWriterChunk { + child, + written: 0, + err: Some(err.to_shell_system_error()), + }); } + let withheld = withheld + .and_then(|i| self.state().writers.get(i)) + .filter(|w| !w.is_dead()) + .map(|w| Yield::OnIoWriterChunk { + child: w.ptr, + written: 0, + err: Some(err.to_shell_system_error()), + }); + let s = self.state(); s.total_bytes_written = 0; s.writer_idx = 0; s.buf.clear(); s.writers.clear(); - pending + withheld } /// Write failure reported by the `bun_io` writer callbacks. Each pending - /// child's error completion is driven through its own `Yield::run`; on + /// chunk's error completion is driven through its own `Yield::run`; on /// POSIX these callbacks only fire from the event loop, with no trampoline /// on the stack. On Windows uv can also deliver a synchronous submission /// failure from under `write()` (`start_with_current_pipe` returns `Ok` /// unconditionally), a re-entry `write()` cannot turn into a /// `WriteOutcome::Failed`. fn on_error(&self, err: &sys::Error) { - let _keepalive = self.keepalive(); - for ptr in self.fail_pending_writers(err) { - // `SystemError` owns `bun_core::String`s by value (no shared - // refcount yet), so re-derive a fresh one per callee instead of - // cloning the stored error. - let ee = err.to_shell_system_error(); - self.run_yield(Yield::OnIoWriterChunk { - child: ptr, - written: 0, - err: Some(ee), - }); - } + self.fail_pending_writers(err, None); } /// Synchronous write failure while `child`'s `enqueue` call (and therefore @@ -881,31 +885,15 @@ impl IOWriter { /// *returned* so that trampoline delivers it after `enqueue` unwinds; /// calling `on_error` here instead would re-enter `Yield::run` once per /// failing command and fire `child`'s callback from inside its own - /// `enqueue`. Usually `child`'s chunk is the only pending one (a - /// synchronous failure is the first write attempt of a batch); if a poll - /// re-registration fails while other children are still queued, those are - /// dispatched the way the async path dispatches them. + /// `enqueue`. Usually the chunk `enqueue` just pushed is the only pending + /// one (a synchronous failure is the first write attempt of a batch); if a + /// poll re-registration fails while other chunks are still queued, those + /// are dispatched the way the async path dispatches them. `Yield::done()` + /// comes back only if one of those completions made `child` cancel its + /// remaining chunks, i.e. it has already finished. fn on_sync_error(&self, child: ChildPtr, err: &sys::Error) -> Yield { - let _keepalive = self.keepalive(); - let mut completion = None; - for ptr in self.fail_pending_writers(err) { - // `SystemError` owns `bun_core::String`s by value (no shared - // refcount yet), so re-derive a fresh one per callee. - let y = Yield::OnIoWriterChunk { - child: ptr, - written: 0, - err: Some(err.to_shell_system_error()), - }; - if completion.is_none() && ptr == child { - completion = Some(y); - } else { - self.run_yield(y); - } - } - // The writer `enqueue` just pushed for `child` is live and at or past - // `writer_idx`, so it is always in the pending list. - debug_assert!(completion.is_some()); - completion.unwrap_or_else(Yield::done) + self.fail_pending_writers(err, Some(child)) + .unwrap_or_else(Yield::done) } fn on_close(&self) { diff --git a/src/runtime/shell/builtin/cat.rs b/src/runtime/shell/builtin/cat.rs index f1b338640653..f1db6a3b07ad 100644 --- a/src/runtime/shell/builtin/cat.rs +++ b/src/runtime/shell/builtin/cat.rs @@ -248,7 +248,10 @@ impl Cat { node: cmd, tag: ReaderTag::Cat, }; - // Writing to stdout errored: cancel everything and finish. + // Writing to stdout errored: cancel everything and finish. The + // writer fails each queued chunk separately, so the chunks still + // queued behind this one must not call back into a finished cat. + Self::cancel_stdout_chunks(interp, cmd); // Pull the reader `Arc` out of // state before calling `remove_reader`, then drop it. match &mut Self::state_mut(interp, cmd).state { @@ -395,13 +398,17 @@ impl Cat { CatState::WaitingWriteErr | CatState::Idle => Step::Suspend, }; if cancel { - let wchild = ChildPtr::new(cmd, WriterTag::Builtin); - if let BuiltinIO::Fd(fd) = &Builtin::of(interp, cmd).stdout { - fd.writer.cancel_chunks(wchild); - } + Self::cancel_stdout_chunks(interp, cmd); } step.run(interp, cmd) } + + fn cancel_stdout_chunks(interp: &Interpreter, cmd: NodeId) { + if let BuiltinIO::Fd(fd) = &Builtin::of(interp, cmd).stdout { + fd.writer + .cancel_chunks(ChildPtr::new(cmd, WriterTag::Builtin)); + } + } } #[derive(Clone, Copy, Default)] diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index c10b1170d5da..ec63d804b0a9 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -1599,14 +1599,19 @@ impl CapturedWriter { .writer .clone() .expect("CapturedWriter live without writer"); - // The CapturedWriter lives outside the NodeId arena (embedded in a - // heap-allocated PipeReader), so dispatch is by raw pointer — see - // `io_writer::ChildPtr::subproc_capture` / `WriterTag::Subproc`. - let child = io_writer::ChildPtr::subproc_capture(std::ptr::from_mut(self).cast::()); + let child = self.child_ptr(); let y = writer.enqueue(child, None, chunk); self.parent().run_yield(y); } + /// How this writer's chunks are identified on the IOWriter queue. The + /// CapturedWriter lives outside the NodeId arena (embedded in a + /// heap-allocated PipeReader), so dispatch is by raw pointer — see + /// `io_writer::ChildPtr::subproc_capture` / `WriterTag::Subproc`. + fn child_ptr(&mut self) -> io_writer::ChildPtr { + io_writer::ChildPtr::subproc_capture(std::ptr::from_mut(self).cast::()) + } + pub(crate) fn on_iowriter_chunk(&mut self, amount: usize, err: Option) -> Yield { let addr = std::ptr::from_mut(self) as usize; let written = self.written + amount; @@ -1634,6 +1639,13 @@ impl CapturedWriter { e.syscall ); self.err = Some(e); + // The writer fails each queued chunk separately; the rest of ours + // must not call back in here once the Cmd below has released this + // PipeReader (`do_write` stops enqueueing now that `err` is set). + let child = self.child_ptr(); + if let Some(writer) = &self.writer { + writer.cancel_chunks(child); + } } else if !all_written { return Yield::Suspended; } diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index 27f6eabe8302..a14c9a78c740 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from "bun:test"; -import { isPosix } from "harness"; +import { bunEnv, bunExe, isPosix, tempDir } from "harness"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -20,3 +22,92 @@ describe.if(isPosix)("IOWriter epipe", () => { } }); }); + +// The shell echoes command output to the process's stdout. Once nothing reads +// that stdout anymore, every chunk of output a command queues fails with +// EPIPE, and the command still has to finish so that the awaited `$` settles. +// A command with several chunks queued at that point used to be told about the +// failure once and then wait forever for the rest of them. +describe.if(isPosix)("command output after the stdout reader went away", () => { + const names = Array.from({ length: 16 }, (_, i) => `entry${i}`); + const args = names.join(" "); + + // The fixture keeps writing to its own stdout until that fails with EPIPE, + // so the command only runs once the test has really closed the read end. + // + // The output is produced in the background (by one thread pool task per + // argument, or by the subprocess). Blocking the main thread right after + // starting the command lets all of it pile up, so that it is queued, and + // fails, in one batch: the situation that used to hang. The fixed command + // has to settle however the output ends up being batched, so nothing below + // depends on the length of that pause. + function fixture(command: string): string { + return ` +import { $ } from "bun"; +import { writeSync } from "node:fs"; +while (true) { + try { + writeSync(1, "still has a reader\\n"); + } catch (e) { + if (e.code === "EPIPE") break; + if (e.code !== "EAGAIN") throw e; + } + await Bun.sleep(1); +} +const running = $\`${command}\`.nothrow().run(); +Bun.sleepSync(100); +await running; +console.error("settled"); +`; + } + + async function expectFixtureToSettle(dir: string) { + await using proc = Bun.spawn({ + cmd: [bunExe(), "fixture.ts"], + cwd: dir, + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + await proc.stdout.cancel(); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + expect(stderr).toBe("settled\n"); + expect(exitCode).toBe(0); + } + + function existing(dir: string): string[] { + return names.filter(name => existsSync(join(dir, name))); + } + + test.concurrent("ls with several arguments", async () => { + using dir = tempDir("shell-epipe-ls", { + "fixture.ts": fixture(`ls -d ${args}`), + ...Object.fromEntries(names.map(name => [name, {}])), + }); + await expectFixtureToSettle(String(dir)); + }); + + test.concurrent("mkdir -v with several arguments", async () => { + using dir = tempDir("shell-epipe-mkdir", { "fixture.ts": fixture(`mkdir -v ${args}`) }); + await expectFixtureToSettle(String(dir)); + expect(existing(String(dir))).toEqual(names); + }); + + test.concurrent("rm -v with several arguments", async () => { + using dir = tempDir("shell-epipe-rm", { + "fixture.ts": fixture(`rm -v ${args}`), + ...Object.fromEntries(names.map(name => [name, ""])), + }); + await expectFixtureToSettle(String(dir)); + expect(existing(String(dir))).toEqual([]); + }); + + // A subprocess's output is relayed to stdout through the same writer, one + // chunk per read. The relay gives up at its first failed chunk and can be + // freed along with the subprocess's pipe right there, so the chunks it still + // had queued must not be reported to it afterwards. + test.concurrent("relayed subprocess output", async () => { + using dir = tempDir("shell-epipe-subprocess", { "fixture.ts": fixture("head -c 1048576 /dev/zero") }); + await expectFixtureToSettle(String(dir)); + }); +}); From 1ea2a5204f4b7714c66377bc02d58b5917399593 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 15 Sep 2026 15:44:10 +0000 Subject: [PATCH 02/12] test(shell): cover ls -R into a pipe whose reader exits without reading `ls -R dir | true` with many subdirectories queues one chunk per directory on the pipe's IOWriter. When `true` exits, the writer fails with several chunks still queued. With one error completion per child, ls counted one of them and waited for the others forever. --- test/js/bun/shell/epipe.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index a14c9a78c740..a65e78ae5e0f 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -21,6 +21,19 @@ describe.if(isPosix)("IOWriter epipe", () => { expect(result).toBe("y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"); } }); + + // `ls -R` writes the listing of each directory to the pipe separately. Once + // the reader is gone, every write that is still queued fails, and ls only + // finishes after it has seen all of them fail. + test("ls -R finishes when the pipe reader exits without reading", async () => { + using dir = tempDir( + "shell-epipe-ls-recursive", + Object.fromEntries(Array.from({ length: 1000 }, (_, i) => [`dir${i}`, {}])), + ); + const { stdout, exitCode } = await Bun.$`ls -R . | true`.cwd(String(dir)).quiet().nothrow(); + expect(stdout.toString()).toBe(""); + expect(exitCode).toBe(0); + }); }); // The shell echoes command output to the process's stdout. Once nothing reads From eb95474366dd1025654efd349813110d69b130b9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:13:52 +0000 Subject: [PATCH 03/12] test(shell): cover the pipeline shapes that lose their reader A pipe between two pipeline stages is an IOWriter too. The stage on its left loses its reader when the next stage exits without reading its stdin. Cover the writers that queue one chunk per directory or operand (ls -R, ls -d, mkdir -v, rm -v), a builtin reader, an external reader that exits at once, head -n 1, and a reader in the middle of the pipeline. The builtin-only shapes run on Windows too. --- test/js/bun/shell/epipe.test.ts | 77 +++++++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 17 deletions(-) diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index a65e78ae5e0f..2bd894bf8655 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -1,3 +1,4 @@ +import { $ } from "bun"; import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isPosix, tempDir } from "harness"; import { existsSync } from "node:fs"; @@ -21,18 +22,64 @@ describe.if(isPosix)("IOWriter epipe", () => { expect(result).toBe("y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"); } }); +}); - // `ls -R` writes the listing of each directory to the pipe separately. Once - // the reader is gone, every write that is still queued fails, and ls only - // finishes after it has seen all of them fail. - test("ls -R finishes when the pipe reader exits without reading", async () => { - using dir = tempDir( - "shell-epipe-ls-recursive", - Object.fromEntries(Array.from({ length: 1000 }, (_, i) => [`dir${i}`, {}])), - ); - const { stdout, exitCode } = await Bun.$`ls -R . | true`.cwd(String(dir)).quiet().nothrow(); - expect(stdout.toString()).toBe(""); - expect(exitCode).toBe(0); +function existing(dir: string, names: string[]): string[] { + return names.filter(name => existsSync(join(dir, name))); +} + +// The pipe between two stages of a pipeline is an IOWriter too. A stage loses +// its reader when the next stage exits without reading its stdin. `ls`, +// `mkdir -v` and `rm -v` queue one chunk per directory or operand, and finish +// only after every chunk they queued has completed or failed. +describe("pipeline stage whose reader exits without reading", () => { + const names = Array.from({ length: 64 }, (_, i) => `entry${i}`); + const operands = names.join(" "); + const files = Object.fromEntries(names.map(name => [name, ""])); + const tree = Object.fromEntries(Array.from({ length: 300 }, (_, i) => [`dir${i}`, {}])); + + async function run(dir: string, pipeline: string) { + const { stdout, exitCode } = await $`${{ raw: pipeline }}`.cwd(dir).quiet().nothrow(); + return { stdout: stdout.toString(), exitCode }; + } + + test.concurrent("ls with several operands", async () => { + using dir = tempDir("shell-pipe-ls", files); + expect(await run(String(dir), `ls -d ${operands} | true`)).toEqual({ stdout: "", exitCode: 0 }); + }); + + test.concurrent("mkdir -v with several operands", async () => { + using dir = tempDir("shell-pipe-mkdir", {}); + expect(await run(String(dir), `mkdir -v ${operands} | true`)).toEqual({ stdout: "", exitCode: 0 }); + expect(existing(String(dir), names)).toEqual(names); + }); + + test.concurrent("rm -v with several operands", async () => { + using dir = tempDir("shell-pipe-rm", files); + expect(await run(String(dir), `rm -v ${operands} | true`)).toEqual({ stdout: "", exitCode: 0 }); + expect(existing(String(dir), names)).toEqual([]); + }); + + test.concurrent("ls -R into a builtin", async () => { + using dir = tempDir("shell-pipe-ls-recursive", tree); + expect(await run(String(dir), "ls -R . | true")).toEqual({ stdout: "", exitCode: 0 }); + }); + + test.concurrent("ls -R into a stage in the middle", async () => { + using dir = tempDir("shell-pipe-ls-recursive-middle", tree); + expect(await run(String(dir), "ls -R . | true | cat")).toEqual({ stdout: "", exitCode: 0 }); + }); + + test.concurrent.if(isPosix)("ls -R into a command that exits at once", async () => { + using dir = tempDir("shell-pipe-ls-recursive-exit", tree); + expect(await run(String(dir), "ls -R . | sh -c 'exit 0'")).toEqual({ stdout: "", exitCode: 0 }); + }); + + // `head` exits after the first line, while ls still has chunks queued. + test.concurrent.if(isPosix)("ls -R into head -n 1", async () => { + using dir = tempDir("shell-pipe-ls-recursive-head", tree); + const { stdout, exitCode } = await run(String(dir), "ls -R . | head -n 1"); + expect({ lines: stdout.split("\n").length - 1, exitCode }).toEqual({ lines: 1, exitCode: 0 }); }); }); @@ -88,10 +135,6 @@ console.error("settled"); expect(exitCode).toBe(0); } - function existing(dir: string): string[] { - return names.filter(name => existsSync(join(dir, name))); - } - test.concurrent("ls with several arguments", async () => { using dir = tempDir("shell-epipe-ls", { "fixture.ts": fixture(`ls -d ${args}`), @@ -103,7 +146,7 @@ console.error("settled"); test.concurrent("mkdir -v with several arguments", async () => { using dir = tempDir("shell-epipe-mkdir", { "fixture.ts": fixture(`mkdir -v ${args}`) }); await expectFixtureToSettle(String(dir)); - expect(existing(String(dir))).toEqual(names); + expect(existing(String(dir), names)).toEqual(names); }); test.concurrent("rm -v with several arguments", async () => { @@ -112,7 +155,7 @@ console.error("settled"); ...Object.fromEntries(names.map(name => [name, ""])), }); await expectFixtureToSettle(String(dir)); - expect(existing(String(dir))).toEqual([]); + expect(existing(String(dir), names)).toEqual([]); }); // A subprocess's output is relayed to stdout through the same writer, one From a02dad0a73941074f69899fce7a8a97c094ef3cc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:13:53 +0000 Subject: [PATCH 04/12] shell: tighten the fail_pending_writers doc comment --- src/runtime/shell/IOWriter.rs | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/runtime/shell/IOWriter.rs b/src/runtime/shell/IOWriter.rs index ebc4fed1531e..4f557210923c 100644 --- a/src/runtime/shell/IOWriter.rs +++ b/src/runtime/shell/IOWriter.rs @@ -795,26 +795,23 @@ impl IOWriter { } } - /// Shared failure path: record the error, then fail every chunk that is - /// still queued, oldest first, with its own error completion. + /// Shared failure path: record the error, then give every chunk that is + /// still queued its own error completion, oldest first. /// - /// One completion per *chunk*, not per child. `rm` and the `OutputTask` + /// One completion per *chunk*, not per child: `rm` and the `OutputTask` /// builtins (`ls`, `mkdir`, `touch`, `cp`) queue one chunk per task under - /// the same `ChildPtr` and finish once they have counted a completion for - /// each, so a single per-child error left them waiting for the rest - /// forever. A child that stops at its first error while more of its - /// chunks are queued (`cat`, the subprocess `CapturedWriter`) calls - /// `cancel_chunks` from that callback; that is why the queue is walked in - /// place, each entry re-checked right before its callback, and only - /// cleared after the last completion. Nothing is appended meanwhile: - /// `err`/`broken_pipe` are set before the first callback, so a child that - /// enqueues from its callback (the next statement, the RHS of `&&`, ...) - /// is answered by `handle_dead_writer` instead of being queued onto a - /// writer whose handle the error path is tearing down. + /// one `ChildPtr` and finish only after a completion for each. A child + /// that stops at its first error (`cat`, the subprocess `CapturedWriter`) + /// calls `cancel_chunks` from that callback, so the queue is walked in + /// place and each entry is re-checked right before its callback. Nothing + /// is appended meanwhile: `err` is set before the first callback, so a + /// child that enqueues from its callback (the next statement, the RHS of + /// `&&`, ...) is answered by `handle_dead_writer`, not queued onto a writer + /// whose handle the error path is tearing down. /// /// `withhold` is the child whose `enqueue` is still on the stack (see - /// `on_sync_error`): the first of its chunks is not dispatched here but - /// returned, provided it is still live once everything else has run. + /// `on_sync_error`). Its first live chunk is not dispatched here. It is + /// returned, if it is still live after everything else has run. fn fail_pending_writers(&self, err: &sys::Error, withhold: Option) -> Option { // A completion may drop the last external `Arc` to this writer. let _keepalive = self.keepalive(); From 74a0fb6d7827260884b0fdb1749e72a8882936f8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 00:27:26 +0000 Subject: [PATCH 05/12] test(shell): cover cat losing its pipe reader with several chunks queued On Windows cat is a builtin. It finishes at its first failed chunk, so it cancels the chunks queued behind it. Without that cancel a second error completion reaches the finished cat and panics with "expected Node::Cmd at Node#3, got Free". --- test/js/bun/shell/epipe.test.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index 2bd894bf8655..dbf6b4adfbe7 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -1,6 +1,6 @@ import { $ } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isPosix, tempDir } from "harness"; +import { bunEnv, bunExe, isPosix, isWindows, tempDir } from "harness"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { createTestBuilder } from "./test_builder"; @@ -81,6 +81,27 @@ describe("pipeline stage whose reader exits without reading", () => { const { stdout, exitCode } = await run(String(dir), "ls -R . | head -n 1"); expect({ lines: stdout.split("\n").length - 1, exitCode }).toEqual({ lines: 1, exitCode: 0 }); }); + + // On Windows `cat` is a builtin. It finishes at its first failed chunk, so + // the chunks queued behind that one must not complete into the finished + // cat. That is a panic, so the pipeline runs in a child process. + test.concurrent.if(isWindows)("cat with several chunks queued", async () => { + using dir = tempDir("shell-pipe-cat", { "big.txt": Buffer.alloc(1024 * 1024, "a").toString() }); + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + "const { exitCode } = await Bun.$`cat big.txt | true`.quiet().nothrow(); console.log(exitCode);", + ], + cwd: String(dir), + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + if (exitCode !== 0) console.error(stderr); + expect({ stdout, exitCode, signalCode: proc.signalCode }).toEqual({ stdout: "0\n", exitCode: 0, signalCode: null }); + }); }); // The shell echoes command output to the process's stdout. Once nothing reads From 5aefab3779158999803c5d1c0a0fee619226bef0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 00:33:25 +0000 Subject: [PATCH 06/12] shell: keep the new IOWriter comments to one line --- src/runtime/shell/IOWriter.rs | 49 +++++++++++--------------------- src/runtime/shell/builtin/cat.rs | 4 +-- src/runtime/shell/subproc.rs | 9 ++---- 3 files changed, 19 insertions(+), 43 deletions(-) diff --git a/src/runtime/shell/IOWriter.rs b/src/runtime/shell/IOWriter.rs index 4f557210923c..481de3d90611 100644 --- a/src/runtime/shell/IOWriter.rs +++ b/src/runtime/shell/IOWriter.rs @@ -514,10 +514,7 @@ impl IOWriter { // ── queue management ──────────────────────────────────────────────── - /// Cancel the chunks enqueued by the given child by marking them as dead: - /// they are skipped without a callback, both when the queue drains and - /// when it fails (`fail_pending_writers`), so a child that is about to - /// finish with chunks still queued calls this first. + /// Cancel the chunks enqueued by the given child by marking them as dead. pub(crate) fn cancel_chunks(&self, ptr: ChildPtr) { let s = self.state(); if s.writers.is_empty() { @@ -765,8 +762,7 @@ impl IOWriter { if !not_fully_written { return; } - // Other end of the socket/pipe closed (e.g. `ls | echo`): - // everything still queued fails with EPIPE. + // The other end closed (e.g. `ls | echo`): every queued chunk fails with EPIPE. self.fail_pending_writers(&sys::Error::from_code(E::EPIPE, sys::Tag::write), None); return; } @@ -795,23 +791,7 @@ impl IOWriter { } } - /// Shared failure path: record the error, then give every chunk that is - /// still queued its own error completion, oldest first. - /// - /// One completion per *chunk*, not per child: `rm` and the `OutputTask` - /// builtins (`ls`, `mkdir`, `touch`, `cp`) queue one chunk per task under - /// one `ChildPtr` and finish only after a completion for each. A child - /// that stops at its first error (`cat`, the subprocess `CapturedWriter`) - /// calls `cancel_chunks` from that callback, so the queue is walked in - /// place and each entry is re-checked right before its callback. Nothing - /// is appended meanwhile: `err` is set before the first callback, so a - /// child that enqueues from its callback (the next statement, the RHS of - /// `&&`, ...) is answered by `handle_dead_writer`, not queued onto a writer - /// whose handle the error path is tearing down. - /// - /// `withhold` is the child whose `enqueue` is still on the stack (see - /// `on_sync_error`). Its first live chunk is not dispatched here. It is - /// returned, if it is still live after everything else has run. + /// Fails every chunk still queued, oldest first, each with its own error completion. fn fail_pending_writers(&self, err: &sys::Error, withhold: Option) -> Option { // A completion may drop the last external `Arc` to this writer. let _keepalive = self.keepalive(); @@ -820,6 +800,10 @@ impl IOWriter { if err.get_errno() == E::EPIPE { s.flags.broken_pipe = true; } + // Mark the writer dead before any completion below runs: a child that + // enqueues from its callback (the next statement, the RHS of `&&`, ...) + // must be rejected by `handle_dead_writer`, not queued onto a writer + // whose handle the error path is tearing down. s.err = Some(err.clone()); crate::shell_log!( "IOWriter(fd={}) failing {} queued chunk(s): {:?}", @@ -828,22 +812,22 @@ impl IOWriter { err.get_errno() ); // Writers before writer_idx have already had their callback fired and - // may have been freed; only the still-pending ones are notified. + // may have been freed; only notify the still-pending ones. let mut idx = s.writer_idx; let mut withheld: Option = None; - // Re-derived every iteration: a callback may `cancel_chunks`. + // Re-derived every iteration: a callback may `cancel_chunks` the entries behind it. while let Some(w) = self.state().writers.get(idx) { let (dead, child, this_idx) = (w.is_dead(), w.ptr, idx); idx += 1; if dead { continue; } + // `withhold`'s `enqueue` is on the stack: its first live chunk is returned, not run. if withheld.is_none() && withhold == Some(child) { withheld = Some(this_idx); continue; } - // `SystemError` owns its strings by value, so derive a fresh one - // per callee instead of cloning the stored error. + // `SystemError` is not `Clone`: each completion derives its own. self.run_yield(Yield::OnIoWriterChunk { child, written: 0, @@ -882,13 +866,12 @@ impl IOWriter { /// *returned* so that trampoline delivers it after `enqueue` unwinds; /// calling `on_error` here instead would re-enter `Yield::run` once per /// failing command and fire `child`'s callback from inside its own - /// `enqueue`. Usually the chunk `enqueue` just pushed is the only pending - /// one (a synchronous failure is the first write attempt of a batch); if a - /// poll re-registration fails while other chunks are still queued, those - /// are dispatched the way the async path dispatches them. `Yield::done()` - /// comes back only if one of those completions made `child` cancel its - /// remaining chunks, i.e. it has already finished. + /// `enqueue`. Usually `child`'s chunk is the only pending one (a + /// synchronous failure is the first write attempt of a batch); if a poll + /// re-registration fails while other children are still queued, those are + /// dispatched the way the async path dispatches them. fn on_sync_error(&self, child: ChildPtr, err: &sys::Error) -> Yield { + // `None`: an inline completion made `child` cancel its chunks, so it has finished. self.fail_pending_writers(err, Some(child)) .unwrap_or_else(Yield::done) } diff --git a/src/runtime/shell/builtin/cat.rs b/src/runtime/shell/builtin/cat.rs index f1db6a3b07ad..47cce911dcb4 100644 --- a/src/runtime/shell/builtin/cat.rs +++ b/src/runtime/shell/builtin/cat.rs @@ -248,9 +248,7 @@ impl Cat { node: cmd, tag: ReaderTag::Cat, }; - // Writing to stdout errored: cancel everything and finish. The - // writer fails each queued chunk separately, so the chunks still - // queued behind this one must not call back into a finished cat. + // Writing to stdout errored: cancel everything and finish. Self::cancel_stdout_chunks(interp, cmd); // Pull the reader `Arc` out of // state before calling `remove_reader`, then drop it. diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index ec63d804b0a9..9c777911579e 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -1604,10 +1604,7 @@ impl CapturedWriter { self.parent().run_yield(y); } - /// How this writer's chunks are identified on the IOWriter queue. The - /// CapturedWriter lives outside the NodeId arena (embedded in a - /// heap-allocated PipeReader), so dispatch is by raw pointer — see - /// `io_writer::ChildPtr::subproc_capture` / `WriterTag::Subproc`. + /// This writer's identity on the IOWriter queue, see `ChildPtr::subproc_capture`. fn child_ptr(&mut self) -> io_writer::ChildPtr { io_writer::ChildPtr::subproc_capture(std::ptr::from_mut(self).cast::()) } @@ -1639,9 +1636,7 @@ impl CapturedWriter { e.syscall ); self.err = Some(e); - // The writer fails each queued chunk separately; the rest of ours - // must not call back in here once the Cmd below has released this - // PipeReader (`do_write` stops enqueueing now that `err` is set). + // The chunks still queued must not call back: the Cmd below can free this PipeReader. let child = self.child_ptr(); if let Some(writer) = &self.writer { writer.cancel_chunks(child); From bb0a17bb60e38782fdd59d2d1f329187ca85852f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 01:09:53 +0000 Subject: [PATCH 07/12] test(shell): run the stdout fixture commands ten times instead of pausing The fixture blocked the main thread for 100 ms so that every chunk was queued before the first write failed. Only a run with several chunks queued takes the path under test, so the fixture now runs the command ten times and has no timed wait. It is a file now (epipe-fixture.ts). --- test/js/bun/shell/epipe-fixture.ts | 37 +++++++++++++++ test/js/bun/shell/epipe.test.ts | 75 ++++++++---------------------- 2 files changed, 56 insertions(+), 56 deletions(-) create mode 100644 test/js/bun/shell/epipe-fixture.ts diff --git a/test/js/bun/shell/epipe-fixture.ts b/test/js/bun/shell/epipe-fixture.ts new file mode 100644 index 000000000000..03b26ad16cb1 --- /dev/null +++ b/test/js/bun/shell/epipe-fixture.ts @@ -0,0 +1,37 @@ +// usage: bun epipe-fixture.ts ... +import { $ } from "bun"; +import { rmSync, writeFileSync, writeSync } from "node:fs"; + +const [command, ...names] = process.argv.slice(2); + +function start() { + switch (command) { + case "ls": + return $`ls -d ${names}`; + case "mkdir": + for (const name of names) rmSync(name, { recursive: true, force: true }); + return $`mkdir -v ${names}`; + case "rm": + for (const name of names) writeFileSync(name, ""); + return $`rm -v ${names}`; + case "subprocess": + return $`head -c 1048576 /dev/zero`; + default: + throw new Error(`unknown command: ${command}`); + } +} + +// The test closes the read end of stdout right after the spawn. Wait until a write fails. +while (true) { + try { + writeSync(1, "still has a reader\n"); + } catch (e) { + if (e.code === "EPIPE") break; + if (e.code !== "EAGAIN") throw e; + } + await Bun.sleep(1); +} + +// Only a run with several chunks queued before the first write fails takes the path under test. +for (let run = 0; run < 10; run++) await start().nothrow(); +console.error("settled"); diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index dbf6b4adfbe7..1a012a75fb61 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -105,46 +105,14 @@ describe("pipeline stage whose reader exits without reading", () => { }); // The shell echoes command output to the process's stdout. Once nothing reads -// that stdout anymore, every chunk of output a command queues fails with -// EPIPE, and the command still has to finish so that the awaited `$` settles. -// A command with several chunks queued at that point used to be told about the -// failure once and then wait forever for the rest of them. +// that stdout, every chunk of output a command queues fails with EPIPE, and the +// command still has to finish so that the awaited `$` settles. describe.if(isPosix)("command output after the stdout reader went away", () => { const names = Array.from({ length: 16 }, (_, i) => `entry${i}`); - const args = names.join(" "); - - // The fixture keeps writing to its own stdout until that fails with EPIPE, - // so the command only runs once the test has really closed the read end. - // - // The output is produced in the background (by one thread pool task per - // argument, or by the subprocess). Blocking the main thread right after - // starting the command lets all of it pile up, so that it is queued, and - // fails, in one batch: the situation that used to hang. The fixed command - // has to settle however the output ends up being batched, so nothing below - // depends on the length of that pause. - function fixture(command: string): string { - return ` -import { $ } from "bun"; -import { writeSync } from "node:fs"; -while (true) { - try { - writeSync(1, "still has a reader\\n"); - } catch (e) { - if (e.code === "EPIPE") break; - if (e.code !== "EAGAIN") throw e; - } - await Bun.sleep(1); -} -const running = $\`${command}\`.nothrow().run(); -Bun.sleepSync(100); -await running; -console.error("settled"); -`; - } - async function expectFixtureToSettle(dir: string) { + async function expectFixtureToSettle(command: string, dir: string) { await using proc = Bun.spawn({ - cmd: [bunExe(), "fixture.ts"], + cmd: [bunExe(), join(import.meta.dir, "epipe-fixture.ts"), command, ...names], cwd: dir, env: bunEnv, stdout: "pipe", @@ -152,39 +120,34 @@ console.error("settled"); }); await proc.stdout.cancel(); const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); - expect(stderr).toBe("settled\n"); - expect(exitCode).toBe(0); + expect({ stderr, exitCode, signalCode: proc.signalCode }).toEqual({ + stderr: "settled\n", + exitCode: 0, + signalCode: null, + }); } test.concurrent("ls with several arguments", async () => { - using dir = tempDir("shell-epipe-ls", { - "fixture.ts": fixture(`ls -d ${args}`), - ...Object.fromEntries(names.map(name => [name, {}])), - }); - await expectFixtureToSettle(String(dir)); + using dir = tempDir("shell-epipe-ls", Object.fromEntries(names.map(name => [name, {}]))); + await expectFixtureToSettle("ls", String(dir)); }); test.concurrent("mkdir -v with several arguments", async () => { - using dir = tempDir("shell-epipe-mkdir", { "fixture.ts": fixture(`mkdir -v ${args}`) }); - await expectFixtureToSettle(String(dir)); + using dir = tempDir("shell-epipe-mkdir", {}); + await expectFixtureToSettle("mkdir", String(dir)); expect(existing(String(dir), names)).toEqual(names); }); test.concurrent("rm -v with several arguments", async () => { - using dir = tempDir("shell-epipe-rm", { - "fixture.ts": fixture(`rm -v ${args}`), - ...Object.fromEntries(names.map(name => [name, ""])), - }); - await expectFixtureToSettle(String(dir)); + using dir = tempDir("shell-epipe-rm", {}); + await expectFixtureToSettle("rm", String(dir)); expect(existing(String(dir), names)).toEqual([]); }); - // A subprocess's output is relayed to stdout through the same writer, one - // chunk per read. The relay gives up at its first failed chunk and can be - // freed along with the subprocess's pipe right there, so the chunks it still - // had queued must not be reported to it afterwards. + // The relay of a subprocess's output stops at its first failed chunk and can + // be freed right there, so its other queued chunks must not reach it. test.concurrent("relayed subprocess output", async () => { - using dir = tempDir("shell-epipe-subprocess", { "fixture.ts": fixture("head -c 1048576 /dev/zero") }); - await expectFixtureToSettle(String(dir)); + using dir = tempDir("shell-epipe-subprocess", {}); + await expectFixtureToSettle("subprocess", String(dir)); }); }); From 4bc407c59b8b69256ce1cd95c20d8345bf3fd1be Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 19:56:51 +0000 Subject: [PATCH 08/12] shell(cat): do not finish while output chunks are still queued The file form of cat kept an out_done flag that stayed set once its output queue had drained. When more input arrived afterwards, cat still finished at the end of its input with chunks queued. The node is reused by the next command, which then received the completions of those chunks: output was lost, and with one error completion per chunk the second one reached a freed node (panic: expected Node::Cmd at Node#2, got Free). cat now compares chunks_done with chunks_queued, as the stdin form already does. --- src/runtime/shell/builtin/cat.rs | 15 ++----- test/js/bun/shell/epipe.test.ts | 75 ++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 12 deletions(-) diff --git a/src/runtime/shell/builtin/cat.rs b/src/runtime/shell/builtin/cat.rs index 47cce911dcb4..a0f8d7749aae 100644 --- a/src/runtime/shell/builtin/cat.rs +++ b/src/runtime/shell/builtin/cat.rs @@ -33,7 +33,6 @@ pub enum CatState { reader: Option>, chunks_queued: usize, chunks_done: usize, - out_done: bool, in_done: bool, }, WaitingWriteErr, @@ -89,7 +88,6 @@ impl Cat { reader: None, chunks_queued: 0, chunks_done: 0, - out_done: false, in_done: false, } }; @@ -216,14 +214,12 @@ impl Cat { chunks_done, chunks_queued, in_done, - out_done, .. } = &mut Self::state_mut(interp, cmd).state { *chunks_done = 0; *chunks_queued = 0; *in_done = false; - *out_done = false; *slot = Some(Arc::clone(&reader)); } reader.add_reader(ReaderChildPtr { @@ -295,14 +291,10 @@ impl Cat { chunks_queued, chunks_done, in_done, - out_done, .. } => { *chunks_done += 1; - if *chunks_done >= *chunks_queued { - *out_done = true; - } - if *in_done && *out_done { + if *in_done && *chunks_done >= *chunks_queued { Step::Next } else { Step::Suspend @@ -373,13 +365,12 @@ impl Cat { chunks_queued, chunks_done, in_done, - out_done, reader, .. } => { *in_done = true; if errno != 0 { - if *out_done || !stdout_needs_io { + if *chunks_done >= *chunks_queued || !stdout_needs_io { // Drop the reader ref. *reader = None; Step::Done(errno) @@ -387,7 +378,7 @@ impl Cat { cancel = true; Step::Suspend } - } else if *out_done || *chunks_done >= *chunks_queued || !stdout_needs_io { + } else if *chunks_done >= *chunks_queued || !stdout_needs_io { Step::Next } else { Step::Suspend diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index 1a012a75fb61..a77cbb6b54ae 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -2,6 +2,7 @@ import { $ } from "bun"; import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isPosix, isWindows, tempDir } from "harness"; import { existsSync } from "node:fs"; +import { open } from "node:fs/promises"; import { join } from "node:path"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -151,3 +152,77 @@ describe.if(isPosix)("command output after the stdout reader went away", () => { await expectFixtureToSettle("subprocess", String(dir)); }); }); + +// The builtin cat queues one chunk per read. It must not finish while one of +// them is still queued: the node is reused by the next command, which then +// receives the completions of those chunks. +describe.if(isPosix)("cat whose input ends while its output is still queued", () => { + const size = 1024 * 1024; + + function spawnCat(dir: string) { + return Bun.spawn({ + cmd: [bunExe(), "-e", "await Bun.$`cat fifo; echo tail`.nothrow(); console.error('settled');"], + env: { ...bunEnv, BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS: "1" }, + cwd: dir, + stdout: "pipe", + stderr: "pipe", + }); + } + + // Lets cat write "first\n", so that its output has drained once. Then feeds it `size` bytes and + // the end of its input while nothing reads its stdout. + async function feed(dir: string, reader: ReadableStreamDefaultReader) { + const received: Uint8Array[] = []; + // "r+" does not wait for cat to open the other end. + const input = await open(join(dir, "fifo"), "r+"); + try { + await input.writeFile("first\n"); + while (Buffer.concat(received).length < "first\n".length) { + const { value, done } = await reader.read(); + if (done) break; + received.push(value); + } + expect(Buffer.concat(received).toString()).toBe("first\n"); + await input.writeFile(Buffer.alloc(size, "a")); + } finally { + await input.close(); + } + return received; + } + + test.concurrent("every byte is written before the next command runs", async () => { + using dir = tempDir("shell-cat-fifo-read", {}); + expect(await Bun.spawn(["mkfifo", join(String(dir), "fifo")]).exited).toBe(0); + await using proc = spawnCat(String(dir)); + const stderr = proc.stderr.text(); + const reader = proc.stdout.getReader(); + const received = await feed(String(dir), reader); + while (true) { + const { value, done } = await reader.read(); + if (done) break; + received.push(value); + } + const stdout = Buffer.concat(received); + expect({ + bytes: stdout.length, + intact: stdout.equals(Buffer.concat([Buffer.from("first\n"), Buffer.alloc(size, "a"), Buffer.from("tail\n")])), + stderr: await stderr, + exitCode: await proc.exited, + }).toEqual({ bytes: "first\n".length + size + "tail\n".length, intact: true, stderr: "settled\n", exitCode: 0 }); + }); + + test.concurrent("the queued chunks fail when the stdout reader goes away", async () => { + using dir = tempDir("shell-cat-fifo-close", {}); + expect(await Bun.spawn(["mkfifo", join(String(dir), "fifo")]).exited).toBe(0); + await using proc = spawnCat(String(dir)); + const stderr = proc.stderr.text(); + const reader = proc.stdout.getReader(); + await feed(String(dir), reader); + await reader.cancel(); + expect({ stderr: await stderr, exitCode: await proc.exited, signalCode: proc.signalCode }).toEqual({ + stderr: "settled\n", + exitCode: 0, + signalCode: null, + }); + }); +}); From 9c10730a354a836cf1af17be332f490a04de9d30 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:04:25 +0000 Subject: [PATCH 09/12] test(shell): cover the builtin cat on Windows with a file read in several chunks --- test/js/bun/shell/epipe.test.ts | 34 ++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index a77cbb6b54ae..6f77bc595a9b 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -156,7 +156,7 @@ describe.if(isPosix)("command output after the stdout reader went away", () => { // The builtin cat queues one chunk per read. It must not finish while one of // them is still queued: the node is reused by the next command, which then // receives the completions of those chunks. -describe.if(isPosix)("cat whose input ends while its output is still queued", () => { +describe("cat whose input ends while its output is still queued", () => { const size = 1024 * 1024; function spawnCat(dir: string) { @@ -190,7 +190,7 @@ describe.if(isPosix)("cat whose input ends while its output is still queued", () return received; } - test.concurrent("every byte is written before the next command runs", async () => { + test.concurrent.if(isPosix)("every byte is written before the next command runs", async () => { using dir = tempDir("shell-cat-fifo-read", {}); expect(await Bun.spawn(["mkfifo", join(String(dir), "fifo")]).exited).toBe(0); await using proc = spawnCat(String(dir)); @@ -211,7 +211,7 @@ describe.if(isPosix)("cat whose input ends while its output is still queued", () }).toEqual({ bytes: "first\n".length + size + "tail\n".length, intact: true, stderr: "settled\n", exitCode: 0 }); }); - test.concurrent("the queued chunks fail when the stdout reader goes away", async () => { + test.concurrent.if(isPosix)("the queued chunks fail when the stdout reader goes away", async () => { using dir = tempDir("shell-cat-fifo-close", {}); expect(await Bun.spawn(["mkfifo", join(String(dir), "fifo")]).exited).toBe(0); await using proc = spawnCat(String(dir)); @@ -225,4 +225,32 @@ describe.if(isPosix)("cat whose input ends while its output is still queued", () signalCode: null, }); }); + + // On Windows cat is a builtin, and a file this large is read in several chunks. A completion + // for a chunk that cat left behind arrives after its pipeline settled, so the pipeline runs again. + test.concurrent.if(isWindows)("every byte of a file reaches the next stage", async () => { + using dir = tempDir("shell-cat-file", { "big.txt": Buffer.alloc(size, "a").toString() }); + const script = ` + const sizes = []; + for (let run = 0; run < 5; run++) { + await Bun.$\`cat big.txt | cat > out.txt\`.nothrow(); + sizes.push(Bun.file("out.txt").size); + } + console.log(JSON.stringify(sizes)); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + if (exitCode !== 0) console.error(stderr); + expect({ stdout, exitCode, signalCode: proc.signalCode }).toEqual({ + stdout: JSON.stringify(Array(5).fill(size)) + "\n", + exitCode: 0, + signalCode: null, + }); + }); }); From f204df772f2d165d985c587c91babe9aede0ef14 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:28:30 +0000 Subject: [PATCH 10/12] test(shell): run the cat FIFO tests on Linux only On macOS both tests time out in CI: the handshake that reads the first line back before it writes more input never completes there. --- test/js/bun/shell/epipe.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/js/bun/shell/epipe.test.ts b/test/js/bun/shell/epipe.test.ts index 6f77bc595a9b..5dcb452411bd 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -1,6 +1,6 @@ import { $ } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isPosix, isWindows, tempDir } from "harness"; +import { bunEnv, bunExe, isLinux, isPosix, isWindows, tempDir } from "harness"; import { existsSync } from "node:fs"; import { open } from "node:fs/promises"; import { join } from "node:path"; @@ -190,7 +190,8 @@ describe("cat whose input ends while its output is still queued", () => { return received; } - test.concurrent.if(isPosix)("every byte is written before the next command runs", async () => { + // Linux only: on macOS the handshake in `feed` never completes and both tests time out in CI. + test.concurrent.if(isLinux)("every byte is written before the next command runs", async () => { using dir = tempDir("shell-cat-fifo-read", {}); expect(await Bun.spawn(["mkfifo", join(String(dir), "fifo")]).exited).toBe(0); await using proc = spawnCat(String(dir)); @@ -211,7 +212,7 @@ describe("cat whose input ends while its output is still queued", () => { }).toEqual({ bytes: "first\n".length + size + "tail\n".length, intact: true, stderr: "settled\n", exitCode: 0 }); }); - test.concurrent.if(isPosix)("the queued chunks fail when the stdout reader goes away", async () => { + test.concurrent.if(isLinux)("the queued chunks fail when the stdout reader goes away", async () => { using dir = tempDir("shell-cat-fifo-close", {}); expect(await Bun.spawn(["mkfifo", join(String(dir), "fifo")]).exited).toBe(0); await using proc = spawnCat(String(dir)); From 4036febc2fc6040d70e9af885cf4303748e7cce8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:44:05 +0000 Subject: [PATCH 11/12] shell: keep the Subproc dispatch SAFETY comment accurate The PipeReader can now be released at the first failed chunk while later chunks of its CapturedWriter are still in the queue. They are cancelled first, so say that. --- src/runtime/shell/IOWriter.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/shell/IOWriter.rs b/src/runtime/shell/IOWriter.rs index 481de3d90611..30e1f9d36309 100644 --- a/src/runtime/shell/IOWriter.rs +++ b/src/runtime/shell/IOWriter.rs @@ -1202,7 +1202,7 @@ pub(crate) fn on_io_writer_chunk( // `CapturedWriter::do_write`; the PipeReader (and the embedded // CapturedWriter) is kept alive by the `Readable::Pipe` Arc on // the owning ShellSubprocess until `on_close_io` runs, which only - // happens after the writer has finished draining. Single-threaded. + // happens once its chunks are all written or cancelled. Single-threaded. let cw = unsafe { &mut *child.raw.cast::() }; cw.on_iowriter_chunk(written, err) } From 6ddd1a6d6d5f437bc134613506601b8f0b9cdcdc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:26:39 +0000 Subject: [PATCH 12/12] ci: retrigger