Skip to content

FileSink: keep the sink alive until on_close returns - #43761

Merged
Jarred-Sumner merged 5 commits into
mainfrom
robobun/da231342/filesink-on-close-owner-ref
Sep 29, 2026
Merged

Jarred-Sumner merged 5 commits into
mainfrom
robobun/da231342/filesink-on-close-owner-ref

Conversation

@robobun

@robobun robobun commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • On Windows, a worker can use the stdin FileSink of a Bun.spawn child after it is freed. It needs stdin: "pipe", a live child, and a script that never read proc.stdin. Debug build: panic: misaligned pointer dereference: address must be a multiple of 0x8 but is 0xdfdfdfdfdfdf. A release build reads freed memory silently.
  • FileSink::on_close (src/runtime/webcore/FileSink.rs:528) calls source.close(). That reaches Writable::on_close (src/runtime/api/bun/subprocess/Writable.rs:114), which drops the only ref on the sink. on_close then continues on freed memory.

Fix

  • FileSink::on_close holds a ref on the sink until it returns. on_write and run_pending already use this guard.
  • A testing hook, subprocessInternals.closeStdinWriter(proc), does the same close as the Windows stop phase, on every platform.
  • Verified with the hook, in test/js/bun/util/filesink.test.ts. Without the guard, the Linux ASAN build reports heap-use-after-free in settle_stream_done, and a Windows debug build panics. With the guard both pass. The worker test in test/js/web/workers/worker-terminate-lifetime.test.ts can fail only on a Windows debug build.
  • Self-reviewed: 3 concerns raised, 2 addressed (see Notes).

Background

Downsides

  • None found for the guard. on_close never runs while the sink is destroyed, so the guard never takes a ref from zero.
  • Still open: the stream-fed stdin leak in the Notes.
Notes

Repro (windows-x64, debug build, 5 of 5 runs on main at b7ea95a):

import { Worker } from "node:worker_threads";
const w = new Worker(`
  const { parentPort } = require("node:worker_threads");
  globalThis.keep = Bun.spawn({ cmd: [process.execPath, "-e", "setTimeout(() => {}, 4000)"], stdin: "pipe", stdout: "ignore", stderr: "ignore" });
  setTimeout(() => parentPort.postMessage("go"), 300);
`, { eval: true });
await new Promise(r => w.once("message", r));
await w.terminate();
console.log("survived");

Symbolized stack (llvm-symbolizer with the PDB, ASLR off, line numbers at b7ea95a):

bun_jsc::strong::Impl::get                                   src/jsc/Strong.rs:179
bun_jsc::strong::Optional::get                               src/jsc/Strong.rs:92
webcore::streams::PipeCell::take_done                        src/runtime/webcore/streams.rs:908
FileSink::settle_stream_done                                 src/runtime/webcore/FileSink.rs:552
FileSink::on_close                                           src/runtime/webcore/FileSink.rs:530
<FileSink as WindowsStreamingWriterParent>::on_close         src/io/PipeWriter.rs:2734
WindowsStreamingWriter<FileSink>::on_close_source            src/io/PipeWriter.rs:2010
WindowsStreamingWriter<FileSink>::close                      src/io/PipeWriter.rs:1212
WindowsStreamingWriter<FileSink>::stop_for_vm_teardown       src/io/PipeWriter.rs:1130
open_handles::stop_all_for_vm_teardown                       src/libuv_sys/open_handles.rs:172
VirtualMachine::stop_phase_sweep                             src/jsc/VirtualMachine.rs:2554
VirtualMachine::teardown                                     src/jsc/VirtualMachine.rs:2401
WebWorker::shutdown / spin / thread_main                     src/jsc/web_worker.rs

The address matches. Strong::get masks the handle to 48 bits, and 0xdfdfdfdfdfdfdfdf & ((1 << 48) - 1) is 0xdfdfdfdfdfdf. 0xdf is the fill that a debug mimalloc writes into a freed block.

Linux ASAN report (debug ASAN build with the hook and without the guard, from the new test in filesink.test.ts):

