diff --git a/src/runtime/shell/IOWriter.rs b/src/runtime/shell/IOWriter.rs index ef004501d537..30e1f9d36309 100644 --- a/src/runtime/shell/IOWriter.rs +++ b/src/runtime/shell/IOWriter.rs @@ -762,11 +762,8 @@ 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(); + // 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; } if s.writers[idx].written >= s.writers[idx].len { @@ -794,41 +791,10 @@ 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 { + /// 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(); self.set_writing(false); let s = self.state(); if err.get_errno() == E::EPIPE { @@ -839,41 +805,60 @@ impl IOWriter { // 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 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` 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` is not `Clone`: each completion derives its own. + 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 @@ -886,26 +871,9 @@ impl IOWriter { /// 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 { - 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) + // `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) } fn on_close(&self) { @@ -1234,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) } diff --git a/src/runtime/shell/builtin/cat.rs b/src/runtime/shell/builtin/cat.rs index f1b338640653..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 { @@ -249,6 +245,7 @@ impl Cat { tag: ReaderTag::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. match &mut Self::state_mut(interp, cmd).state { @@ -294,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 @@ -372,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) @@ -386,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 @@ -395,13 +387,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..9c777911579e 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -1599,14 +1599,16 @@ 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); } + /// 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::()) + } + 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 +1636,11 @@ impl CapturedWriter { e.syscall ); self.err = Some(e); + // 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); + } } else if !all_written { return Yield::Suspended; } 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 27f6eabe8302..5dcb452411bd 100644 --- a/test/js/bun/shell/epipe.test.ts +++ b/test/js/bun/shell/epipe.test.ts @@ -1,5 +1,9 @@ +import { $ } from "bun"; import { describe, expect, test } from "bun:test"; -import { isPosix } 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"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -20,3 +24,234 @@ describe.if(isPosix)("IOWriter epipe", () => { } }); }); + +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 }); + }); + + // 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 +// 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}`); + + async function expectFixtureToSettle(command: string, dir: string) { + await using proc = Bun.spawn({ + cmd: [bunExe(), join(import.meta.dir, "epipe-fixture.ts"), command, ...names], + 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, 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", 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", {}); + 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", {}); + await expectFixtureToSettle("rm", String(dir)); + expect(existing(String(dir), names)).toEqual([]); + }); + + // 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", {}); + 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("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; + } + + // 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)); + 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.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)); + 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, + }); + }); + + // 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, + }); + }); +});