Skip to content

event_loop: yield worker/port message drains to the next iteration so a postMessage flood can't starve timers/poll - #36314

Closed
robobun wants to merge 8 commits into
mainfrom
farm/05142769/worker-message-starvation
Closed

robobun wants to merge 8 commits into
mainfrom
farm/05142769/worker-message-starvation

Conversation

@robobun

@robobun robobun commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

A worker running a tight for(;;) postMessage() loop starves the parent event loop: timers, setImmediate and TCP accept never run while messages keep arriving. One worker is enough.

let recv = 0, t0 = 0; const seen = {};
const w = new Worker(URL.createObjectURL(new Blob(["for (;;) postMessage('m');"], { type: "text/javascript" })));
w.onmessage = () => {
  if (++recv === 1) { t0 = Date.now(); setTimeout(() => { seen.timer50ms = Date.now() - t0; }, 50); setImmediate(() => { seen.setImmediate = Date.now() - t0; }); }
  if (recv >= 2_000_000) { console.log(JSON.stringify({ messages: recv, ms: Date.now() - t0, fired: seen, TIMER_STARVED: !("timer50ms" in seen) })); process.exit(); }
};

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::drainAndDispatch already cap each drain at max(inbox.size(), 1000) and reschedule when the cap is hit, but the reschedule goes through postTaskTo -> postTaskConcurrently -> the parent's concurrent task queue, and EventLoop::tick() calls tick_concurrent() inside its while tick_with_count() > 0 loop. The reschedule is promoted and runs in the same tick(), so tick() never returns to auto_tick (jsc_hooks.rs), which is the only place immediates, the I/O poll (TCP accept) and drain_timers run. The max(size, 1000) cap also grows with the backlog when the sender outruns the receiver, so even the first batch can be arbitrarily long.

Fix

  • EventLoop gains a next_iteration_tasks lane, promoted into tasks once at tick() entry (never inside the drain loop). Exposed to C++ as ScriptExecutionContext::postTaskNextIteration via Bun__queueTaskNextIteration. Folded into is_event_loop_alive, the has_pending_immediate poll-deadline check in auto_tick / auto_tick_active, and release_queued_tasks_for_shutdown so shutdown reclaims any task left parked there.
  • The reschedule legs in Worker::drainToParent, Worker::drainToWorker and MessagePortPipe::drainAndDispatch post via that lane instead of postTaskTo.
  • The per-turn cap is now a fixed 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_async fires once per loop iteration and MessagePort::OnMessage drains 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 with STARVED: 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 with STARVED: true; with the fix the 100 ms timer and setImmediate both fire under the flood.

Regression sweep on the debug build: worker.test.ts 26/26, message-port-pipe.test.ts 14/14, worker_threads.test.ts 91/91, message-channel.test.ts 17/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)
ASAN without fix: 2 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/workers/message-port-pipe.test.ts test/js/web/workers/worker.test.ts
bun test v1.4.0 (b933785b2)