ERROR: AddressSanitizer: heap-use-after-free ... READ of size 8
    #0 bun_jsc::strong::Optional::get                  src/jsc/Strong.rs:91
    #1 webcore::streams::PipeCell::take_done           src/runtime/webcore/streams.rs:908
    #2 FileSink::settle_stream_done                    src/runtime/webcore/FileSink.rs
    #3 FileSink::on_close                              src/runtime/webcore/FileSink.rs
    #5 PosixStreamingWriter<FileSink>::close           src/io/PipeWriter.rs:1048
    #7 PollOrFd::close_impl                            src/io/pipes.rs:118
   #10 testing_apis::close_stdin_writer                src/runtime/api/bun/subprocess.rs
freed by thread T0 here:
   #12 <FileSink as CellRefCounted>::destroy           src/ptr/ref_count.rs:448
   #15 <RefPtr<FileSink> as Drop>::drop                src/ptr/ref_count.rs:522
   #19 JsCell<Writable>::set                           src/ptr/js_cell.rs:94
   #20 Writable::on_close                              src/runtime/api/bun/subprocess/Writable.rs:114
   #22 SourceHandle::close                             src/runtime/webcore/streams.rs:1043
   #23 FileSink::on_close                              src/runtime/webcore/FileSink.rs

The use and the free are in the same FileSink::on_close call. For this proof I removed only the guard line and kept the hook. With the src/ of main the new filesink.test.ts test also fails, but for a weaker reason: the hook does not exist there.

Why only this path. Every other path that closes this sink keeps it alive or detaches the source first:

  • Subprocess::on_process_exit clears source before on_attached_process_exit, which also holds a ref.
  • Writable::finalize and on_close_io clear source before they drop the ref.
  • The proc.stdin getter takes the pipe out of the stdin slot and clears source, so Writable::on_close is not reached.
  • POSIX has no stop-phase close of the pipe. The sink dies in Subprocess::finalize. A poll HUP with an empty buffer reports Drained, not a close.

Variants (windows-x64 debug, before and after the fix):

worker ends by stdin before after
terminate() "pipe", never read panic ok
process.exit() in the worker "pipe", never read panic ok
loop drains (proc.unref()) "pipe", never read panic ok
terminate(), stdout: "pipe" too "pipe", never read panic ok
terminate() "pipe", proc.stdin.write() pending ok ok
no worker, closeStdinWriter(proc) hook "pipe", never read panic ok

After the fix, fileSinkInternals.liveCount() is back at the baseline after the exit event of the worker in each row.

Suites run with the fix.

  • windows-x64 debug: worker-terminate-lifetime.test.ts (24 pass, 2 skip), worker_destruction.test.ts (5 pass), spawn.test.ts (126 pass), spawn-stdin-readable-stream.test.ts (36 pass), spawn-stdin-destroy.test.ts, spawn-stdin-pipe-fd-leak.test.ts, child_process.test.ts (53 pass), filesink.test.ts (33 pass, 1 fail, see below). The hook test passes 5 of 5 runs and the worker test 3 of 3.
  • linux-x64 debug ASAN: both new tests, filesink.test.ts (70 pass), spawn-stdin-readable-stream.test.ts (37 pass), spawn-stdin-destroy.test.ts, worker_destruction.test.ts (5 pass with --timeout 120000).

Self-review.

  • Addressed: no CI lane could fail the worker test. The Windows lanes run release builds, where the stale reads do not crash, and Linux does not reach the path. The hook test now fails on an ASAN build of any platform without the guard. The worker test stays, because it is the real trigger, and its comment says which build can fail it.
  • Addressed: the comment before clear_keep_alive_ref said that call can free the sink. With the guard it cannot, so the sentence is gone.
  • Not changed: the sink keeps its stale source after the owner is told. Nothing reads it again on this path, because a later write needs the JS wrapper, and the getter that creates the wrapper clears source.
  • Checked and fine: no caller of on_close touches the writer or the sink after the call returns (on_close_source, the tail of close, stop_all_for_vm_teardown, and PollOrFd::close on POSIX, where the callback is last). Both writer Drop impls close without a report, so on_close never runs while the sink is destroyed.

Not in this PR. On Windows, a worker that ends while Bun.spawn({ stdin: new ReadableStream({ pull(c) { c.enqueue(new Uint8Array(1024)); return new Promise(() => {}); } }) }) still pumps leaves one FileSink alive. liveCount() stays at +1, before and after this change. Linux returns to the baseline. The cause is different: the ref that assign_to_js_stream takes for the reactions of the pump promise is not released, because the reactions never run after script is forbidden. #43729 adds a flag that tracks that ref.

Local failures that this diff does not cause.

  • windows-x64 (Server 2019): test/js/bun/util/filesink.test.ts "Bun.spawn stdin pipe with an unref'd child" fails 3 of 3 runs with the src/ of main, with this fix, and with the release canary.
  • linux-x64 debug ASAN in my container: "terminate() while dns.lookup() is in flight" in the same test file reports a 16 byte LeakSanitizer leak from node_fs_binding::Binding::new. No FileSink is involved.

no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/workers/worker-terminate-lifetime.test.ts, test/js/bun/util/filesink.test.ts

`FileSink::on_close` calls `source.close()`. For a `Bun.spawn` child with
`stdin: "pipe"`, that call reaches `Writable::on_close`, which drops the
Subprocess's ref on the sink. When script never read `.stdin`, that ref is
the only one. The sink was freed while `on_close` still used it.

On Windows, the stop phase of a worker closes the stdin pipe in that
state. A debug build panics in `settle_stream_done`:
"misaligned pointer dereference: address must be a multiple of 0x8 but
is 0xdfdfdfdfdfdf".

Hold a ref for the length of `on_close`, as `on_write` and `run_pending`
do.
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: oven-sh/bun/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 24c065f4-727b-41d1-bb82-602461116eae

📥 Commits

Reviewing files that changed from the base of the PR and between f5bb689 and ee22607.

📒 Files selected for processing (5)
  • src/js/internal-for-testing.ts
  • src/runtime/api/bun/subprocess.rs
  • src/runtime/webcore/FileSink.rs
  • test/js/bun/util/filesink.test.ts
  • test/js/web/workers/worker-terminate-lifetime.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.


Walkthrough

The change adds a subprocess testing API to close pipe-backed stdin writers, protects FileSink during close re-entrancy, and adds subprocess and worker-termination regression tests.

Changes

Subprocess stdin lifetime

Layer / File(s) Summary
Expose subprocess stdin writer closure
src/js/internal-for-testing.ts, src/runtime/api/bun/subprocess.rs
subprocessInternals.closeStdinWriter validates a Bun.Subprocess, closes its pipe-backed stdin writer, and returns a boolean.
Guard FileSink closure lifetime
src/runtime/webcore/FileSink.rs
FileSink::on_close holds a temporary reference during operations that can release the last sink reference.
Add regression coverage
test/js/bun/util/filesink.test.ts, test/js/web/workers/worker-terminate-lifetime.test.ts
Tests cover unread stdin closure and worker termination with a live child process and pipe-backed stdin.

Suggested reviewers: jarred-sumner

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to ee226

This change prevents freed-memory access during subprocess stdin closure and adds regression coverage; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: keeping the FileSink alive until on_close returns.
Description check ✅ Passed The description thoroughly explains the problem, fix, testing, regression coverage, known limitations, and local failures. It does not use the exact template headings, but it provides the required inf…

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review.

How I reproduced it.

  • Windows: on a windows-x64 debug build of main (b7ea95a), the script in the Notes of the PR body panics 5 of 5 runs with misaligned pointer dereference: address must be a multiple of 0x8 but is 0xdfdfdfdfdfdf. The worker test in test/js/web/workers/worker-terminate-lifetime.test.ts fails 5 of 5 runs there before the fix and passes after.
  • Every platform: the new test in test/js/bun/util/filesink.test.ts closes the stdin writer through the subprocessInternals.closeStdinWriter hook. With the hook and without the guard, the Linux debug ASAN build reports heap-use-after-free in FileSink::settle_stream_done, freed in Writable::on_close, and a Windows debug build panics as above. With the guard the test passes on both.

