Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/event_loop/DeferredTaskQueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ impl DeferredTaskQueue {
self.map.swap_remove(&ctx)
}

pub fn is_empty(&self) -> bool {
self.map.is_empty()
}

pub fn run(&mut self) {
// Callbacks may re-entrantly mutate `self.map` (see the re-entrancy
// note in the file doc), so re-read `len()` every iteration and
Expand Down
7 changes: 7 additions & 0 deletions src/event_loop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ This is called when the event loop is active and needs to wait for I/O:
└─────────────────────────────────────┘
```

### Nested waits (`EventLoop::wait_for_promise`)

Some native code blocks its caller until a promise settles (`expect(p).resolves` in `bun:test`, an async plugin `setup()` in `Bun.build()`, macros, the entry point load) by running `tick()` + `autoTick()` from inside whatever JavaScript called it. Such a wait uses `auto_tick_waiting_on(promise)`, which differs from a plain `autoTick()` in two ways:

- The blocked frame usually has the loop entered (it is itself a timer, immediate or task callback, or runs inside a microtask drain), so the `exit()` of each immediate run in step 1 is not the outermost one and does not drain microtasks. The waiting tick runs the microtask checkpoint itself right after step 1, since the promise is normally settled by one of them (an await continuation). It does so only when the checkpoint has work (a tick, a microtask or a deferred task is queued, or there is a stop to report): a program with a pending top-level await is in such a wait on every turn of its loop, and an empty checkpoint is not free.
- If the promise has settled or the VM has stopped by then (nothing else before step 4 runs user script), step 4 polls without blocking, as it does when an immediate is queued. A settled promise wakes nothing, so a blocking poll there would sleep until the next unrelated timer or I/O event even though the waiter is done.

## Task Draining Algorithm

### For Regular Tasks (`Task.rs:97-512`)
Expand Down
15 changes: 11 additions & 4 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2756,7 +2756,8 @@ pub struct RuntimeHooks {
pub ensure_debugger: unsafe fn(vm: *mut VirtualMachine, block_until_connected: bool),
/// `eventLoop().autoTick()` — needs `Timer::All` for the timeout calc.
/// Hoisted here so `event_loop.rs` doesn't need its own hook table.
pub auto_tick: unsafe fn(vm: *mut VirtualMachine),
/// `waiting_on`: see [`crate::event_loop::EventLoop::auto_tick_waiting_on`].
pub auto_tick: unsafe fn(vm: *mut VirtualMachine, waiting_on: Option<jsc::AnyPromise>),
/// `eventLoop().autoTickActive()` — like `auto_tick` but only sleeps in
/// the uSockets loop while it has active handles.
/// Separate slot because the body skips `runImminentGCTimer` /
Expand Down Expand Up @@ -3377,9 +3378,15 @@ impl VirtualMachine {
/// (needs `Timer::All` for the poll timeout).
#[inline]
pub fn auto_tick(&mut self) {
self.auto_tick_waiting_on(None);
}

/// See [`crate::event_loop::EventLoop::auto_tick_waiting_on`].
#[inline]
pub fn auto_tick_waiting_on(&mut self, waiting_on: Option<jsc::AnyPromise>) {
if let Some(hooks) = runtime_hooks() {
// SAFETY: hook contract — `self` is the live per-thread VM.
unsafe { (hooks.auto_tick)(self) };
unsafe { (hooks.auto_tick)(self, waiting_on) };
} else {
// No high tier (unit tests) — fall back to a non-blocking tick.
self.event_loop_mut().tick();
Expand Down Expand Up @@ -3572,7 +3579,7 @@ impl VirtualMachine {
};
// SAFETY: see above.
if crate::JSPromise::status_ptr(p) == crate::js_promise::Status::Pending {
self.auto_tick();
self.auto_tick_waiting_on(Some(jsc::AnyPromise::Internal(p)));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
} else {
Expand Down Expand Up @@ -5603,7 +5610,7 @@ impl VirtualMachine {
};
// SAFETY: see above.
if crate::JSPromise::status_ptr(p) == crate::js_promise::Status::Pending {
self.auto_tick();
self.auto_tick_waiting_on(Some(jsc::AnyPromise::Internal(p)));
}
}
} else {
Expand Down
14 changes: 14 additions & 0 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3176,6 +3176,20 @@ extern "C" uint8_t JSC__JSGlobalObject__drainMicrotasks(Zig::GlobalObject* globa
return globalObject->drainMicrotasks();
}

// Whether drainMicrotasks() would report a stop or run script: the VM is
// stopping, a termination is pending, or a tick or a microtask is queued. For
// a caller on a path too hot for an empty drain.
Comment thread
robobun marked this conversation as resolved.
Resolved
extern "C" bool JSC__JSGlobalObject__hasMicrotaskCheckpointWork(Zig::GlobalObject* globalObject)
{
auto& vm = globalObject->vm();
if (WebCore::clientData(vm)->isStoppingOrStopped(vm) || vm.hasPendingTerminationException()) [[unlikely]]
return true;
auto* nextTickQueue = globalObject->m_nextTickQueue.get();
if (nextTickQueue && !nextTickQueue->isEmpty())
return true;
return !vm.defaultMicrotaskQueue().isEmpty();
}

template<class Visitor, class T> static void visitGlobalObjectMember(Visitor& visitor, T& anything)
{
anything.visit(visitor);
Expand Down
31 changes: 29 additions & 2 deletions src/jsc/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Comment thread
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()
Expand Down Expand Up @@ -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.
Comment thread
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
Expand Down Expand Up @@ -1150,7 +1177,7 @@ impl EventLoop {
}
self.tick();
if promise.status() == PromiseStatus::Pending {
self.auto_tick();
self.auto_tick_waiting_on(promise);

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.

🟣 pre-existing, not blocking: REPL users still get the parked wait this PR fixes elsewhere: an await at the prompt that an immediate settles returns only when an unrelated timer or I/O event wakes the poll. The REPL has its own copy of this loop, wait_for_promise_or_sigint in src/runtime/cli/repl.rs:1118, which still calls plain auto_tick(). Fix: every promise-wait loop that alternates tick() and autoTick() should pass the awaited promise, so the REPL site should call auto_tick_waiting_on(jsc::AnyPromise::Normal(promise)) like the five sites this PR converts. With a server or interval open it parks up to the idle GC period; with BUN_GC_TIMER_DISABLE=1 it never returns. [also at: src/runtime/cli/repl.rs:1118 - Pre-existing sibling site: REPL users whose awaited expression is settled by a setImmediate callback still wait for an unrelated timer or I/O event before the prompt returns, while every other promise wait in this PR now returns at once. wait_for_promise_or_sigint at src/runtime/cli/repl.rs:1118 is…]
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

In bun repl, with something keeping the loop active (a setInterval or Bun.serve created earlier at the prompt), the user types await new Promise(r => setImmediate(r)). The REPL blocks in wait_for_promise_or_sigint (src/runtime/cli/repl.rs:1109-1121), which loops tick() then auto_tick() while the promise is Pending. On this branch auto_tick (src/runtime/jsc_hooks.rs:904) only computes wait_over when waiting_on is Some; the REPL passes nothing, so after tick_immediate_tasks settles the promise the poll at src/runtime/jsc_hooks.rs:1035 still blocks with the next-timer deadline. The prompt returns only when the idle GC timer or another timer/I/O fires (100 ms to 30 s), or never with BUN_GC_TIMER_DISABLE=1. The PR's own description says the fix covers everything on EventLoop::wait_for_promise; the REPL loop is a hand-rolled sibling of that helper and is not named as an…

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 bun repl with any active handle (a setInterval, Bun.serve) the user types an await that an immediate settles. Mechanism verified. /home/claude/bun/src/runtime/cli/repl.rs:1107-1122 wait_for_promise_or_sigint is the same…

}
}
Ok(())
Expand Down Expand Up @@ -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);

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.

🟣 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. …
A small fix can ride a push you are already making; otherwise a short reply is enough.

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 auto_tick() parked here too; the PR's un-park does not reach this exit condition, and REVIEW.md "fix the whole class" applies since the PR names "the worker entry wait" as an affected wait). Trigger: a worker whose entry evaluation begins inside an auto_tick turn (an immediate-settled plugin hook, or a microtask left after tick()) while the entry module…

}
}
}
Expand Down
23 changes: 18 additions & 5 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))) };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
} else {
Expand Down Expand Up @@ -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`.
///
Comment thread
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.
Expand All @@ -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

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.

🔴 Test authors get a silent pass where main fails: an unrelated unhandled rejection raised while expect(fn).toThrow() waits on fn's promise is now discarded. The new checkpoint at src/runtime/jsc_hooks.rs:925 runs microtasks that on main ran only after the wait returned, and it runs them under the quiet rejection handler that get_value_as_to_throw keeps installed across its wait (src/runtime/test_runner/expect.rs:858, :872). The PR text calls this an accepted downside; it is a real bug hidden in user code. Fix: report rejections raised by the checkpoint in a wait loudly while still swallowing the waited promise's own report, e.g. mark the returned promise handled and restore the scope (scope.apply) before wait_for_promise at expect.rs:872, as .resolves/.rejects do.

Why this was flagged

A test does const stray = (async () => { await new Promise(r => setImmediate(r)); throw new Error("unrelated bug"); })(); and then expect(() => new Promise((_, reject) => setImmediate(() => reject(new Error("boom"))))).toThrow("boom"). get_value_as_to_throw installs on_quiet_unhandled_rejection_handler_capture_value at src/runtime/test_runner/expect.rs:858 and keeps it across vm.wait_for_promise(promise) at expect.rs:872; UnhandledRejectionScope::apply (src/jsc/VirtualMachine.rs:629-633) later restores unhandled_error_counter, so anything reported in that window vanishes. On main the immediate batch rejects the waited promise synchronously, the stray's await continuation stays queued, the wait exits, scope.apply restores the loud handler, and the continuation runs at the next checkpoint: the rejection is reported and the test fails. With the PR, auto_tick drains that continuation at src/runtime/jsc_hooks.rs:925 inside the wait; the stray promise rejects with no handler, the tail handle_rejected_promises of auto_tick routes it to the quiet handler, and scope.apply discards the…

Verification: normal, acknowledged in diff: the PR description's "Downsides" bullet says "expect(() => p).toThrow() hides more unrelated rejections: the checkpoint runs their reactions inside its quiet scope ... 16 of 192 script cells go from exit 1 to exit 0" — the mechanism is real and the author's own measurement confirms it fires; the "16 of 192" bound I could not re-measure, but the class of…

}
// 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() {

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.

🟣 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.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: 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 EventLoop::enqueue_task without settling the awaited promise and without queuing an immediate. Mechanism verified: src/runtime/jsc_hooks.rs:932 `if has_yielded_tasks…

// SAFETY: `el` is the live per-thread event loop.
unsafe { (*el).wakeup() };
}
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading