From 8212aada5abe92efb4f5c98fde4746e8d7b4927c Mon Sep 17 00:00:00 2001 From: Ciro Spaciari MacBook Date: Fri, 24 Jul 2026 01:11:19 +0000 Subject: [PATCH 1/2] FileSink: hand end() the pending write's promise when flush fails, instead of double-reporting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since #35278, a failed deferred auto-flush rejects the pending write() promise. But when the reader disappears before end() runs — the common Bun.spawn shape where the child exits while a 16MB stdin write is still buffered — end_from_js's own flush() sees the write error first and threw it synchronously, leaving the backpressured write()'s promise outstanding. The auto-flush/error path then rejected that promise as well, and a caller that discarded write()'s return value (as spawn.test.ts's 'stdin.end() rejects with EPIPE' does) got an unhandledRejection for a failure it had already caught from end(). Before #35278 the orphaned promise silently resolved as a full success, which is the lie that fix removed - this completes it by routing the error to exactly one place. end_from_js's Err arm now latches the error into the pending slot and returns the same promise (exactly like its Pending arm), so the failure is reported once, to whichever await is watching. The latch happens before writer.end(), whose teardown can re-enter on_error/run_pending synchronously. Verification: new filesink.test.ts regression (discarded backpressured write + closed reader + same-tick end()) fails on the unfixed build and passes with the fix; spawn.test.ts's EPIPE and FORCE_WAITER_THREAD cases reproduce deterministically with the release binary from main's failing CI build 78927 and pass with the fix; filesink, spawn-stdin, streaming stdin, and shell epipe suites all green. --- src/runtime/webcore/FileSink.rs | 25 ++++++++++++++++ test/js/bun/util/filesink.test.ts | 47 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index c5da0eeac865..cbc45719711c 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -1134,6 +1134,31 @@ impl FileSink { } WriteResult::Err(err) => { self.done.set(true); + if self.pending.get().state == streams::PendingState::Pending { + // A backpressured write() left its promise outstanding. + // Throwing here would report the failure to the caller and + // then let the auto-flush/error path reject that promise a + // second time — with nobody holding it when the caller + // discarded write()'s return value, that second delivery + // surfaces as an unhandledRejection. Deliver the error to + // the pending promise instead and hand the caller the same + // promise (exactly like the Pending arm), so the failure is + // reported once, to whichever await is watching. The latch + // and promise grab happen before `writer.end()`: its + // teardown can re-enter `on_error`/`run_pending` + // synchronously, and the slot must already hold the error + // and this caller's promise when that runs. + self.pending + .with_mut(|p| p.result = streams::Writable::Err(err)); + // SAFETY: JsCell — `WritablePending::promise` allocates a + // JSPromise (may GC) but does not invoke any FileSink + // host-fn synchronously. + let promise_result = unsafe { self.pending.get_mut() }.promise(global_this); + self.writer.with_mut(|w| w.end()); + self.run_pending_later(); + // SAFETY: `WritablePending::promise()` never returns null. + return sys::Result::Ok(unsafe { (*promise_result).to_js() }); + } self.writer.with_mut(|w| w.end()); sys::Result::Err(err) } diff --git a/test/js/bun/util/filesink.test.ts b/test/js/bun/util/filesink.test.ts index d4d98fbec2f3..73ba5ad3ab7f 100644 --- a/test/js/bun/util/filesink.test.ts +++ b/test/js/bun/util/filesink.test.ts @@ -273,6 +273,53 @@ it.skipIf(!isPosix)("a backpressured string write() resolves to its encoded byte expect(received).toBe(size); }); +// end() called after a backpressured write() whose promise the caller +// discarded, with the reader already gone: end_from_js's flush() sees EPIPE +// synchronously. Throwing it would report the failure to end()'s caller and +// then let the auto-flush/error path reject the orphaned write() promise as an +// unhandledRejection; instead the error is delivered to that pending promise +// and end() returns the same promise, so the failure is reported exactly once. +it.skipIf(!isPosix)( + "end() after a discarded backpressured write() delivers EPIPE once, with no unhandled rejection", + async () => { + const [readFd, writeFd] = createSocketPair(); + let readFdOpen = true; + const sink = Bun.file(writeFd).writer(); + let unhandled: any = null; + function onUnhandled(e: unknown) { + unhandled = e; + } + process.on("unhandledRejection", onUnhandled); + try { + // Discarded on purpose: the write's promise must not surface on its own. + sink.write(Buffer.alloc(4 * 1024 * 1024, 0x61)); + fs.closeSync(readFd); + readFdOpen = false; + + let caught: any; + try { + await sink.end(); + } catch (e) { + caught = e; + } + expect(caught?.code).toBe("EPIPE"); + + // Bounded window for a stray second rejection to surface. + for (let i = 0; i < 10; i++) await Bun.sleep(1); + expect(unhandled).toBeNull(); + } finally { + process.off("unhandledRejection", onUnhandled); + try { + await sink.end(); + } catch {} + try { + fs.closeSync(writeFd); + } catch {} + if (readFdOpen) fs.closeSync(readFd); + } + }, +); + // The deferred auto-flush microtask runs at the first microtask checkpoint // after write() backpressures. If its flush() hit EPIPE, it discarded the // error and then let `run_pending_later()` resolve the pending write() promise From 6cff521e14ae6d052faee1dd49f51b1afbb12f1e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 24 Jul 2026 01:36:40 +0000 Subject: [PATCH 2/2] test: assert end() returns the pending write() promise directly The previous test's unhandledRejection check never fired in the socketpair scenario (the orphaned promise simply hangs there; the unhandled rejection only happens via on_attached_process_exit in the spawn path), so fail-before was a 5s timeout on the second sink.end() in finally. Assert the actual invariant the fix establishes instead: end() returns the same Promise object write() did, and it rejects with EPIPE. Fails fast on main with a clear EPIPE throw at the sink.end() call site, passes with the fix, and no process-global listener needed. --- test/js/bun/util/filesink.test.ts | 42 +++++++++++++++---------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/test/js/bun/util/filesink.test.ts b/test/js/bun/util/filesink.test.ts index 73ba5ad3ab7f..72da12167a4f 100644 --- a/test/js/bun/util/filesink.test.ts +++ b/test/js/bun/util/filesink.test.ts @@ -273,45 +273,43 @@ it.skipIf(!isPosix)("a backpressured string write() resolves to its encoded byte expect(received).toBe(size); }); -// end() called after a backpressured write() whose promise the caller -// discarded, with the reader already gone: end_from_js's flush() sees EPIPE -// synchronously. Throwing it would report the failure to end()'s caller and -// then let the auto-flush/error path reject the orphaned write() promise as an -// unhandledRejection; instead the error is delivered to that pending promise -// and end() returns the same promise, so the failure is reported exactly once. +// end() called after a backpressured write() with the reader already gone: +// end_from_js's own flush() sees EPIPE synchronously. Throwing it would leave +// the write()'s outstanding promise orphaned (never settled here; in the spawn +// path on_attached_process_exit rejected it a second time as an unhandled +// rejection). Instead end() latches the error into that pending promise and +// returns it, so write()'s promise and end()'s return are the same object and +// the failure is reported exactly once. it.skipIf(!isPosix)( - "end() after a discarded backpressured write() delivers EPIPE once, with no unhandled rejection", + "end() after a backpressured write() with the reader gone returns the write's promise, rejecting with EPIPE", async () => { const [readFd, writeFd] = createSocketPair(); let readFdOpen = true; const sink = Bun.file(writeFd).writer(); - let unhandled: any = null; - function onUnhandled(e: unknown) { - unhandled = e; - } - process.on("unhandledRejection", onUnhandled); try { - // Discarded on purpose: the write's promise must not surface on its own. - sink.write(Buffer.alloc(4 * 1024 * 1024, 0x61)); + const writePromise = sink.write(Buffer.alloc(4 * 1024 * 1024, 0x61)); + expect(writePromise).toBeInstanceOf(Promise); + fs.closeSync(readFd); readFdOpen = false; + // end()'s flush() hits EPIPE synchronously. It must not throw and strand + // writePromise; it hands back the same promise with the error latched. + const endResult = sink.end(); + expect(endResult).toBe(writePromise); + let caught: any; try { - await sink.end(); + await endResult; } catch (e) { caught = e; } expect(caught?.code).toBe("EPIPE"); - // Bounded window for a stray second rejection to surface. - for (let i = 0; i < 10; i++) await Bun.sleep(1); - expect(unhandled).toBeNull(); + // The pending slot is now settled; a follow-up end() short-circuits to + // the written byte count, not another promise. + expect(typeof sink.end()).toBe("number"); } finally { - process.off("unhandledRejection", onUnhandled); - try { - await sink.end(); - } catch {} try { fs.closeSync(writeFd); } catch {}