A Windows release build does not crash on the stale reads, and no other platform closes the pipe in the stop phase. So the worker test can fail only on a Windows debug build.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline note, I also checked the refcount balance of the new guard: clear_keep_alive_ref releases a separately-flagged ref, so the guard's drop at scope end is the only remaining release and stays balanced; on_close cannot run at refcount zero because both writer Drop impls go through close_without_reporting(), so init_ref never resurrects a dead sink; and the callers of the Windows close()/on_close_source path do not touch the writer after the callback returns, so moving the final free to the end of on_close does not expose a freed writer to them.

Extended reasoning...

The change adds a one-line self-keepalive guard to FileSink::on_close in src/runtime/webcore/FileSink.rs, matching the pattern already used at four sibling callbacks in the same file, and adds a subprocess-spawning test in test/js/web/workers/worker-terminate-lifetime.test.ts. It touches no security-sensitive surface. It is small and consistent with local conventions, but it is unsafe refcount lifetime code and the regression test can only fail on Windows debug builds, which CI does not run, so a human familiar with the FileSink/Subprocess ownership model should still glance at it.

Only the stop phase of a Windows worker closes a child's stdin writer
while the Subprocess holds the only ref on the sink. A Windows release
build reads the freed sink silently, so no CI lane could fail the worker
test.

`subprocessInternals.closeStdinWriter(proc)` does the same native close
on any platform. Without the guard in `FileSink::on_close`, ASAN reports
a heap-use-after-free in `settle_stream_done`, and a Windows debug build
panics as before.
Comment thread src/js/internal-for-testing.ts Resolved
Comment thread src/runtime/api/bun/subprocess.rs Resolved
Comment thread src/runtime/webcore/FileSink.rs Resolved
@robobun

robobun commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:28 AM PT - Sep 22nd, 2026

✅ @robobun, your commit ee22607d3df1c3c3f70549a13277ce48bc9a0d5c passed in Build #119623! 🎉


🧪   To try this PR locally:

bunx bun-pr 43761

That installs a local version of the PR into your bun-43761 executable, so you can run:

bun-43761 --bun

Comment thread src/runtime/api/bun/subprocess.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

The new closeStdinWriter hook and the filesink.test.ts case address the earlier concern that the guard had no CI-reachable coverage: on POSIX, PosixStreamingWriter::close -> PollOrFd::close_impl runs FileSink::on_close synchronously with the callback as its last action, so the Linux ASAN lane now exercises the src.close(err) -> Writable::on_close -> last-deref path. Beyond the inline nit, I also checked that the guard never takes a ref from zero (both writer Drop paths go through close_without_reporting, and on_close is not reached from FileSink::drop), and that no caller of on_close touches the writer or sink after it returns. Since this is a refcount change in native FileSink teardown, a human look is still worthwhile.

Extended reasoning...

The production change is three lines in src/runtime/webcore/FileSink.rs (a RefPtr::init_ref guard in on_close, mirroring on_write/run_pending) plus a bun:internal-for-testing hook in the testing_apis module of src/runtime/api/bun/subprocess.rs and two tests; no security-sensitive surface. Since the prior review, commits b84c261 and 4d47caa added the hook-driven test that makes the UAF reproducible on every platform, which was the point raised earlier. Deferring rather than approving because it is a refcount-lifetime change in native teardown code, the most-blocked category, and the Windows #[cfg] trait import cannot be type-checked here.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — the guard mirrors the existing RefPtr::init_ref(this) pattern in on_write/run_pending/on_attached_process_exit, and both points from my earlier reviews are addressed by b84c261 and ee22607.