test/js/web/workers/message-port-pipe.test.ts:
29 |     `;
30 |     await using proc = Bun.spawn({ cmd: [bunExe(), "-e", script], env: bunEnv, stderr: "pipe" });
31 |     const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
32 |     expect(stderr).toBe("");
33 |     const out = JSON.parse(stdout.trim());
34 |     expect(out.STARVED).toBeUndefined();
                             ^
error: expect(received).toBeUndefined()

Received: true

      at <anonymous> (/workspace/bun/test/js/web/workers/message-port-pipe.test.ts:34:25)
(fail) MessagePort pipe > self-feeding onmessage loop yields to timers/immediates [1925.89ms]
(pass) MessagePort pipe > microtasks run between message events (task-source semantics) [22.34ms]
(pass) MessagePort pipe > messages buffered before start() are delivered on start() [8.21ms]
(pass) MessagePort pipe > receiveMessageOnPort pops in FIFO order [125
... (truncated)

release without fix: 3 skipped
bun test v1.4.0-canary.1 (7596e5cb6)

test/js/web/workers/message-port-pipe.test.ts:
(pass) MessagePort pipe > self-feeding onmessage loop yields to timers/immediates [7.33ms]
(pass) MessagePort pipe > microtasks run between message events (task-source semantics) [0.26ms]
(pass) MessagePort pipe > messages buffered before start() are delivered on start() [0.12ms]
(pass) MessagePort pipe > receiveMessageOnPort pops in FIFO order [0.70ms]
(pass) MessagePort pipe > close() inside onmessage handler still delivers already-queued messages [0.20ms]
(pass) MessagePort pipe > messages queued on a port follow it across transfer [0.24ms]
(pass) MessagePort pipe > same-context re-attach inside handler: inbox follows new wrapper [0.22ms]
(pass) MessagePort pipe > chained transfer delivers through every hop [0.23ms]
(pass) MessagePort pipe > objectTypeCounts drop after close + GC; peer-open pins listening port [21.22ms]
(pass) MessagePort pipe > port dropped in transit does not pin its peer [10.28ms]
(skip) MessagePort pipe > concurrent MessageChannel creation across workers is race-free
(skip) MessagePort pipe > burst of postMessage across threads delivers every message in order
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/workers/message-port-pipe.test.ts test/js/web/workers/worker.test.ts
bun test v1.4.0 (b933785b2)

test/js/web/workers/message-port-pipe.test.ts:
(pass) MessagePort pipe > self-feeding onmessage loop yields to timers/immediates [319.84ms]
(pass) MessagePort pipe > microtasks run between message events (task-source semantics) [15.65ms]
(pass) MessagePort pipe > messages buffered before start() are delivered on start() [8.24ms]
(pass) MessagePort pipe > receiveMessageOnPort pops in FIFO order [127.03ms]
(pass) MessagePort pipe > close() inside onmessage handler still delivers already-queued messages [12.54ms]
(pass) MessagePort pipe > messages queued on a port follow it across transfer [26.65ms]
(pass) MessagePort pipe > same-context re-attach inside handler: inbox follows new wrapper [11.61ms]
(pass) MessagePort pipe > chained transfer delivers through every hop [17.67ms]
(pass) MessagePort pipe > objectTypeCounts drop after close + GC; peer-open pins listening port [1531.49ms]
(pass) MessagePort pipe > port dropped in transi
... (truncated)

release with fix: 3 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 701ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/120] gen cpp.rs (cppbind)
[2/120] gen generated_host_exports.rs
generated_host_exports.rs: 95 exports (host=3, lazy=10, generic=82, rust=0); 240 extern-C blocks audited
[2/120] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp)
�[1m�
... (truncated)
diff hotspot
src/jsc/VirtualMachine.rs                     |  1 +
 src/jsc/bindings/ScriptExecutionContext.cpp   |  6 +++
 src/jsc/bindings/ScriptExecutionContext.h     |  2 +
 src/jsc/bindings/ZigGlobalObject.cpp          |  6 +++
 src/jsc/bindings/ZigGlobalObject.h            |  1 +
 src/jsc/bindings/webcore/MessagePort.cpp      |  8 +--
 src/jsc/bindings/webcore/MessagePortPipe.cpp  | 20 ++++----
 src/jsc/bindings/webcore/MessagePortPipe.h    | 10 ++--
 src/jsc/bindings/webcore/Worker.cpp           | 74 +++++++++++++--------------
 src/jsc/event_loop.rs                         | 20 ++++++++
 src/jsc/virtual_machine_exports.rs            | 10 ++++
 src/runtime/jsc_hooks.rs                      | 14 +++--
 test/js/web/workers/message-port-pipe.test.ts | 29 +++++++++++
 test/js/web/workers/worker.test.ts            | 44 ++++++++++++++++
 14 files changed, 189 insertions(+), 56 deletions(-)

gate history · 4 passed · 0 rejected · iteration 1

evidence per changed file
file                                           reads  edits  tests
src/jsc/VirtualMachine.rs                          2      1      0
src/jsc/bindings/ScriptExecutionContext.cpp        1      1      0
src/jsc/bindings/ScriptExecutionContext.h          4      4      0
src/jsc/bindings/ZigGlobalObject.cpp               2      2      0
src/jsc/bindings/ZigGlobalObject.h                 4      4      0
src/jsc/bindings/webcore/MessagePort.cpp           2      1      0
src/jsc/bindings/webcore/MessagePortPipe.cpp       6      5      0
src/jsc/bindings/webcore/MessagePortPipe.h         2      2      0
src/jsc/bindings/webcore/Worker.cpp                8      9      0
src/jsc/event_loop.rs                              8     10      0
src/jsc/virtual_machine_exports.rs                 4      4      0
src/runtime/jsc_hooks.rs                           3      3      0
test/js/web/workers/message-port-pipe.test.ts      1      1      0
test/js/web/workers/worker.test.ts                 2      5      0

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.
@robobun

robobun commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready to merge

Reproduced: for(;;) postMessage() in a worker processes 2M messages with zero timer/immediate callbacks on the parent; same for a self-feeding MessageChannel on one thread.

Fix applied and verified:

USE_SYSTEM_BUN=1 bun test test/js/web/workers/message-port-pipe.test.ts -t self-feeding   # FAIL (STARVED: true)
USE_SYSTEM_BUN=1 bun test test/js/web/workers/worker.test.ts -t "sustained worker"        # FAIL (STARVED: true)
bun bd test test/js/web/workers/message-port-pipe.test.ts -t self-feeding                 # PASS
bun bd test test/js/web/workers/worker.test.ts -t "sustained worker"                      # PASS

Review follow-ups addressed:

  • next_iteration_tasks checked in both #[cfg(windows)] wakeup guards (Windows ignores the poll timeout, so those wakeups are what keep the loop from blocking on a next-iteration deferral).
  • drainInbox flattened now that min(size, cap) makes the re-swap unreachable, and the put-back changed to swap-and-append so lock-held work is O(arrivals) not O(backlog) under a flood.
  • next_iteration_tasks Vec buffer freed in EventLoop::deinit (fixes the 64B LSan report in test-worker-messaging.js).
  • kDrainPerTurnCap hoisted to MessagePortPipe.h so both drain loops share one definition; flushQueuedMessagesBeforeClose now references it and its comment explains why it keeps max(); stale class-header doc updated.

CI (build #84940, finished): 193 passed, 1 failed, 2 expired. The one failed test is worker-transfer-terminate-stress.test.ts on debian 13 x64-asan, now classified [pre-existing] by the CI helper (also fails on main): the ExceptionScope::assertNoException() terminate()/MessagePort-serialize race its own header documents. The 2 expired jobs are the build-cpp scheduling issue that also hit #84842. Everything else is [flaky] (passed alone or on retry) and unrelated.

No failures attributable to this diff.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

The 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

Layer / File(s) Summary
Event-loop deferred task queue
src/jsc/event_loop.rs, src/jsc/VirtualMachine.rs, src/runtime/jsc_hooks.rs
Adds a deferred task queue, promotes it at tick start, includes it in liveness and auto-tick checks, and releases it during shutdown.
Native next-iteration scheduling API
src/jsc/bindings/ScriptExecutionContext.*, src/jsc/bindings/ZigGlobalObject.*, src/jsc/virtual_machine_exports.rs
Adds postTaskNextIteration and forwards tasks through the native binding into the event loop queue.
MessagePort and worker drain fairness
src/jsc/bindings/webcore/MessagePortPipe.*, src/jsc/bindings/webcore/MessagePort.cpp, src/jsc/bindings/webcore/Worker.cpp, test/js/web/workers/*
Bounds message draining at 1024 messages per turn, reschedules remaining work for the next iteration, and adds starvation tests for timers and immediates.

Possibly related PRs

  • oven-sh/bun#36052: Both changes modify VM event-loop pending-work and tick behavior.

Suggested reviewers: jarred-sumner, cirospaciari

🚥 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 summarizes the main change: deferring worker and port drains to the next event-loop iteration to prevent starvation.
Description check ✅ Passed The description covers the PR purpose, root cause, fix, and verification, so it provides the needed information despite different headings.

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

@robobun

robobun commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:13 AM PT - Jul 29th, 2026

❌ @robobun, your commit b933785 has 1 failures in Build #84940 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 36314

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

bun-36314 --bun

Comment thread src/jsc/bindings/ZigGlobalObject.h Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/event_loop.rs Resolved
Comment thread src/jsc/event_loop.rs Resolved
Comment thread src/jsc/event_loop.rs Resolved
Comment thread src/jsc/event_loop.rs Resolved
Comment thread src/jsc/virtual_machine_exports.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. node: fix the genuine-hang class — MessagePort loop starvation, pinned sockets, https handshakeTimeout, TLS alert errors (+2 tests) #35538 - Both introduce a next_iteration_tasks lane in EventLoop and change MessagePortPipe/Worker drain rescheduling to fix postMessage flood starvation of timers and poll; event_loop: yield worker/port message drains to the next iteration so a postMessage flood can't starve timers/poll #36314 extracts this fix standalone from node: fix the genuine-hang class — MessagePort loop starvation, pinned sockets, https handshakeTimeout, TLS alert errors (+2 tests) #35538's broader changeset

🤖 Generated with Claude Code

robobun added 2 commits July 29, 2026 04:08
…: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.
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/event_loop.rs Resolved
Comment thread src/jsc/virtual_machine_exports.rs Resolved
Comment thread src/runtime/jsc_hooks.rs Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
…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.
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread test/js/web/workers/worker.test.ts Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
Comment thread src/jsc/bindings/webcore/Worker.cpp Resolved
…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.
Comment thread src/jsc/bindings/webcore/Worker.cpp 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.

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

  • drainInbox cap-hit put-back: verified swap-then-append preserves FIFO (old tail 1025..N ahead of arrivals) and is O(arrivals) under inbox.lock.
  • next_iteration_tasks wiring: promoted only at tick() entry; folded into liveness, poll-deadline, both Windows wakeup guards, release_queued_tasks_for_shutdown, and deinit.
  • Termination-pending mid-batch path in drainInbox still drops batch without clearing drainScheduled — 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.

@robobun

robobun commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

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 MessagePortPipe::drainAndDispatch on main).

The two tests added here (self-feeding onmessage loop yields to timers/immediates and sustained worker postMessage flood doesn't starve parent timers/immediates) pass unmodified against an ASAN debug build of current main (04148c8) on repeated runs; both failed on the debug build of main when this PR was opened.

@robobun robobun closed this Aug 13, 2026
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