Repository navigation
FileSink: keep the sink alive until on_close returns - #43761
Conversation
`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.
|
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 configurationConfiguration used: Repository: oven-sh/bun/.coderabbit.yaml Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (5)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. WalkthroughThe change adds a subprocess testing API to close pipe-backed stdin writers, protects ChangesSubprocess stdin lifetime
Suggested reviewers: Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to 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)
Comment |
|
Status: ready for review. How I reproduced it.
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. |
There was a problem hiding this comment.
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.
|
Updated 12:28 AM PT - Sep 22nd, 2026
✅ @robobun, your commit ee22607d3df1c3c3f70549a13277ce48bc9a0d5c passed in 🧪 To try this PR locally: bunx bun-pr 43761That installs a local version of the PR into your bun-43761 --bun |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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):_guardis declared inside the unsafe block, so it drops afterclear_keep_alive_refand may perform the final free; nothing readsthisafter that. - Ref-from-zero risk: the writer
Droppaths on both platforms (close_without_reporting) skipParent::on_close(POSIX passes no callback; Windowson_close_sourceearly-returns), soinit_refnever runs on a destroyed sink. - Writer
close()afteron_closemay free the parent: POSIXclose_impltouches nothing after the callback; Windows only derefs viaparent_ptr()when an inflight File write holds its own ref — not new to this PR. - Testing hook (
close_stdin_writer):Subprocessstays owned by the JS wrapper across the call, the&Writableborrow ends atas_ptr(), and the Windows trait import path resolves tosrc/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.
…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 -->
Problem
FileSinkof aBun.spawnchild after it is freed. It needsstdin: "pipe", a live child, and a script that never readproc.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) callssource.close(). That reachesWritable::on_close(src/runtime/api/bun/subprocess/Writable.rs:114), which drops the only ref on the sink.on_closethen continues on freed memory.Fix
FileSink::on_closeholds a ref on the sink until it returns.on_writeandrun_pendingalready use this guard.subprocessInternals.closeStdinWriter(proc), does the same close as the Windows stop phase, on every platform.test/js/bun/util/filesink.test.ts. Without the guard, the Linux ASAN build reportsheap-use-after-freeinsettle_stream_done, and a Windows debug build panics. With the guard both pass. The worker test intest/js/web/workers/worker-terminate-lifetime.test.tscan fail only on a Windows debug build.Background
FileSinkis a refcounted writer. Forstdin: "pipe"the Subprocess holds one ref. Theproc.stdingetter moves it to a JS wrapper.source.close()tells that owner that the sink closed, and the owner drops its ref.FileSink::on_close.Downsides
on_closenever runs while the sink is destroyed, so the guard never takes a ref from zero.Notes
Repro (windows-x64, debug build, 5 of 5 runs on main at b7ea95a):
Symbolized stack (llvm-symbolizer with the PDB, ASLR off, line numbers at b7ea95a):
The address matches.
Strong::getmasks the handle to 48 bits, and0xdfdfdfdfdfdfdfdf & ((1 << 48) - 1)is0xdfdfdfdfdfdf.0xdfis 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):The use and the free are in the same
FileSink::on_closecall. For this proof I removed only the guard line and kept the hook. With thesrc/of main the newfilesink.test.tstest 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_exitclearssourcebeforeon_attached_process_exit, which also holds a ref.Writable::finalizeandon_close_ioclearsourcebefore they drop the ref.proc.stdingetter takes the pipe out of thestdinslot and clearssource, soWritable::on_closeis not reached.Subprocess::finalize. A poll HUP with an empty buffer reportsDrained, not a close.Variants (windows-x64 debug, before and after the fix):
terminate()"pipe", never readprocess.exit()in the worker"pipe", never readproc.unref())"pipe", never readterminate(),stdout: "pipe"too"pipe", never readterminate()"pipe",proc.stdin.write()pendingcloseStdinWriter(proc)hook"pipe", never readAfter the fix,
fileSinkInternals.liveCount()is back at the baseline after theexitevent of the worker in each row.Suites run with the fix.
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.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.
clear_keep_alive_refsaid that call can free the sink. With the guard it cannot, so the sentence is gone.sourceafter 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 clearssource.on_closetouches the writer or the sink after the call returns (on_close_source, the tail ofclose,stop_all_for_vm_teardown, andPollOrFd::closeon POSIX, where the callback is last). Both writerDropimpls close without a report, soon_closenever 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 oneFileSinkalive.liveCount()stays at +1, before and after this change. Linux returns to the baseline. The cause is different: the ref thatassign_to_js_streamtakes 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.
test/js/bun/util/filesink.test.ts"Bun.spawn stdin pipe with an unref'd child" fails 3 of 3 runs with thesrc/of main, with this fix, and with the release canary.node_fs_binding::Binding::new. NoFileSinkis 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