What was reviewed:

  • Guard lifetime in FileSink::on_close (src/runtime/webcore/FileSink.rs:515): _guard is declared inside the unsafe block, so it drops after clear_keep_alive_ref and may perform the final free; nothing reads this after that.
  • Ref-from-zero risk: the writer Drop paths on both platforms (close_without_reporting) skip Parent::on_close (POSIX passes no callback; Windows on_close_source early-returns), so init_ref never runs on a destroyed sink.
  • Writer close() after on_close may free the parent: POSIX close_impl touches nothing after the callback; Windows only derefs via parent_ptr() when an inflight File write holds its own ref — not new to this PR.
  • Testing hook (close_stdin_writer): Subprocess stays owned by the JS wrapper across the call, the &Writable borrow ends at as_ptr(), and the Windows trait import path resolves to src/io/PipeWriter.rs:1111.
Extended reasoning...

The change adds a one-line RefPtr keep-alive guard at the top of FileSink::on_close, adjusts two doc comments, adds a test-only host_fn in subprocess.rs (exposed through bun:internal-for-testing) that closes the stdin writer the way a Windows worker's stop phase does, and adds two subprocess tests. It touches no security-sensitive surface (no auth, crypto, parsing of untrusted data); the unsafe code follows the pattern already used three times in the same file. The decision to approve rests on the small, self-contained diff, verification that the guard cannot ref from zero via the Drop paths, no CODEOWNER on the changed files, and that both of my prior inline comments were addressed by later commits.

