Repository navigation
event loop: do not park a promise wait's poll once the promise has settled #39268
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 9 commits
857bf66
e8aa742
b1700e2
7dc53f5
cc6fc1a
b831cdd
84f7d48
8e469f5
c0fb4d9
90c8cb4
2a1d052
e5fdbde
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -153,6 +153,7 @@ mod drain_result { | |
| // the microtask queue through it is interior mutation invisible to Rust. | ||
| unsafe extern "C" { | ||
| safe fn JSC__JSGlobalObject__drainMicrotasks(global: &JSGlobalObject) -> u8; | ||
| safe fn JSC__JSGlobalObject__hasMicrotaskCheckpointWork(global: &JSGlobalObject) -> bool; | ||
| } | ||
|
|
||
| impl JSGlobalObject { | ||
|
|
@@ -458,6 +459,15 @@ impl EventLoop { | |
| self.drain_microtasks_with_global(global, jsc_vm) | ||
| } | ||
|
|
||
| /// Whether [`drain_microtasks`](Self::drain_microtasks) has anything to | ||
| /// do: a deferred task is registered, the VM is stopping, a termination is | ||
| /// pending, or a tick or a microtask is queued. | ||
|
robobun marked this conversation as resolved.
Resolved
|
||
| #[inline] | ||
| pub fn has_checkpoint_work(&self) -> bool { | ||
| !self.deferred_tasks.is_empty() | ||
| || JSC__JSGlobalObject__hasMicrotaskCheckpointWork(self.global_ref()) | ||
| } | ||
|
|
||
| // should be called after exit() | ||
| pub fn maybe_drain_microtasks(&mut self) -> Result<(), Stopped> { | ||
| if self.entered_event_loop_count == 0 && !self.vm_ref().is_inside_deferred_task_queue.get() | ||
|
|
@@ -1118,6 +1128,23 @@ impl EventLoop { | |
| self.vm_ref().as_mut().auto_tick(); | ||
| } | ||
|
|
||
| /// [`auto_tick`](Self::auto_tick) for a caller blocked until `promise` | ||
| /// settles. A settled promise wakes nothing, and neither does a stop met | ||
| /// while script ran. So after the immediates this tick runs the microtask | ||
| /// checkpoint if it has work, and polls without parking once `promise` has | ||
| /// settled or the VM has stopped: the caller returns as soon as it does. | ||
| /// | ||
| /// The checkpoint has work there when the caller has the loop entered (it | ||
| /// is a callback, or runs in a microtask drain): the exits of the | ||
| /// immediates are then not outermost and checkpoint nothing, so their | ||
| /// microtasks and the flush of their buffered writes are still due. The | ||
| /// tail of the caller's `tick()` (an `unhandledRejection` handler) and an | ||
| /// immediate that throws leave microtasks too. | ||
|
robobun marked this conversation as resolved.
Resolved
|
||
| #[inline] | ||
| pub fn auto_tick_waiting_on(&mut self, promise: jsc::AnyPromise) { | ||
| self.vm_ref().as_mut().auto_tick_waiting_on(Some(promise)); | ||
| } | ||
|
|
||
| /// `eventLoop().autoTickActive()` — like [`auto_tick`](Self::auto_tick) but | ||
| /// only sleeps in the uSockets loop while it has active handles. | ||
| /// Dispatches through | ||
|
|
@@ -1150,7 +1177,7 @@ impl EventLoop { | |
| } | ||
| self.tick(); | ||
| if promise.status() == PromiseStatus::Pending { | ||
| self.auto_tick(); | ||
| self.auto_tick_waiting_on(promise); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 pre-existing, not blocking: REPL users still get the parked wait this PR fixes elsewhere: an Why this was flaggedIn Verification: pre-existing (same-class site the PR leaves unfixed; REVIEW.md "fix the whole class" applies and the PR does not state the exclusion). Trigger: in interactive |
||
| } | ||
| } | ||
| Ok(()) | ||
|
|
@@ -1360,7 +1387,7 @@ impl EventLoop { | |
| // Nothing in flight can settle the load; let spin() decide. | ||
| break; | ||
| } | ||
| self.auto_tick(); | ||
| self.auto_tick_waiting_on(promise); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 pre-existing, not blocking: Worker startup still parks after this PR when an immediate-settled plugin hook starts the entry's evaluation: the worker stays in the Pending state until an unrelated timer or I/O event wakes its poll. wait_for_worker_entry_evaluation (src/jsc/event_loop.rs:1362-1380) exits on entry_evaluation_started, but auto_tick_waiting_on only un-parks on the promise settling or a stop (src/runtime/jsc_hooks.rs:927). With a top-level await pending the promise stays Pending, so wait_over is false and the poll at jsc_hooks.rs:1037 blocks even though the wait's own exit condition already holds. … Why this was flagged…Fix: fold every exit condition of a waiting loop into the non-blocking decision (entry_evaluation_started and has_requested_terminate for this loop), e.g. let the waiter pass a closure or re-check after the checkpoint and set wait_over. A Worker whose Bun.plugin onLoad/onResolve hook resolves from a setImmediate callback, and whose entry module has a top-level await (e.g. awaiting the first parentPort message). The immediate runs in tick_immediate_tasks (src/runtime/jsc_hooks.rs:917); its exit() checkpoint runs the module-loader reactions, which set entry_evaluation_started and begin evaluating the entry, which then suspends on its top-level await. Back in auto_tick, wait_over at jsc_hooks.rs:927 is false because the promise is still Pending, so has_pending_immediate is false and tick_with_timeout at jsc_hooks.rs:1037 blocks. wait_for_worker_entry_evaluation (src/jsc/event_loop.rs:1362) only re-checks entry_evaluation_started after auto_tick returns, so WebWorker__workerGlobalScopeStarted (src/jsc/web_worker.rs:923) and the delivery of messages the parent already posted are delayed… Verification: pre-existing (the base's plain |
||
| } | ||
| } | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -821,7 +821,7 @@ unsafe fn load_preloads(vm: *mut VirtualMachine) -> bun_jsc::CrateResult<*mut JS | |
| // SAFETY: per fn contract — short-lived `&mut *vm` for the | ||
| // dispatched `auto_tick` hook (same shape as the | ||
| // non-watcher `wait_for_promise` arm). | ||
| unsafe { (*vm).auto_tick() }; | ||
| unsafe { (*vm).auto_tick_waiting_on(Some(AnyPromise::Internal(pip))) }; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
| } else { | ||
|
|
@@ -894,12 +894,14 @@ unsafe fn ensure_debugger(vm: *mut VirtualMachine, block_until_connected: bool) | |
| /// `eventLoop().autoTick()`. Needs | ||
| /// `timer::All` for the poll-timeout calculation, hence dispatched here. | ||
| /// | ||
| /// `waiting_on`: see `EventLoop::auto_tick_waiting_on`. | ||
| /// | ||
|
robobun marked this conversation as resolved.
Resolved
|
||
| /// PERF: the one fn-ptr indirection is dwarfed by the kqueue/epoll syscall it | ||
| /// gates. | ||
| /// | ||
| /// # Safety | ||
| /// `vm` is the live per-thread VM. | ||
| unsafe fn auto_tick(vm: *mut VirtualMachine) { | ||
| /// `vm` is the live per-thread VM; `waiting_on`, if any, is a live promise. | ||
| unsafe fn auto_tick(vm: *mut VirtualMachine, waiting_on: Option<AnyPromise>) { | ||
| // Note: reshaped for borrowck — `EventLoop` is a value field of | ||
| // `VirtualMachine`, so holding `&mut EventLoop` while also touching VM | ||
| // siblings would alias. Dereference per-field via the raw `vm` ptr. | ||
|
|
@@ -913,10 +915,21 @@ unsafe fn auto_tick(vm: *mut VirtualMachine) { | |
| // the `has_pending_immediate` read below is correct. | ||
| // SAFETY: `el` is the live per-thread event loop; `vm` per fn contract. | ||
| unsafe { (*el).tick_immediate_tasks(vm) }; | ||
| let mut wait_over = false; | ||
| if let Some(promise) = waiting_on { | ||
| // See `EventLoop::auto_tick_waiting_on`. An empty checkpoint is | ||
| // skipped: a program with a pending top-level await is here on every | ||
| // turn of its loop. | ||
| // SAFETY: as above. | ||
| let stopped = | ||
| unsafe { &*el }.has_checkpoint_work() && unsafe { (*el).drain_microtasks() }.is_err(); | ||
| // Final: nothing else before the poll runs user script. | ||
| wait_over = stopped || promise.status() != PromiseStatus::Pending; | ||
|
Comment on lines
+924
to
+927
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Test authors get a silent pass where main fails: an unrelated unhandled rejection raised while Why this was flaggedA test does Verification: normal, acknowledged in diff: the PR description's "Downsides" bullet says " |
||
| } | ||
| // SAFETY: as above. | ||
| let has_yielded_tasks = unsafe { (*el).promote_yield_tasks() }; | ||
| #[cfg(windows)] | ||
| if has_yielded_tasks || !unsafe { &*el }.immediate_tasks.is_empty() { | ||
| if has_yielded_tasks || wait_over || !unsafe { &*el }.immediate_tasks.is_empty() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 pre-existing, not blocking: On Windows a promise wait still parks when the new checkpoint enqueues a JS-thread task: the libuv poll blocks until an unrelated event even though a task is ready. The Windows wakeup condition at src/runtime/jsc_hooks.rs:932 checks has_yielded_tasks, wait_over and immediate_tasks but not has_pending_tasks(), while the Unix timeout at :995-998 does include has_pending_tasks(). The PR's checkpoint at :925 now runs microtasks before this decision, so tasks they enqueue (postMessage delivery, stream reads) are ready but do not un-park on Windows. Fix: make the Windows wakeup condition match the Unix has_pending_immediate set, including has_pending_tasks(), so both platforms treat a ready task as a reason not to block. Why this was flaggedTrigger: on Windows, inside a nested wait (expect(p).resolves, Bun.build plugin, entry load), a microtask run by the new checkpoint at src/runtime/jsc_hooks.rs:925-926 enqueues a task onto the JS thread's task queue (a MessagePort delivery, a stream pull, a same-thread enqueue_task) without settling the awaited promise. wait_over at :927 is false, immediate_tasks is empty, so the cfg(windows) branch at :932 does not call wakeup(); tick_with_timeout at :1037 ignores its timeout argument on libuv (comment at src/jsc/event_loop.rs:1338), so the loop parks until an unrelated timer or I/O event. The Unix path at :995-998 folds has_pending_tasks() into has_pending_immediate and does not block. The base branch had the same omission at :932, but microtasks then ran only in tick(), before auto_tick; the PR moves microtask execution to a point after which the only un-park decision for Windows is this condition, and it was dismissed as pre-existing without checking that the two platform conditions differ. Population: every Windows user of a synchronous promise wait whose settling chain goes through a task.… Verification: pre-existing. Trigger: on Windows, inside a nested wait, JS run before the poll (an immediate, an unhandledRejection handler, or — with this PR — a microtask run by the new checkpoint) enqueues a same-thread task via |
||
| // SAFETY: `el` is the live per-thread event loop. | ||
| unsafe { (*el).wakeup() }; | ||
| } | ||
|
|
@@ -979,8 +992,8 @@ unsafe fn auto_tick(vm: *mut VirtualMachine) { | |
| // `tickImmediateTasks` swaps `next_immediate_tasks` in, so this | ||
| // reflects next-tick immediates (queued during the drain above). | ||
| // SAFETY: `el` is the live per-thread event loop. | ||
| // SAFETY: `el` is the live per-thread event loop. | ||
| let has_pending_immediate = has_yielded_tasks | ||
| || wait_over | ||
| || !unsafe { &*el }.immediate_tasks.is_empty() | ||
| || unsafe { &*el }.has_pending_tasks(); | ||
| // Fold the QUIC deadline into the poll timeout. | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.