Repository navigation
FileSink: flush buffered bytes when process.exit() runs in the same tick as write() - #36250
Conversation
|
Status: reproduced on stock 1.4.0-canary and main ( CI at e965c56 (build 84377): |
|
Warning Review limit reached
Next review available in: 4 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
Comment |
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🔴
src/jsc/VirtualMachine.rs:1495-1497— This drain runs unconditionally, so ifprocess.exit()is called from user JS reached inside an auto-flush callback (e.g.H2FrameParser::on_auto_flush→handler.close()→ JS'close'handler, orHTTPServerWritable::on_auto_flush→signal.close()),on_exit()re-entersdeferred_tasks.run()while the outerrun()still holds&mut DeferredTaskQueue— Rust&mutaliasing UB via the raw-ptrevent_loop_mut(), and the innerrun()re-invokes the currently-executing callback (double-deref()of the registration ref for h2/NodeHTTPResponse). Every other call site guards on!is_inside_deferred_task_queue.get()(event_loop.rs:256/283/362); this one should too — save the prior flag and only run when it was false.Extended reasoning...
What the bug is
The new drain at
VirtualMachine.rs:1495-1497unconditionally setsis_inside_deferred_task_queue = trueand callsself.event_loop_mut().deferred_tasks.run(). It does not check whetheris_inside_deferred_task_queuewas already true — i.e. whether we are already insideDeferredTaskQueue::run()on this stack. Every other path intodeferred_tasks.run()guards on exactly that flag (event_loop.rs:256,283,362); this new site does not, so it can re-enterrun()while the outerrun()still has a live&mut DeferredTaskQueue.The code path that triggers it
Several
AutoFlushercallbacks synchronously reach user JS. Concretely:H2FrameParser::on_auto_flush(h2_frame_parser.rs:3251-3275) on thetransport_write_fatalarm callsself.deref()(releasing the registration ref) thenclose_transport_after_fatal_write()→handler.close(). Its own doc comment at :3222-3226 says this triggers "native callback detach, JS close, session destroy", and the comment at :3254-3259 explicitly documents avoiding "re-entrant map mutation from inside run()".HTTPServerWritable::on_auto_flush(streams.rs:1878-1880) callssignal.close(None)andflush_promise(); the comment at streams.rs:1820-1822 documents "the close fires the JS onClose callback".NodeHTTPResponse::on_auto_flush(:2305-2316) doesself.deref()and returnsfalse.
If the JS reached from one of these calls
process.exit(), we goBun__Process__exit→vm.on_exit()→ the new drain — while still inside the outerdeferred_tasks.run().Why existing code doesn't prevent it
on_exit()has no re-entry guard around the new drain: the CPU/heap profilers use.take(),dispatch_on_exitis gated bym_isExiting, but nothing checks the deferred-queue flag.event_loop_mut()(VirtualMachine.rs:741-745) returns&mut EventLoopviaunsafe { &mut *raw_ptr }, so borrowck cannot see the aliasing. AndDeferredTaskQueue::run()(DeferredTaskQueue.rs:65-96) invokestask(nn.as_ptr())at line 89 beforeswap_removeat line 90, so a nestedrun()starting from index 0 will find the currently-executing entry still in the map and re-invoke it.Before this PR,
on_exit()had nodeferred_tasks.run()call at all —process.exit()from inside an auto-flush callback went straight throughdispatch_on_exit→ cleanup hooks →global_exit()without a secondrun(). This re-entrancy is newly introduced.Impact
Two concrete failure modes during the inner
run():&mutaliasing UB. The outerrun()holds&mut self: DeferredTaskQueuelive across thetask()call; the innerrun()forms a second&mut DeferredTaskQueueto the same object via the raw-ptrevent_loop_mut(). This violates Rust'snoaliason the outer receiver — release-build UB per REVIEW.md's "benign same-value races are still UB" / provenance rules insrc/CLAUDE.md.- Double-invocation of the mid-execution callback. The inner
run()re-iterates the map from index 0 and re-invokes the callback that is currently executing on the outer frame. ForH2FrameParserandNodeHTTPResponsethis callsself.deref()a second time on a registration ref that was already released — an unbalanced refcount on a terminal path (REVIEW.md: "Reference counts provably balanced on every terminal path"). For other flushers it double-flushes.
global_exit()isnoreturn, so the outerrun()never resumes and post-hoc map corruption isn't observed — but the aliasing and the double-invoked callbacks happen during the innerrun(), before exit.Step-by-step proof
drain_microtasks_with_global()at event_loop.rs:336-338 setsis_inside_deferred_task_queue = trueand callsself.deferred_tasks.run(). The outerrun()now holds&mut DeferredTaskQueue.run()reaches indexi= the H2FrameParser entry, copies outtask, and callstask(nn.as_ptr())(DeferredTaskQueue.rs:89). The entry is still in the map —swap_removeis line 90.H2FrameParser::on_auto_flushtakes thetransport_write_fatalarm:self.deref()(registration ref released), thenclose_transport_after_fatal_write()→handler.close()→ socketon_closefires the JS'close'event synchronously.- The user's
'close'handler callsprocess.exit(1). Bun__Process__exit→vm.on_exit().dispatch_on_exitno-ops (m_isExitingalready true). Line 1495 overwritesis_inside_deferred_task_queuetotrue(it was alreadytrue). Line 1496 callsself.event_loop_mut().deferred_tasks.run()— a second live&mut DeferredTaskQueue.- The inner
run()starts ati = 0, reaches the same H2 entry (still present), and callstask(nn.as_ptr())again →self.deref()runs a second time on a ref that was released in step 3. global_exit()terminates the process; the outerrun()never returns.
Fix
Match the guard shape used everywhere else — save the prior flag and only run when it was false:
if !self.is_inside_deferred_task_queue.get() { self.is_inside_deferred_task_queue.set(true); self.event_loop_mut().deferred_tasks.run(); self.is_inside_deferred_task_queue.set(false); }
Skipping the drain when already inside
run()is fine for the PR's goal: the outerrun()is what's currently flushing sinks, andglobal_exit()'s stdout/stderr flush still runs. The FileSink case this PR targets (top-levelwrite()+process.exit()) is never insiderun(), so it's unaffected.
|
Addressed the re-entrancy finding in 7f79ec1: the on_exit drain is now guarded by |
Bun.file(p).writer().write(chunk) buffers below the auto-flush threshold and registers a deferred task to push the bytes at the next microtask drain. A same-tick process.exit() never returns to the event loop, so that task was dropped and the file stayed at 0 bytes. Every other exit path (natural fall-through, process.exitCode, a later-tick exit) already reaches the drain via tick(). Run deferred_tasks.run() inside on_exit() after the 'exit' listeners fire, so writes made before and inside an 'exit' listener both reach the fd. This runs only the bounded sync flush callbacks, not JS microtasks.
On Windows FileSink dispatches the first write via uv_fs_write and queues the listener's write behind it; the completion callback never runs because process.exit() does not return to the event loop. Only the first write lands (pre-existing behavior, not a regression). POSIX buffers both writes synchronously and the on_exit auto-flush drains them in one write(2).
A process.exit() reached from inside an AutoFlusher callback (e.g. H2FrameParser on_auto_flush -> handler close -> JS close handler) would re-enter deferred_tasks.run() while the outer run() still holds &mut DeferredTaskQueue. Skip the drain when already inside, matching the guard at every other call site.
On Windows the write goes straight to uv_fs_write on the libuv threadpool without registering an AutoFlusher, so the on_exit drain is a no-op and whether the bytes land before ExitProcess is a race.
138f52f to
71f8332
Compare
The Windows FileSink writer dispatches via uv_fs_write on the libuv threadpool and never registers an AutoFlusher synchronously, so every process.exit() variant here is a threadpool-vs-ExitProcess race rather than the POSIX buffered flush these tests cover.
There was a problem hiding this comment.
The Windows flakiness I flagged in earlier passes is resolved by skipping the whole describe on Windows. No bugs found this run. Deferring to a maintainer because the runtime change sits in VirtualMachine::on_exit() and drains the full deferred_tasks queue — which also holds AutoFlusher entries for Postgres/MySQL/Valkey connections, NodeHTTPResponse, H2FrameParser, and HTTPServerWritable, not just FileSink. That looks intentional per the PR description, but it's a behavior change on the process.exit() path worth a human sign-off.
What was reviewed:
on_exit()drain mirrors the guard pattern atevent_loop.rs:336-338; re-entry guard matches the other three call sites.- Placement after
dispatch_on_exitand beforeis_shutting_down = true— nothing the AutoFlusher callbacks depend on is torn down yet. - Test: 5 subprocess cases (repro + 3 controls + exit-listener), whole describe Windows-skipped with rationale; stderr drained, stdout is empty so no pipe-buffer deadlock.
Extended reasoning...
Overview
Two files: a 7-line addition to VirtualMachine::on_exit() in src/jsc/VirtualMachine.rs that drains event_loop.deferred_tasks after the 'exit' event fires, and a new 5-case describe block in test/js/bun/util/filesink.test.ts. The runtime change is a copy of the guard-set-run-unset pattern already at event_loop.rs:336-338, gated on !is_inside_deferred_task_queue so a process.exit() reached from inside an AutoFlusher callback skips the inner drain.
Security risks
None identified. The drain runs already-registered native flush callbacks (write(2) of buffered bytes, socket uncork) on the JS thread; it does not run JS microtasks and does not accept new external input.
Level of scrutiny
High. on_exit() runs on every process termination and every worker termination. The FIXME immediately below the added block notes that a full event_loop().tick() here breaks 50+ tests — the exit path is known-sensitive. This change is much narrower (deferred-task queue only, no microtask drain), but the queue holds more than FileSink: PostgresSQLConnection, JSMySQLConnection, ValkeyClient, NodeHTTPResponse, H2FrameParser, and HTTPServerWritable all register on_auto_flush callbacks there. Flushing those on process.exit() aligns it with the natural-exit path (where they've already been drained), and the PR description acknowledges the scope, but a maintainer should confirm that's the intended semantics rather than a FileSink-only flush.
Other factors
I left three prior review comments on this PR, all about Windows test flakiness (async uv_fs_write never registers the AutoFlusher, so the drain is a no-op there and every process.exit() variant races the threadpool against ExitProcess). All three are now resolved by e965c56, which skips the entire describe on Windows with a rationale comment. The tests follow file conventions (tmpdirSync, bunEnv, it.concurrent for independent subprocesses, combined-object assertion). The child processes write nothing to stdout, so the un-drained default stdout pipe cannot fill. The bug-hunting system found nothing this run.
|
Updated 4:06 PM PT - Jul 28th, 2026
❌ @robobun, your commit e965c56 has some failures in 🧪 To try this PR locally: bunx bun-pr 36250That installs a local version of the PR into your bun-36250 --bun |
|
Updated 6:01 PM PT - Jul 28th, 2026
❌ @robobun, your commit e965c56 has some failures in 🧪 To try this PR locally: bunx bun-pr 36250That installs a local version of the PR into your bun-36250 --bun |
* upstream/main: (422 commits) install: drop packages held only by optional-peer resolution slots from bun.lock (oven-sh#35681) Update mimalloc to the upstream dev3 (v3.4.3) sync (oven-sh#36431) compile(pe): ftruncate the Windows --compile output after writing (oven-sh#36430) Strong: back bun_jsc::Strong with StrongRootBlock; free AbortSignal.timeout at wrapper GC (oven-sh#35849) test(harness): replace toRun matcher with async bunRun + toSpawn (oven-sh#36424) test: measure memory via harness rss() instead of process.memoryUsage.rss() (oven-sh#36429) Deflake a few tests no-orphans(windows): allow CREATE_BREAKAWAY_FROM_JOB and set DIE_ON_UNHANDLED_EXCEPTION on the Job (oven-sh#36414) GarbageCollectionController: replace per-tick heap sampler with idle timer only (oven-sh#35356) exe_format(pe): write a valid OptionalHeader.CheckSum for --compile output (oven-sh#36383) FileSink: flush buffered bytes when process.exit() runs in the same tick as write() (oven-sh#36250) test(http): speed up and de-flake serve-async-stream-client-abort.test.ts (oven-sh#35919) test(20144): stop racing child startup against the 1s SIGKILL guard (oven-sh#34166) test(no-orphans): skip fast-exit perl daemon test on macOS (oven-sh#36413) fs: return negative BigIntStats *Ns for pre-epoch timestamps (oven-sh#36187) event_loop: make DeferredTaskQueue::run tolerate re-entrant map mutation (oven-sh#32703) dotenv: stop panicking on nested `${...}` inside `${VAR:-default}` (oven-sh#36199) fetch: make the idle timer an absolute deadline for the response header block (oven-sh#36145) bundler: don't panic on unterminated naming template placeholders (oven-sh#36325) Buffer#indexOf/lastIndexOf: rare-byte SIMD filter with a Two-Way O(n+m) fallback (oven-sh#36420) ... # Conflicts: # src/jsc/bindings/BunDebugger.cpp
* upstream/main: (422 commits) install: drop packages held only by optional-peer resolution slots from bun.lock (oven-sh#35681) Update mimalloc to the upstream dev3 (v3.4.3) sync (oven-sh#36431) compile(pe): ftruncate the Windows --compile output after writing (oven-sh#36430) Strong: back bun_jsc::Strong with StrongRootBlock; free AbortSignal.timeout at wrapper GC (oven-sh#35849) test(harness): replace toRun matcher with async bunRun + toSpawn (oven-sh#36424) test: measure memory via harness rss() instead of process.memoryUsage.rss() (oven-sh#36429) Deflake a few tests no-orphans(windows): allow CREATE_BREAKAWAY_FROM_JOB and set DIE_ON_UNHANDLED_EXCEPTION on the Job (oven-sh#36414) GarbageCollectionController: replace per-tick heap sampler with idle timer only (oven-sh#35356) exe_format(pe): write a valid OptionalHeader.CheckSum for --compile output (oven-sh#36383) FileSink: flush buffered bytes when process.exit() runs in the same tick as write() (oven-sh#36250) test(http): speed up and de-flake serve-async-stream-client-abort.test.ts (oven-sh#35919) test(20144): stop racing child startup against the 1s SIGKILL guard (oven-sh#34166) test(no-orphans): skip fast-exit perl daemon test on macOS (oven-sh#36413) fs: return negative BigIntStats *Ns for pre-epoch timestamps (oven-sh#36187) event_loop: make DeferredTaskQueue::run tolerate re-entrant map mutation (oven-sh#32703) dotenv: stop panicking on nested `${...}` inside `${VAR:-default}` (oven-sh#36199) fetch: make the idle timer an absolute deadline for the response header block (oven-sh#36145) bundler: don't panic on unterminated naming template placeholders (oven-sh#36325) Buffer#indexOf/lastIndexOf: rare-byte SIMD filter with a Two-Way O(n+m) fallback (oven-sh#36420) ...
* upstream/main: (422 commits) install: drop packages held only by optional-peer resolution slots from bun.lock (oven-sh#35681) Update mimalloc to the upstream dev3 (v3.4.3) sync (oven-sh#36431) compile(pe): ftruncate the Windows --compile output after writing (oven-sh#36430) Strong: back bun_jsc::Strong with StrongRootBlock; free AbortSignal.timeout at wrapper GC (oven-sh#35849) test(harness): replace toRun matcher with async bunRun + toSpawn (oven-sh#36424) test: measure memory via harness rss() instead of process.memoryUsage.rss() (oven-sh#36429) Deflake a few tests no-orphans(windows): allow CREATE_BREAKAWAY_FROM_JOB and set DIE_ON_UNHANDLED_EXCEPTION on the Job (oven-sh#36414) GarbageCollectionController: replace per-tick heap sampler with idle timer only (oven-sh#35356) exe_format(pe): write a valid OptionalHeader.CheckSum for --compile output (oven-sh#36383) FileSink: flush buffered bytes when process.exit() runs in the same tick as write() (oven-sh#36250) test(http): speed up and de-flake serve-async-stream-client-abort.test.ts (oven-sh#35919) test(20144): stop racing child startup against the 1s SIGKILL guard (oven-sh#34166) test(no-orphans): skip fast-exit perl daemon test on macOS (oven-sh#36413) fs: return negative BigIntStats *Ns for pre-epoch timestamps (oven-sh#36187) event_loop: make DeferredTaskQueue::run tolerate re-entrant map mutation (oven-sh#32703) dotenv: stop panicking on nested `${...}` inside `${VAR:-default}` (oven-sh#36199) fetch: make the idle timer an absolute deadline for the response header block (oven-sh#36145) bundler: don't panic on unterminated naming template placeholders (oven-sh#36325) Buffer#indexOf/lastIndexOf: rare-byte SIMD filter with a Two-Way O(n+m) fallback (oven-sh#36420) ... # Conflicts: # src/js/internal/debugger.ts
* upstream/main: (422 commits) install: drop packages held only by optional-peer resolution slots from bun.lock (oven-sh#35681) Update mimalloc to the upstream dev3 (v3.4.3) sync (oven-sh#36431) compile(pe): ftruncate the Windows --compile output after writing (oven-sh#36430) Strong: back bun_jsc::Strong with StrongRootBlock; free AbortSignal.timeout at wrapper GC (oven-sh#35849) test(harness): replace toRun matcher with async bunRun + toSpawn (oven-sh#36424) test: measure memory via harness rss() instead of process.memoryUsage.rss() (oven-sh#36429) Deflake a few tests no-orphans(windows): allow CREATE_BREAKAWAY_FROM_JOB and set DIE_ON_UNHANDLED_EXCEPTION on the Job (oven-sh#36414) GarbageCollectionController: replace per-tick heap sampler with idle timer only (oven-sh#35356) exe_format(pe): write a valid OptionalHeader.CheckSum for --compile output (oven-sh#36383) FileSink: flush buffered bytes when process.exit() runs in the same tick as write() (oven-sh#36250) test(http): speed up and de-flake serve-async-stream-client-abort.test.ts (oven-sh#35919) test(20144): stop racing child startup against the 1s SIGKILL guard (oven-sh#34166) test(no-orphans): skip fast-exit perl daemon test on macOS (oven-sh#36413) fs: return negative BigIntStats *Ns for pre-epoch timestamps (oven-sh#36187) event_loop: make DeferredTaskQueue::run tolerate re-entrant map mutation (oven-sh#32703) dotenv: stop panicking on nested `${...}` inside `${VAR:-default}` (oven-sh#36199) fetch: make the idle timer an absolute deadline for the response header block (oven-sh#36145) bundler: don't panic on unterminated naming template placeholders (oven-sh#36325) Buffer#indexOf/lastIndexOf: rare-byte SIMD filter with a Two-Way O(n+m) fallback (oven-sh#36420) ...
Reproduction
process.exit(0)same tickawait Bun.sleep(0); process.exit(0)process.exitCode = 0The
fatal(); log.write(msg); process.exit(1)shape silently lost the last log lines with exit code 0 and no error.Cause
FileSink.write()buffers in userspace and, when data is pending, only registers anAutoFlusherdeferred task (FileSink.rs:414). That task is drained byEventLoop::deferred_tasks.run()insidedrain_microtasks_with_global()(event_loop.rs:337), which every other exit path reaches viatick()beforeon_exit().process.exit()goesProcess_functionExit->reallyExit->Bun__Process__exit->on_exit()->global_exit()->Global::exitwithout ever returning to the event loop (see the existing FIXME atVirtualMachine.rs:1512).Global::exitflushes only Bun's own stdout/stderr writer, which is why a same-tickconsole.logsurvived.Fix
Drain
deferred_tasksinon_exit()right afterExitHandler::dispatch_on_exit, so writes done beforeprocess.exit()and inside an'exit'listener both reach the fd. This runs only the bounded sync flush callbacks registered viaAutoFlusher(awrite(2)of already-accepted bytes), not JS microtasks. It is a no-op on the natural-exit path (the queue is already empty by then) and also covers the workeron_exitpath.Node's
fs.createWriteStreamwrite is async and is documented as not awaited byprocess.exit(); Bun'sFileSink.write()already accepted the bytes synchronously into a userspace buffer on a plain fd, so flushing them is the same class of work as the stdout flush Bun already does and the SQLite close-for-termination indispatch_on_exit.Verification
Full
filesink.test.tsis 55/55 green.process/,worker.test.ts,spawn/exit-code.test.tsare unchanged vs main in this environment.no test proof · iteration 2 · 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