@Jarred-Sumner
Jarred-Sumner merged commit 3df1dda into main Sep 29, 2026
10 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the robobun/da231342/filesink-on-close-owner-ref branch September 29, 2026 22:06
Jarred-Sumner pushed a commit that referenced this pull request Sep 30, 2026
…allback (#44250)

### Problem
- With nothing else alive, a JS stream piped into a `FileSink` on a pipe
stops at the first full drain. Un-awaited `Bun.write(Bun.stdout, new
Response(stream))` delivers 4,194,304 of 8,388,608 bytes, exits with
code 0, and never settles.
- `FileSink::on_write` (`src/runtime/webcore/FileSink.rs:366`) ran its
microtask checkpoint before it resumed the pump. The run loop does not
count the microtask the pump queues. `on_close` had no checkpoint.

### Fix
- `completion_scope()` opens an event-loop scope while a stream is piped
in. Its exit is the checkpoint. `on_write` and `on_close` open it before
they enter JS.
- Correct because a callback from the loop owes a checkpoint for the JS
it enters.
- Verified: `test/js/bun/util/filesink.test.ts`, seven new tests, 0 of 7
on main. Each scope has a test that fails without it. Also 15 more Linux
suites.
- Self-reviewed: 6 concerns raised, 5 addressed as proposed, 1 otherwise
(Notes).

### Background
- The pump (`readStreamIntoSink`) feeds the sink from a JS stream and
waits for `ready()` after a short write. A microtask checkpoint runs
queued promise reactions.
- Considered a drain in the run loop after each poll callback: every
loop turn pays. A scope around every `FileSink` poll callback charges
plain writers too.

### Downsides
- A sink written from script pays 7 more instructions per `on_write` and
per `on_close`. `.text` grows by 256 bytes.
- An un-awaited `Bun.write` whose stream fails now exits with code 1.
Main exits 0 in 9 of 10 runs.
- After `proc.unref()`, a stream stdin that can always produce now
arrives in full. Main cuts it.

<details><summary>Notes</summary>

All numbers are from release builds of main ad60a9b and of this
branch at 028985b on Linux x64, unless a line says debug.

**Repro** (no `beforeExit` listener, no timer, no top-level await):

```js
// bun repro.mjs | (sleep 0.4; wc -c)      expected 8388608, main prints 4194304
const first = new Uint8Array(4 * 1024 * 1024).fill(97);
const chunk = new Uint8Array(64 * 1024).fill(98);
let pulls = 0;
Bun.write(Bun.stdout, new Response(new ReadableStream({
  pull(c) {
    if (++pulls === 1) return c.enqueue(first);
    if (pulls <= 65) return c.enqueue(chunk);
    c.close();
  },
})));
```

**Why main loses the step.** The run loop is `while
vm.is_event_loop_alive() { vm.tick(); vm.auto_tick_active(); }`
(`src/runtime/cli/run_command.rs`). `auto_tick_active` runs the poll
callback. `on_write` drops the loop ref of the poll because the buffer
is empty, and `src.ready()` makes the pump read the next chunk. The
chunk steps, close steps and error steps of that read are queued with
`queueReactionJob`
(`src/jsc/bindings/webcore/streams/JSReadRequest.cpp`). The callback
returns, nothing is alive, and the loop ends before the next `tick()`.
One ref'd timer gives the loop another turn and hides the bug.

**The fix itself**, 20 runs per shape. A run counts when every byte
arrived and the reaction of the promise ran.

| Shape | main | this branch |
| --- | --- | --- |
| chunks arrive after the pump parked, to a piped stdout | 0 of 20 | 20
of 20 |
| the same into a FIFO | 0 of 20 | 20 of 20 |
| stream closes while the pump is parked | 2 of 20 | 20 of 20 |
| stream fails while the pump is parked | 1 of 20 | 20 of 20 |
| direct stream, closed with bytes still buffered | 0 of 20 | 20 of 20 |
| small chunk, sink ended against a full socket | 0 of 20 | 20 of 20 |
| direct stream that awaits each `flush()` (control) | 20 of 20 | 20 of
20 |

**Each scope is needed** (debug+ASAN builds, the seven new tests):

| Build | Failing tests |
| --- | --- |
| main | 7 |
| this branch | 0 |
| this branch without the scope in `on_write` | 5: chunks to stdout,
chunks to FIFO, `beforeExit` count, close, error |
| this branch without the scope in `on_close` | 1: sink closed with no
source parked |

**Microtask checkpoints and `enter()` calls per callback**, from debug
logs (`BUN_DEBUG_ALL=1`), constant over 3 runs. The column for main is
from a debug build of 1313ca6, where `FileSink.rs` is the same file
as on ad60a9b.

| Callback | main | this branch |
| --- | --- | --- |
| drain that resumes the pump | 1 checkpoint, 1 `enter()` | 1
checkpoint, 2 `enter()` |
| drain that leaves bytes in the buffer | 0, 0 | 0, 0 |
| close, a source had parked | 1, 1 | 1, 3 |
| close, no source parked | 1, 1 | 2, 2 |
| sink written from script, drain or close | 1, 1 | 1, 1 |

On main the one checkpoint of a drain runs before the pump is resumed.
On this branch it runs after.

**`beforeExit` emissions** for the 8 MiB pump with a listener installed,
10 runs: main 1 to 21, this branch 1 in 10 of 10, Node v26.3.0 1 in 10
of 10.

**Cost for a sink written from script.** One `on_write(65536, Drained)`
call: 46 instructions on main, 53 on this branch, no `call` instruction
in either. One `on_close` call: 28 and 35, 2 `call` instructions in
both. Counted with gdb `nexti` on release builds with symbols, identical
over 8 calls. Binary size with `size`: `.text` 80,667,862 to 80,668,118,
`data` and `bss` equal, the file keeps its size of 80,836,168 bytes.
`on_write` grows from 1,302 to 1,530 bytes and `on_close` from 1,860 to
1,983.

**Not measured:** `write(2)` calls that return `EAGAIN` per drain.
`strace`, `perf` and `valgrind` are not installed where I measured, and
under gdb `catch syscall` the writer is so slow that the pipe never
fills.

**A stream that fails with no handler**, 10 runs. Main: exit code 0 and
nothing on stderr in 9 runs, `error: boom` and exit code 1 in 1 run.
This branch: `error: boom` and exit code 1 in 10 runs. The same stream
awaited at top level gives `error: boom` and exit code 1 on both builds.

**`proc.unref()` and a stream stdin**, 10 runs per cell. The child
starts to read only after the pump has taken the first chunk.

| Stream | main | this branch |
| --- | --- | --- |
| can always produce | 4,194,304 of 8,388,608 | 8,388,608 |
| all data queued and closed before the spawn | 219,264 in 9 of 10 runs
| 219,264 in 9 of 10 runs |
| produces one chunk, then waits on a promise that never settles |
4,194,304, parent exits | 4,194,304, parent exits |
| can always produce, no `unref()` | 8,388,608 | 8,388,608 |

This change does not touch `Writable::unref`, which clears the loop ref
of the stdin writer also while it holds accepted bytes (second row).
What `unref()` must mean for a writer that owes bytes is a decision for
a maintainer and relates to #33533. No test here uses `unref()`.

**Sites that this change leaves alone, and why.**

| Site | Reason |
| --- | --- |
| `on_ready` | The POSIX writer never calls it. It is the `on_writable`
slot on Windows, where the unfixed build has no failing case. |
| `EndOfFile` arm of `on_write` | No test reaches it with a piped stream
on POSIX. |
| Windows settle for a borrowed fd, in `end_writer` and in the abort
handler | No failing case on Windows. #42819 rewrites that code. |
| `on_auto_flush` | It runs inside the deferred task queue, where
`EventLoop::exit()` does not drain. The task that `run_pending_later`
queues just before the resume keeps the loop alive for the next
`tick()`. |
| Other sinks and other poll owners | Not examined here. |

**Other PRs that touch the same lines.**

- #43761 added a ref guard at the top of `on_close` and merged while
this PR was open. This branch contains it: guard first, scope second.
Its stdin test passes and the tests here pass.
- #42032 adds a checkpoint after the `beforeExit` dispatch. On unfixed
code with that hunk, six of the seven tests pass, because the loop
passes through that dispatch after each drain. The seventh fails:
`beforeExit` fires more than once for one stream (8 times in my run).
With this change and that hunk together all seven pass.

**Self-review.** Concerns raised and what I did:

1. A ref guard in `on_close` repeated #43761 without its tests. The
proposal was to stack this PR on #43761. I removed the guard and did not
stack: the scope does not read the sink when it ends, so it does not
need the guard. #43761 has merged since.
2. A `cfg(windows)` scope in `end_writer` had no failing test and sits
in code that #42819 rewrites. Removed.
3. A scope and a guard in `on_ready`, and an `EndOfFile` clause in
`on_write`, had no failing test. Removed.
4. A gate on `VM::is_entered()` had no failing test. I built the change
without the gate and ran a script that closes the sink inside the
`Bun.write` call with a microtask already queued. The order of the
microtask did not change, because a script frame already runs inside an
entered scope. Removed.
5. The predicate also matched a `stdin: "pipe"` sink that script never
read, and shell pipes. It now tests only for a piped stream.
6. The tests would pass on unfixed code once #42032 lands. Added the
test that counts `beforeExit`.

**Platforms.** On Windows Server 2019 x64 a debug build of main passes
every portable shape, also with a first chunk of 64 MiB and of 256 MiB
where the child waits 0.6 to 2.3 s for the reader. So on Windows the
five portable tests guard against a regression only. The first revision
of the FIFO test read its end with `Bun.file(fd).bytes()`. On macOS that
read never finished, 8 of 8 attempts, although the child had exited. The
test now reads with `read(2)` in a poll with a deadline, and passes on
macOS.

**Suites** on the debug build of this branch, 60 s per test, all pass:
`filesink` (77 after the merge with main), `bun-write` (86),
`spawn-stdin-readable-stream` (4 files, 55), `spawn-streaming-stdin`,
`spawn-stdin-destroy`, `spawn-stdin-pipe-fd-leak`,
`readablestream-helpers`, `streams` (624), `compression`,
`sync-pull-fast-path`, `native-source-onclose-leak`,
`direct-readable-stream`, `bunshell` (436).

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 4 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/bun/util/filesink.test.ts

<!-- robobun:evidence:end -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants