Repository navigation
Conversation
A worker running a tight for(;;) postMessage() loop starved the parent
event loop: timers, setImmediate and TCP accept never ran while messages
kept arriving. drainInbox/drainAndDispatch already cap each drain and
reschedule when the cap is hit, but the reschedule went through
postTaskTo -> postTaskConcurrently -> concurrent_tasks, and
EventLoop::tick() calls tick_concurrent() inside its drain-until-empty
loop, so the reschedule ran in the same tick() and tick() never returned
to auto_tick (the only place immediates, poll and drain_timers run). The
old max(size, 1000) cap also grew with the backlog, so even the first
batch could be arbitrarily long when producer outran consumer.
EventLoop gains a next_iteration_tasks lane, promoted into tasks at
tick() entry only, plus ScriptExecutionContext::postTaskNextIteration to
reach it from C++. The drain reschedules in Worker::drainTo{Parent,
Worker} and MessagePortPipe::drainAndDispatch go there instead of the
concurrent queue, and the per-turn cap is now a fixed min(size, 1024).
The lane is folded into is_event_loop_alive, the poll-deadline immediacy
check, and release_queued_tasks_for_shutdown so shutdown reclaims any
task left parked there.
|
Status: ready to merge Reproduced: Fix applied and verified: Review follow-ups addressed:
CI (build #84940, finished): 193 passed, 1 failed, 2 expired. The one failed test is No failures attributable to this diff. |
WalkthroughChangesThe event loop now supports tasks deferred to the next iteration. Native bindings expose this scheduling path, and worker/message-port drains use bounded batches with next-iteration rescheduling. Tests cover timer and immediate execution during sustained message floods. Next-iteration scheduling and fair message draining
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 5:13 AM PT - Jul 29th, 2026
❌ @robobun, your commit b933785 has 1 failures in 🧪 To try this PR locally: bunx bun-pr 36314That installs a local version of the PR into your bun-36314 --bun |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
…:deinit The Vec backing next_iteration_tasks is owned by EventLoop, which is a field of a VM box that is freed without running Drop on worker teardown. release_queued_tasks_for_shutdown drains it into tasks for the existing per-tag reclaim, but the drained Vec keeps its capacity; deinit now resets it alongside the immediate-task Vecs so the buffer is released. Also drop the explicit per-test timeout and tighten the subprocess deadline now that the fixed per-turn cap keeps each drain bounded.
…rainInbox On Windows the poll timeout is ignored (uv_run UV_RUN_ONCE) and has_pending_immediate is discarded; the cfg(windows) wakeup() guards in auto_tick/auto_tick_active are what keep the loop from blocking when the only pending work is JS-thread-local. The reschedule moved off postTaskConcurrently (which called wakeup()) to a bare Vec::push, so those guards need to check next_iteration_tasks too. drainInbox: with limit = min(size, cap) the batch-exhausted re-swap was unreachable (limit always reaches 0 exactly when batch empties). Drop the outer while(true) and the re-swap; anything that arrived during dispatch waits for the next loop iteration, which is the intended yield.
…Pipe share one definition
…als), not O(backlog) With the fixed cap, whenever the inbox holds N > 1024 the drain dispatches 1024 then has N-1024 left in the local batch. The old prepend loop did N-1024 individual prepends under inbox.lock, which is the same lock the sender contends on every postMessage and grows with the backlog under a sustained flood. Swap so inbox.queue holds the large undrained tail, then append the few arrivals-during-dispatch: O(arrivals), independent of backlog, FIFO preserved. Also: update the stale max(size, 1000) text in the MessagePortPipe.h class-header doc, and rewrite the flushQueuedMessagesBeforeClose comment (its max() is intentional, a one-shot terminal flush with no reschedule) and replace its raw 1000 with kDrainPerTurnCap so the single tuning knob is greppable.
There was a problem hiding this comment.
All three prior-round findings are addressed in b933785 (swap-and-append put-back is now O(arrivals) with FIFO preserved; flushQueuedMessagesBeforeClose references kDrainPerTurnCap with an updated rationale; the MessagePortPipe.h class-header doc matches the new cap/yield semantics). No new issues found.
Deferring to a human for sign-off because this adds a new scheduling lane (next_iteration_tasks) to EventLoop::tick() and threads it through is_event_loop_alive, the auto_tick/auto_tick_active poll-deadline and Windows-wakeup checks, and shutdown reclaim — core event-loop invariants that warrant a maintainer look, and #35538 is already building on the same primitive.
What was reviewed
drainInboxcap-hit put-back: verified swap-then-append preserves FIFO (old tail 1025..N ahead of arrivals) and is O(arrivals) underinbox.lock.next_iteration_taskswiring: promoted only attick()entry; folded into liveness, poll-deadline, both Windows wakeup guards,release_queued_tasks_for_shutdown, anddeinit.- Termination-pending mid-batch path in
drainInboxstill dropsbatchwithout clearingdrainScheduled— unchanged from pre-PR behavior and correct given the thread is tearing down.
Extended reasoning...
Overview
The PR fixes event-loop starvation under a sustained postMessage flood by (1) adding a next_iteration_tasks lane to EventLoop that is promoted into tasks only at tick() entry, exposed to C++ as ScriptExecutionContext::postTaskNextIteration → Bun__queueTaskNextIteration; (2) switching the per-turn drain cap in Worker::drainInbox and MessagePortPipe::drainAndDispatch from max(size, 1000) to min(size, kDrainPerTurnCap=1024); and (3) routing the reschedule legs in drainToParent/drainToWorker/drainAndDispatch through the new lane instead of postTaskTo/scheduleDrain (which re-enter the same tick()). It touches event_loop.rs, jsc_hooks.rs, VirtualMachine.rs, four C++ binding files, three webcore files, and adds two tests.
This is my fourth pass. Prior rounds flagged: missing next_iteration_tasks in the Windows wakeup guards (fixed d45479c); duplicated kMessageDrainPerTurnCap constant (hoisted 7596e5c); and in the last round an O(backlog) prepend-back under inbox.lock, a stale sibling in flushQueuedMessagesBeforeClose, and a stale class-header doc — all addressed in b933785 and verified in the current diff.
Security risks
None identified. This is scheduling/fairness plumbing; no untrusted-input parsing, no auth/crypto, no boundary changes.
Level of scrutiny
High. EventLoop::tick(), is_event_loop_alive(), and the auto_tick poll-deadline computation are load-bearing for process liveness and I/O responsiveness across every workload. Adding a new task lane that participates in "is the loop alive" and "should the poll block" is exactly the kind of change where a subtle miss (e.g., a lane that keeps the process alive but is never promoted on some path) hangs real programs. I traced each integration point and they look consistent — promotion at tick() entry, folded into all four has_pending_immediate sites, both #[cfg(windows)] wakeup guards, is_event_loop_alive, release_queued_tasks_for_shutdown (drained into tasks before the per-tag release), and deinit — but a maintainer should confirm this is the intended shape for a primitive that #35538 also depends on.
Other factors
The drainInbox refactor (dropping the outer while(true) re-swap) changes when arrivals-during-dispatch are picked up: previously a small initial batch (< 1000) would re-swap and continue in the same task; now they always wait for the next iteration. That is the intended yield and matches the updated function-header comment. The termination-pending early return still drops the local batch without restoring it or clearing drainScheduled — identical to pre-PR behavior and correct given the thread is tearing down. Tests: the deterministic message-count-bounded test in message-port-pipe.test.ts is the gate proof; the wall-clock cross-thread test in worker.test.ts was discussed in an earlier round and left at 2000 ms with stated headroom. Regression sweep passed on debug+ASAN per the PR evidence.
|
Closing: superseded by #37075 (merged 2026-08-08), which gives worker and MessagePort drains a fixed per-task budget and continues them on the next loop iteration, after I/O and timers, when messages are left over (see the budget handling at the end of The two tests added here ( |
A worker running a tight
for(;;) postMessage()loop starves the parent event loop: timers,setImmediateand TCP accept never run while messages keep arriving. One worker is enough.Before:
{"messages":2000000,"ms":1507,"fired":{},"TIMER_STARVED":true}. Node v26 under the same flood interleaves fairly (setImmediate ~20 ms, 50 ms timer ~110 ms).Cause
Worker::drainToParent/MessagePortPipe::drainAndDispatchalready cap each drain atmax(inbox.size(), 1000)and reschedule when the cap is hit, but the reschedule goes throughpostTaskTo->postTaskConcurrently-> the parent's concurrent task queue, andEventLoop::tick()callstick_concurrent()inside itswhile tick_with_count() > 0loop. The reschedule is promoted and runs in the sametick(), sotick()never returns toauto_tick(jsc_hooks.rs), which is the only place immediates, the I/O poll (TCP accept) anddrain_timersrun. Themax(size, 1000)cap also grows with the backlog when the sender outruns the receiver, so even the first batch can be arbitrarily long.Fix
EventLoopgains anext_iteration_taskslane, promoted intotasksonce attick()entry (never inside the drain loop). Exposed to C++ asScriptExecutionContext::postTaskNextIterationviaBun__queueTaskNextIteration. Folded intois_event_loop_alive, thehas_pending_immediatepoll-deadline check inauto_tick/auto_tick_active, andrelease_queued_tasks_for_shutdownso shutdown reclaims any task left parked there.Worker::drainToParent,Worker::drainToWorkerandMessagePortPipe::drainAndDispatchpost via that lane instead ofpostTaskTo.min(size, 1024)so the inbox acts as the backpressure buffer and each loop iteration dispatches a bounded slice.This is Node's model:
uv_asyncfires once per loop iteration andMessagePort::OnMessagedrains what was queued when the callback started, so timers and poll run between drains.Tests
message-port-pipe.test.ts"self-feeding onmessage loop yields to timers/immediates": same-thread port whose handler posts back to itself; deterministic (single-threaded, message-count bounded). Fails on main at count>10000 withSTARVED: true; with the fix setTimeout(0) and setImmediate both fire within a few batches.worker.test.ts"sustained worker postMessage flood doesn't starve parent timers/immediates": the reported cross-thread scenario. Fails on main withSTARVED: true; with the fix the 100 ms timer and setImmediate both fire under the flood.Regression sweep on the debug build:
worker.test.ts26/26,message-port-pipe.test.ts14/14,worker_threads.test.ts91/91,message-channel.test.ts17/17.The same next-iteration primitive is on
claude/node-v26-hang-fixes(#35538) for the node parallel test; this applies it standalone to main with the fixed cap and the cross-thread worker coverage.[review] gate passed · iteration 1 · 14 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 4 passed · 0 rejected · iteration 1
evidence per changed file