From a05b9c03b4774294840e8ea1220cd41ef9d57d74 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 13 Jun 2026 16:07:05 +0000 Subject: [PATCH 1/7] usockets: preserve the outer ready-poll batch across nested event-loop ticks A poll callback can re-enter us_loop_run_bun_tick (waitForPromise -> autoTick; in Bun.$ this happens when finish() runs a command's continuation inline during the poll dispatch via loop.exit()). The inner tick's epoll_wait/kevent overwrites the shared loop->ready_polls, num_ready_polls, and current_ready_poll while the outer us_internal_dispatch_ready_polls is still iterating the batch, so the outer loop resumes against the inner batch and silently skips its remaining events. For one-shot fds a skipped event is unrecoverable: the kernel disarmed the fd when epoll_wait returned it, and onUpdate never ran to set the re-arm flag. PR #30301 made the pidfd level-triggered so its dropped events recover on the next wait, but assumed pipes self-heal via EPOLLHUP. A disarmed EPOLLONESHOT fd reports nothing, so a batch of concurrent Bun.$ commands could drop one command's stdout/stderr EOF and hang it forever. Snapshot the outer batch and its cursor before a nested tick fetches new events, and restore them afterward, so no one-shot event is lost. A poll freed during a nested tick is nulled out of the live batch and every saved snapshot, so it is never re-dispatched from a stale entry; FilePolls route teardown through the new us_loop_invalidate_ready_poll to get the protection sockets already have via us_poll_stop/us_poll_change. --- .../bun-usockets/src/eventing/epoll_kqueue.c | 90 +++++++++++++++++++ packages/bun-usockets/src/internal/internal.h | 5 ++ .../bun-usockets/src/internal/loop_data.h | 4 + src/io/posix_event_loop.rs | 16 +++- src/uws_sys/InternalLoopData.rs | 6 ++ src/uws_sys/Loop.rs | 22 +++++ .../bun/spawn/pipe-reader-nested-tick.test.ts | 69 ++++++++++++++ 7 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 test/js/bun/spawn/pipe-reader-nested-tick.test.ts diff --git a/packages/bun-usockets/src/eventing/epoll_kqueue.c b/packages/bun-usockets/src/eventing/epoll_kqueue.c index 7507f27a3a4c..230ab803f359 100644 --- a/packages/bun-usockets/src/eventing/epoll_kqueue.c +++ b/packages/bun-usockets/src/eventing/epoll_kqueue.c @@ -52,6 +52,37 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout #endif #endif +/* A saved copy of an outer dispatch's ready-poll batch. us_loop_run_bun_tick + * re-enters itself (a poll callback calls waitForPromise -> autoTick), and the + * inner tick's epoll_wait/kevent overwrites the shared loop->ready_polls and + * its counters while the outer us_internal_dispatch_ready_polls is still + * mid-iteration. Without saving the outer batch, the outer loop resumes against + * the inner batch's data and silently skips its remaining events; for one-shot + * fds (pipe readers, pidfds) the kernel has already disarmed them, so a skipped + * event is lost forever and its owner waits for an event that never comes. + * Snapshots form a LIFO stack (loop->data.ready_poll_snapshots) so an + * arbitrarily nested tick protects every enclosing dispatch. */ +#ifdef LIBUS_USE_EPOLL +typedef struct epoll_event us_ready_poll_event_t; +#define GET_SNAPSHOT_POLL(snap, index) (struct us_poll_t *) (snap)->polls[index].data.ptr +#define SET_SNAPSHOT_POLL(snap, index, poll) (snap)->polls[index].data.ptr = (void*)poll +#else +typedef struct kevent64_s us_ready_poll_event_t; +#define GET_SNAPSHOT_POLL(snap, index) (struct us_poll_t *) (snap)->polls[index].udata +#if defined(__FreeBSD__) +#define SET_SNAPSHOT_POLL(snap, index, poll) (snap)->polls[index].udata = (void*)poll +#else +#define SET_SNAPSHOT_POLL(snap, index, poll) (snap)->polls[index].udata = (uint64_t)poll +#endif +#endif + +struct us_ready_poll_snapshot_t { + struct us_ready_poll_snapshot_t *outer; + int num; + int current; + us_ready_poll_event_t polls[]; +}; + /* Loop */ void us_loop_free(struct us_loop_t *loop) { us_internal_loop_data_free(loop); @@ -352,6 +383,26 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout loop->data.tick_depth++; + /* current_ready_poll < num_ready_polls is true only while an outer + * us_internal_dispatch_ready_polls is mid-iteration (a completed dispatch + * leaves them equal). So it means this is a nested tick, and the epoll_wait + * below is about to clobber the outer batch. Save it (and its cursor) now + * and restore it before we return so the outer dispatch resumes intact. On + * allocation failure we skip the snapshot and degrade to the old + * event-dropping behavior rather than crash. */ + struct us_ready_poll_snapshot_t *outer_snapshot = NULL; + if (loop->current_ready_poll < loop->num_ready_polls) { + int saved_num = loop->num_ready_polls; + outer_snapshot = us_malloc(sizeof(*outer_snapshot) + (size_t) saved_num * sizeof(outer_snapshot->polls[0])); + if (outer_snapshot) { + outer_snapshot->num = saved_num; + outer_snapshot->current = loop->current_ready_poll; + memcpy(outer_snapshot->polls, loop->ready_polls, (size_t) saved_num * sizeof(outer_snapshot->polls[0])); + outer_snapshot->outer = loop->data.ready_poll_snapshots; + loop->data.ready_poll_snapshots = outer_snapshot; + } + } + struct us_internal_callback_t *timer_callback = (struct us_internal_callback_t*)loop->data.sweep_timer; // Only integrate the loop if we haven't already. @@ -408,6 +459,18 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout /* Emit post callback */ us_internal_loop_post(loop); + + /* Restore the outer batch we clobbered (entries a nested free nulled out + * are preserved). Pop before tick_depth-- so it is gone once this frame is + * no longer on the stack. */ + if (outer_snapshot) { + memcpy(loop->ready_polls, outer_snapshot->polls, (size_t) outer_snapshot->num * sizeof(outer_snapshot->polls[0])); + loop->num_ready_polls = outer_snapshot->num; + loop->current_ready_poll = outer_snapshot->current; + loop->data.ready_poll_snapshots = outer_snapshot->outer; + us_free(outer_snapshot); + } + loop->data.tick_depth--; } @@ -432,6 +495,33 @@ void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop, struct num_entries_possibly_remaining--; } } + + /* A poll freed/changed while a nested tick is live must also be fixed up in + * the saved outer batches, or the outer dispatch re-dispatches a stale + * (freed) entry when it resumes. Each buffer holds the poll at most once + * (epoll) or twice (kqueue), same as the live buffer above. */ + for (struct us_ready_poll_snapshot_t *snap = loop->data.ready_poll_snapshots; snap; snap = snap->outer) { +#ifdef LIBUS_USE_EPOLL + int remaining = 1; +#else + int remaining = 2; +#endif + for (int i = snap->current; i < snap->num && remaining; i++) { + if (GET_SNAPSHOT_POLL(snap, i) == old_poll) { + SET_SNAPSHOT_POLL(snap, i, new_poll); + remaining--; + } + } + } +} + +/* Drop `poll` from the live ready-poll batch and every saved outer-batch + * snapshot so it is never dispatched after being freed. us_poll_stop/change + * already do this for uSockets sockets via us_internal_loop_update_pending_ + * ready_polls; Bun's FilePolls are torn down on the Rust side and call this so + * they get the same protection across nested ticks. */ +void us_loop_invalidate_ready_poll(struct us_loop_t *loop, void *poll) { + us_internal_loop_update_pending_ready_polls(loop, (struct us_poll_t *) poll, NULL, 0, 0); } /* Poll */ diff --git a/packages/bun-usockets/src/internal/internal.h b/packages/bun-usockets/src/internal/internal.h index 014d925fcc55..b30e8914428f 100644 --- a/packages/bun-usockets/src/internal/internal.h +++ b/packages/bun-usockets/src/internal/internal.h @@ -49,6 +49,11 @@ void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop, struct us_poll_t *new_poll, int old_events, int new_events); + +/* Drop `poll` from the live ready-poll batch and every saved outer-batch + * snapshot. Called from Bun's Rust FilePoll teardown so a FilePoll freed + * mid-dispatch (or mid-nested-tick) is never re-dispatched from a stale entry. */ +void us_loop_invalidate_ready_poll(struct us_loop_t *loop, void *poll); #endif /* We only have one networking implementation so far */ diff --git a/packages/bun-usockets/src/internal/loop_data.h b/packages/bun-usockets/src/internal/loop_data.h index 801649b2d1f8..9885d4ff6d84 100644 --- a/packages/bun-usockets/src/internal/loop_data.h +++ b/packages/bun-usockets/src/internal/loop_data.h @@ -80,6 +80,10 @@ struct us_internal_loop_data_t { * sockets must be deferred to the outermost tick so the outer dispatch * doesn't read a freed poll. */ int tick_depth; + /* LIFO stack of saved outer ready-poll batches, one per active nested + * us_loop_run_bun_tick (struct us_ready_poll_snapshot_t, defined in + * epoll_kqueue.c). NULL when no nested tick is in flight. */ + void *ready_poll_snapshots; }; #endif // LOOP_DATA_H diff --git a/src/io/posix_event_loop.rs b/src/io/posix_event_loop.rs index 942da6b2d8d8..a83122764400 100644 --- a/src/io/posix_event_loop.rs +++ b/src/io/posix_event_loop.rs @@ -411,13 +411,27 @@ impl FilePoll { } fn deinit_possibly_defer(&mut self, vm: EventLoopCtx, force_unregister: bool) { + // `unregister` below only drops us from the kernel; it does not touch + // `loop->ready_polls`. If we are being torn down while a dispatch (or a + // nested tick) is mid-iteration over that batch, the outer loop would + // re-dispatch our now-freed slot. Drop ourselves from the live batch + // and every saved outer snapshot first, while `self` is still valid. + // Only a registered poll can appear in a batch, and `unregister` leaves + // `WasEverRegistered` set, so this read is stable across it. + let was_ever_registered = self.flags.contains(Flags::WasEverRegistered); + if was_ever_registered { + let tagged = Pollable::init(self).ptr(); + // SAFETY: `loop_()` is the live C-owned uws loop; `tagged` is the + // exact tagged pointer stored in `ready_polls` for this FilePoll. + unsafe { Loop::invalidate_ready_poll(vm.loop_(), tagged) }; + } + // `loop_mut()` is the crate-private nonnull-asref accessor (single // deref in `EventLoopCtx`); the `&mut Loop` is consumed by `unregister` // and dropped before any `&mut Store` is materialised. let _ = self.unregister(vm.loop_mut(), force_unregister); self.owner.clear(); - let was_ever_registered = self.flags.contains(Flags::WasEverRegistered); self.flags = FlagsSet::empty(); self.fd = INVALID_FD; // `self` may live inside the `Store.hive` inline array, so a diff --git a/src/uws_sys/InternalLoopData.rs b/src/uws_sys/InternalLoopData.rs index 74df8437d991..9ff3fee3bdbf 100644 --- a/src/uws_sys/InternalLoopData.rs +++ b/src/uws_sys/InternalLoopData.rs @@ -55,6 +55,12 @@ pub struct InternalLoopData { // Higher tier (`bun_runtime`) casts this back when reading. pub jsc_vm: *const c_void, pub tick_depth: c_int, + /// LIFO stack of saved outer ready-poll batches (C + /// `struct us_ready_poll_snapshot_t`), one per active nested + /// `us_loop_run_bun_tick`. Owned and manipulated entirely on the C side; + /// mirrored here only so `InternalLoopData`'s size matches the C struct + /// (the `PosixLoop` layout assertions key `num_polls`' offset off it). + pub ready_poll_snapshots: *mut c_void, } impl InternalLoopData { diff --git a/src/uws_sys/Loop.rs b/src/uws_sys/Loop.rs index 8a6a20a8320b..5779cee4acc9 100644 --- a/src/uws_sys/Loop.rs +++ b/src/uws_sys/Loop.rs @@ -138,6 +138,26 @@ impl PosixLoop { self.ready_polls[idx] } + /// Drop `poll` (a tagged `FilePoll` pointer) from the live ready-poll batch + /// and every saved outer-batch snapshot, so a `FilePoll` torn down + /// mid-dispatch is never re-dispatched from a stale `ready_polls` entry. + /// The uSockets socket path does this via + /// `us_internal_loop_update_pending_ready_polls`; `FilePoll`s are freed on + /// the Rust side and route through here for the same protection. + /// + /// Takes `this: *mut Self` (not `&mut self`): callers hold the C-owned loop + /// as a raw pointer and the C callee touches the same loop, so a `&mut` + /// reborrow would be the noalias hazard `mod c` documents. + /// + /// # Safety + /// `this` must be the live C-allocated loop pointer; `poll` is the tagged + /// pointer stored in `ready_polls`. + #[inline] + pub unsafe fn invalidate_ready_poll(this: *mut Self, poll: *mut c_void) { + // SAFETY: per fn contract. + unsafe { c::us_loop_invalidate_ready_poll(this, poll) }; + } + pub fn inc(&mut self) { bun_core::scoped_log!(Loop, "inc {} + 1 = {}", self.num_polls, self.num_polls + 1); self.num_polls += 1; @@ -640,6 +660,8 @@ mod c { pub(super) fn uws_loop_addPreHandler(loop_: *mut Loop, ctx: *mut c_void, cb: LoopCtxCb); #[cfg(not(windows))] pub(super) fn us_loop_run_bun_tick(loop_: *mut Loop, timeout_ms: *const Timespec); + #[cfg(not(windows))] + pub(super) fn us_loop_invalidate_ready_poll(loop_: *mut Loop, poll: *mut c_void); pub(super) fn us_internal_free_closed_sockets(loop_: *mut Loop); pub(super) fn us_loop_close_all_groups(loop_: *mut Loop) -> c_int; #[cfg(not(windows))] diff --git a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts new file mode 100644 index 000000000000..477da13c719c --- /dev/null +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -0,0 +1,69 @@ +// A subprocess stdout/stderr pipe reader is registered one-shot on Linux +// (EPOLLONESHOT, via OneShotFlag::Dispatch). When the reader's readable/EOF +// event is dropped in user-space after epoll_wait has already returned it, the +// kernel has disarmed the fd and nothing re-arms it: `onUpdate` (which sets the +// re-arm flag) never ran. The output is then never read and the consumer waits +// forever. +// +// The drop happens when a poll callback re-enters us_loop_run_bun_tick while the +// outer us_internal_dispatch_ready_polls is still iterating the batch. The inner +// tick runs epoll_wait again, overwriting the shared loop->ready_polls / +// num_ready_polls / current_ready_poll, so the outer loop resumes against the +// inner batch and silently skips its own remaining events. +// +// Bun.$ hits this without any test-only poke: when a command finishes, finish() +// wraps the promise resolution in loop.enter()/loop.exit(), and loop.exit() +// drains microtasks inline, running the command's .then continuation *during* +// the poll dispatch. If that continuation synchronously waits on a promise +// (waitForPromise -> autoTick), the nested tick clobbers the batch and sibling +// commands' one-shot pipe-EOF events are lost. The command's shell never sees +// EOF, so its promise never resolves. +// +// PR #30301 fixed this for the pidfd by making it level-triggered, but left the +// pipe readers one-shot and assumed a dropped pipe event is reported again via +// EPOLLHUP on the next wait. It is not: a disarmed EPOLLONESHOT fd reports +// nothing until it is re-armed, which never happens. +// +// Fix: us_loop_run_bun_tick snapshots the outer ready-poll batch before a nested +// tick can clobber it and restores it afterward, so no one-shot event is dropped. +import { expect, test } from "bun:test"; +import { isLinux } from "harness"; + +// One-shot pipe polls are the POSIX event-loop path; on Windows libuv drives +// readiness. The deterministic repro relies on EPOLLONESHOT pipe readers, so gate +// it to Linux like the sibling pidfd regression test. +test.skipIf(!isLinux)( + "a batch of Bun.$ commands survives a nested tick from one command's continuation", + async () => { + const N = 34; + let nested = false; + + const cmds = Array.from({ length: N }, (_, i) => { + const cmd = Bun.$`printf %s out-${i}`.quiet(); + // The first command to settle runs this continuation inline, during the + // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on a + // promise here forces a nested us_loop_run_bun_tick; without the fix it + // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF + // events, which EPOLLONESHOT has already disarmed in the kernel. + cmd.then( + () => { + if (!nested) { + nested = true; + expect(Bun.sleep(1)).resolves.toBe(undefined); + } + }, + () => {}, + ); + return cmd; + }); + + // With the dropped-slot bug, the commands whose pipe-EOF was skipped never + // finish and this hangs until the test times out. There is no other wake + // source for a disarmed one-shot pipe. + const results = await Promise.all(cmds); + + for (let i = 0; i < N; i++) { + expect(results[i].stdout.toString()).toBe(`out-${i}`); + } + }, +); From ed74700c9e704b11828606131e689b86bab088eb Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 13 Jun 2026 16:09:26 +0000 Subject: [PATCH 2/7] [autofix.ci] apply automated fixes --- .../bun/spawn/pipe-reader-nested-tick.test.ts | 61 +++++++++---------- 1 file changed, 29 insertions(+), 32 deletions(-) diff --git a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts index 477da13c719c..ba7c23717433 100644 --- a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -32,38 +32,35 @@ import { isLinux } from "harness"; // One-shot pipe polls are the POSIX event-loop path; on Windows libuv drives // readiness. The deterministic repro relies on EPOLLONESHOT pipe readers, so gate // it to Linux like the sibling pidfd regression test. -test.skipIf(!isLinux)( - "a batch of Bun.$ commands survives a nested tick from one command's continuation", - async () => { - const N = 34; - let nested = false; +test.skipIf(!isLinux)("a batch of Bun.$ commands survives a nested tick from one command's continuation", async () => { + const N = 34; + let nested = false; - const cmds = Array.from({ length: N }, (_, i) => { - const cmd = Bun.$`printf %s out-${i}`.quiet(); - // The first command to settle runs this continuation inline, during the - // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on a - // promise here forces a nested us_loop_run_bun_tick; without the fix it - // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF - // events, which EPOLLONESHOT has already disarmed in the kernel. - cmd.then( - () => { - if (!nested) { - nested = true; - expect(Bun.sleep(1)).resolves.toBe(undefined); - } - }, - () => {}, - ); - return cmd; - }); + const cmds = Array.from({ length: N }, (_, i) => { + const cmd = Bun.$`printf %s out-${i}`.quiet(); + // The first command to settle runs this continuation inline, during the + // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on a + // promise here forces a nested us_loop_run_bun_tick; without the fix it + // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF + // events, which EPOLLONESHOT has already disarmed in the kernel. + cmd.then( + () => { + if (!nested) { + nested = true; + expect(Bun.sleep(1)).resolves.toBe(undefined); + } + }, + () => {}, + ); + return cmd; + }); - // With the dropped-slot bug, the commands whose pipe-EOF was skipped never - // finish and this hangs until the test times out. There is no other wake - // source for a disarmed one-shot pipe. - const results = await Promise.all(cmds); + // With the dropped-slot bug, the commands whose pipe-EOF was skipped never + // finish and this hangs until the test times out. There is no other wake + // source for a disarmed one-shot pipe. + const results = await Promise.all(cmds); - for (let i = 0; i < N; i++) { - expect(results[i].stdout.toString()).toBe(`out-${i}`); - } - }, -); + for (let i = 0; i < N; i++) { + expect(results[i].stdout.toString()).toBe(`out-${i}`); + } +}); From a5c3a1145c38d180dbad5ed56ac164a1bedbb289 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 13 Jun 2026 17:56:29 +0000 Subject: [PATCH 3/7] ci: retrigger From a841c0d3243c1f836463c796f30e3190394add2f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 1 Jul 2026 19:58:29 +0000 Subject: [PATCH 4/7] usockets: dispatch the outer ready-poll remainder before a nested tick overwrites it Replaces the snapshot/restore approach with the shape suggested in review: when us_loop_run_bun_tick detects it is nested inside a mid-iteration dispatch (current_ready_poll < num_ready_polls, which a completed dispatch never leaves true), it dispatches the outer batch's remaining entries before its own epoll_wait/kevent can overwrite them. A completed dispatch always leaves current_ready_poll == num_ready_polls, so once the remainder is drained, the nested tick leaving the counters in that state makes the outer for loop exit correctly instead of silently skipping. That postcondition also handles arbitrary nesting depth with no extra state: a drained callback that re-enters gets its own remainder drained the same way, and each enclosing frame exits on the same check as control unwinds. This does not introduce a new reentrancy class. Every still-ready level-triggered fd in the remainder is already re-reported by the nested epoll_wait and dispatched at the deeper level with the outer callback on the stack; the drain extends the same treatment to the one-shot entries the kernel has already disarmed and can never re-report. Callbacks that stop, change, or free a sibling poll are covered by us_internal_loop_update_pending_ready_polls exactly as in a flat dispatch. Because nothing of the outer batch is preserved across the nested tick, there is no saved copy for a FilePoll freed during the nested tick to dangle in, so the previous commits' invalidation machinery (us_loop_invalidate_ready_poll, its Rust FFI shim, the InternalLoopData field, and the FilePoll::deinit_possibly_defer hook) is removed along with the snapshot. On kqueue the coalescing pass is bounded to [start, n) so a pending kevent cannot merge into an already dispatched slot and get lost. The regression test is self-checking: from inside the continuation it asserts, via bun:internal-for-testing's event-loop stats (which now report the uws tick depth and the live batch's undispatched remainder), that it is running inline from a poll dispatch with undispatched siblings, and that a nested tick really ran, so a refactor of either mechanism it relies on fails the test instead of leaving it vacuously green. It runs on every POSIX platform: the pipe readers are one-shot on kqueue too (EV_DISPATCH), and macOS additionally still uses a one-shot EVFILT_PROC exit watch. --- .../bun-usockets/src/eventing/epoll_kqueue.c | 160 +++++++----------- packages/bun-usockets/src/internal/internal.h | 5 - .../bun-usockets/src/internal/loop_data.h | 4 - src/io/posix_event_loop.rs | 16 +- src/js/internal-for-testing.ts | 11 +- src/jsc/event_loop.rs | 28 ++- src/uws_sys/InternalLoopData.rs | 6 - src/uws_sys/Loop.rs | 22 --- .../bun/spawn/pipe-reader-nested-tick.test.ts | 133 +++++++++------ 9 files changed, 185 insertions(+), 200 deletions(-) diff --git a/packages/bun-usockets/src/eventing/epoll_kqueue.c b/packages/bun-usockets/src/eventing/epoll_kqueue.c index 230ab803f359..e26e43536dd5 100644 --- a/packages/bun-usockets/src/eventing/epoll_kqueue.c +++ b/packages/bun-usockets/src/eventing/epoll_kqueue.c @@ -52,37 +52,6 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout #endif #endif -/* A saved copy of an outer dispatch's ready-poll batch. us_loop_run_bun_tick - * re-enters itself (a poll callback calls waitForPromise -> autoTick), and the - * inner tick's epoll_wait/kevent overwrites the shared loop->ready_polls and - * its counters while the outer us_internal_dispatch_ready_polls is still - * mid-iteration. Without saving the outer batch, the outer loop resumes against - * the inner batch's data and silently skips its remaining events; for one-shot - * fds (pipe readers, pidfds) the kernel has already disarmed them, so a skipped - * event is lost forever and its owner waits for an event that never comes. - * Snapshots form a LIFO stack (loop->data.ready_poll_snapshots) so an - * arbitrarily nested tick protects every enclosing dispatch. */ -#ifdef LIBUS_USE_EPOLL -typedef struct epoll_event us_ready_poll_event_t; -#define GET_SNAPSHOT_POLL(snap, index) (struct us_poll_t *) (snap)->polls[index].data.ptr -#define SET_SNAPSHOT_POLL(snap, index, poll) (snap)->polls[index].data.ptr = (void*)poll -#else -typedef struct kevent64_s us_ready_poll_event_t; -#define GET_SNAPSHOT_POLL(snap, index) (struct us_poll_t *) (snap)->polls[index].udata -#if defined(__FreeBSD__) -#define SET_SNAPSHOT_POLL(snap, index, poll) (snap)->polls[index].udata = (void*)poll -#else -#define SET_SNAPSHOT_POLL(snap, index, poll) (snap)->polls[index].udata = (uint64_t)poll -#endif -#endif - -struct us_ready_poll_snapshot_t { - struct us_ready_poll_snapshot_t *outer; - int num; - int current; - us_ready_poll_event_t polls[]; -}; - /* Loop */ void us_loop_free(struct us_loop_t *loop) { us_internal_loop_data_free(loop); @@ -223,10 +192,16 @@ struct us_loop_t *us_create_loop(void *hint, void (*wakeup_cb)(struct us_loop_t return loop; } -/* Shared dispatch loop for both us_loop_run and us_loop_run_bun_tick */ -static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { +/* Shared dispatch loop for both us_loop_run and us_loop_run_bun_tick. + * + * `start` is the first index of ready_polls to dispatch. Every normal caller + * passes 0. A nested us_loop_run_bun_tick passes the interrupted outer + * dispatch's cursor + 1 so the outer batch's remaining entries run before the + * inner epoll_wait/kevent overwrites them (see the drain in + * us_loop_run_bun_tick). Always leaves current_ready_poll == num_ready_polls. */ +static void us_internal_dispatch_ready_polls_from(struct us_loop_t *loop, int start) { #ifdef LIBUS_USE_EPOLL - for (loop->current_ready_poll = 0; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { + for (loop->current_ready_poll = start; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { struct us_poll_t *poll = GET_READY_POLL(loop, loop->current_ready_poll); if (LIKELY(poll)) { if (CLEAR_POINTER_TAG(poll) != poll) { @@ -257,10 +232,22 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { }; _Static_assert(sizeof(struct kevent_flags) == 1, "kevent_flags must be 1 byte"); - struct kevent_flags coalesced[LIBUS_MAX_READY_POLLS]; /* no zeroing needed — every index is written in the first pass */ - - /* First pass: decode kevents and coalesce same-poll entries */ - for (int i = 0; i < loop->num_ready_polls; i++) { + struct kevent_flags coalesced[LIBUS_MAX_READY_POLLS]; /* no zeroing needed — every index in [start, n) is written in the first pass */ + + /* First pass: decode kevents and coalesce same-poll entries. + * + * The merge window is [start, n): entries below `start` were already + * dispatched by the interrupted outer pass, so merging into one would lose + * the event (its slot will never be dispatched again). The residual when + * start > 0 is the opposite direction and is benign: a socket whose two + * filters straddle `start` had the later one already folded into the + * earlier dispatch by the OUTER pass's (full-range) coalescing, and this + * pass re-dispatches the later filter on its own. If the earlier callback + * closed the socket, us_poll_stop nulled this slot and it is skipped; if + * not, it is one extra callback on a live level-triggered socket, which + * the next kevent() would deliver anyway. Tagged (FilePoll) entries never + * coalesce, so they are unaffected. */ + for (int i = start; i < loop->num_ready_polls; i++) { struct us_poll_t *poll = GET_READY_POLL(loop, i); if (!poll || CLEAR_POINTER_TAG(poll) != poll) { coalesced[i] = (struct kevent_flags){ .skip = 1 }; @@ -281,9 +268,10 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { }; /* Look backward for a prior entry with the same poll to coalesce into. - * Kqueue returns at most 2 kevents per fd (READ + WRITE). */ + * Kqueue returns at most 2 kevents per fd (READ + WRITE). Bounded by + * `start`: see the pass comment above. */ int merged = 0; - for (int j = i - 1; j >= 0; j--) { + for (int j = i - 1; j >= start; j--) { if (!coalesced[j].skip && GET_READY_POLL(loop, j) == poll) { coalesced[j].readable |= bits.readable; coalesced[j].writable |= bits.writable; @@ -300,7 +288,7 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { } /* Second pass: dispatch everything in order — tagged pointers and coalesced events */ - for (loop->current_ready_poll = 0; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { + for (loop->current_ready_poll = start; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { struct us_poll_t *poll = GET_READY_POLL(loop, loop->current_ready_poll); if (!poll) continue; @@ -324,6 +312,10 @@ static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { #endif } +static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { + us_internal_dispatch_ready_polls_from(loop, 0); +} + /* If the kernel filled our entire buffer, more events are likely already queued. * Re-poll non-blocking and dispatch again before running pre/post callbacks, so a * single tick covers all pending I/O instead of one 1024-event slice per roundtrip. @@ -383,24 +375,39 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout loop->data.tick_depth++; - /* current_ready_poll < num_ready_polls is true only while an outer + /* current_ready_poll < num_ready_polls holds only while an outer * us_internal_dispatch_ready_polls is mid-iteration (a completed dispatch - * leaves them equal). So it means this is a nested tick, and the epoll_wait - * below is about to clobber the outer batch. Save it (and its cursor) now - * and restore it before we return so the outer dispatch resumes intact. On - * allocation failure we skip the snapshot and degrade to the old - * event-dropping behavior rather than crash. */ - struct us_ready_poll_snapshot_t *outer_snapshot = NULL; + * always leaves them equal), i.e. we are a nested tick: a poll callback + * re-entered us_loop_run_bun_tick (e.g. via waitForPromise -> autoTick). + * The epoll_wait/kevent below is about to overwrite the shared ready_polls + * and its counters, which would silently skip the outer batch's remaining + * entries. For a level-triggered fd that is harmless (the kernel reports + * it again), but a one-shot fd (EPOLLONESHOT / EV_DISPATCH pipe readers, + * EV_ONESHOT EVFILT_PROC on macOS) was already disarmed by the kernel, so + * a skipped entry is lost forever and its owner waits for an event that + * never comes. + * + * Dispatch the outer remainder now, before it is overwritten. This does + * not introduce a new reentrancy class: every still-ready level-triggered + * fd in that remainder would be re-reported by our epoll_wait below and + * dispatched at this depth anyway, with the outer callback on the stack; + * we just extend the same treatment to the one-shot entries the kernel + * can no longer re-report. Callbacks that stop/change/free a sibling poll + * are covered by us_internal_loop_update_pending_ready_polls exactly as in + * a flat dispatch (its [current_ready_poll, num) window is our cursor), + * and closed sockets stay deferred to the outermost loop_post because + * tick_depth is already >= 2 here. + * + * Afterwards current_ready_poll == num_ready_polls, which is the outer + * for-loop's normal exit state, so when we return the outer dispatch + * terminates correctly instead of skipping. That postcondition also makes + * this recurse cleanly: if one of the drained callbacks re-enters, the + * deeper tick drains *our* remainder the same way, and each enclosing + * frame exits on the same check when control unwinds. Nothing depends on + * the remainder running at the outer depth (level-triggered entries + * already did not). */ if (loop->current_ready_poll < loop->num_ready_polls) { - int saved_num = loop->num_ready_polls; - outer_snapshot = us_malloc(sizeof(*outer_snapshot) + (size_t) saved_num * sizeof(outer_snapshot->polls[0])); - if (outer_snapshot) { - outer_snapshot->num = saved_num; - outer_snapshot->current = loop->current_ready_poll; - memcpy(outer_snapshot->polls, loop->ready_polls, (size_t) saved_num * sizeof(outer_snapshot->polls[0])); - outer_snapshot->outer = loop->data.ready_poll_snapshots; - loop->data.ready_poll_snapshots = outer_snapshot; - } + us_internal_dispatch_ready_polls_from(loop, loop->current_ready_poll + 1); } struct us_internal_callback_t *timer_callback = (struct us_internal_callback_t*)loop->data.sweep_timer; @@ -459,18 +466,6 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout /* Emit post callback */ us_internal_loop_post(loop); - - /* Restore the outer batch we clobbered (entries a nested free nulled out - * are preserved). Pop before tick_depth-- so it is gone once this frame is - * no longer on the stack. */ - if (outer_snapshot) { - memcpy(loop->ready_polls, outer_snapshot->polls, (size_t) outer_snapshot->num * sizeof(outer_snapshot->polls[0])); - loop->num_ready_polls = outer_snapshot->num; - loop->current_ready_poll = outer_snapshot->current; - loop->data.ready_poll_snapshots = outer_snapshot->outer; - us_free(outer_snapshot); - } - loop->data.tick_depth--; } @@ -495,33 +490,6 @@ void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop, struct num_entries_possibly_remaining--; } } - - /* A poll freed/changed while a nested tick is live must also be fixed up in - * the saved outer batches, or the outer dispatch re-dispatches a stale - * (freed) entry when it resumes. Each buffer holds the poll at most once - * (epoll) or twice (kqueue), same as the live buffer above. */ - for (struct us_ready_poll_snapshot_t *snap = loop->data.ready_poll_snapshots; snap; snap = snap->outer) { -#ifdef LIBUS_USE_EPOLL - int remaining = 1; -#else - int remaining = 2; -#endif - for (int i = snap->current; i < snap->num && remaining; i++) { - if (GET_SNAPSHOT_POLL(snap, i) == old_poll) { - SET_SNAPSHOT_POLL(snap, i, new_poll); - remaining--; - } - } - } -} - -/* Drop `poll` from the live ready-poll batch and every saved outer-batch - * snapshot so it is never dispatched after being freed. us_poll_stop/change - * already do this for uSockets sockets via us_internal_loop_update_pending_ - * ready_polls; Bun's FilePolls are torn down on the Rust side and call this so - * they get the same protection across nested ticks. */ -void us_loop_invalidate_ready_poll(struct us_loop_t *loop, void *poll) { - us_internal_loop_update_pending_ready_polls(loop, (struct us_poll_t *) poll, NULL, 0, 0); } /* Poll */ diff --git a/packages/bun-usockets/src/internal/internal.h b/packages/bun-usockets/src/internal/internal.h index b30e8914428f..014d925fcc55 100644 --- a/packages/bun-usockets/src/internal/internal.h +++ b/packages/bun-usockets/src/internal/internal.h @@ -49,11 +49,6 @@ void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop, struct us_poll_t *new_poll, int old_events, int new_events); - -/* Drop `poll` from the live ready-poll batch and every saved outer-batch - * snapshot. Called from Bun's Rust FilePoll teardown so a FilePoll freed - * mid-dispatch (or mid-nested-tick) is never re-dispatched from a stale entry. */ -void us_loop_invalidate_ready_poll(struct us_loop_t *loop, void *poll); #endif /* We only have one networking implementation so far */ diff --git a/packages/bun-usockets/src/internal/loop_data.h b/packages/bun-usockets/src/internal/loop_data.h index 9885d4ff6d84..801649b2d1f8 100644 --- a/packages/bun-usockets/src/internal/loop_data.h +++ b/packages/bun-usockets/src/internal/loop_data.h @@ -80,10 +80,6 @@ struct us_internal_loop_data_t { * sockets must be deferred to the outermost tick so the outer dispatch * doesn't read a freed poll. */ int tick_depth; - /* LIFO stack of saved outer ready-poll batches, one per active nested - * us_loop_run_bun_tick (struct us_ready_poll_snapshot_t, defined in - * epoll_kqueue.c). NULL when no nested tick is in flight. */ - void *ready_poll_snapshots; }; #endif // LOOP_DATA_H diff --git a/src/io/posix_event_loop.rs b/src/io/posix_event_loop.rs index a83122764400..942da6b2d8d8 100644 --- a/src/io/posix_event_loop.rs +++ b/src/io/posix_event_loop.rs @@ -411,27 +411,13 @@ impl FilePoll { } fn deinit_possibly_defer(&mut self, vm: EventLoopCtx, force_unregister: bool) { - // `unregister` below only drops us from the kernel; it does not touch - // `loop->ready_polls`. If we are being torn down while a dispatch (or a - // nested tick) is mid-iteration over that batch, the outer loop would - // re-dispatch our now-freed slot. Drop ourselves from the live batch - // and every saved outer snapshot first, while `self` is still valid. - // Only a registered poll can appear in a batch, and `unregister` leaves - // `WasEverRegistered` set, so this read is stable across it. - let was_ever_registered = self.flags.contains(Flags::WasEverRegistered); - if was_ever_registered { - let tagged = Pollable::init(self).ptr(); - // SAFETY: `loop_()` is the live C-owned uws loop; `tagged` is the - // exact tagged pointer stored in `ready_polls` for this FilePoll. - unsafe { Loop::invalidate_ready_poll(vm.loop_(), tagged) }; - } - // `loop_mut()` is the crate-private nonnull-asref accessor (single // deref in `EventLoopCtx`); the `&mut Loop` is consumed by `unregister` // and dropped before any `&mut Store` is materialised. let _ = self.unregister(vm.loop_mut(), force_unregister); self.owner.clear(); + let was_ever_registered = self.flags.contains(Flags::WasEverRegistered); self.flags = FlagsSet::empty(); self.fd = INVALID_FD; // `self` may live inside the `Store.hive` inline array, so a diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index 10064f1f8b30..8e60aa3b2d61 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -279,8 +279,15 @@ export const lowercaseHeaderNameSIMD: (name: string) => string = $newCppFunction 1, ); -export const getEventLoopStats: () => { activeTasks: number; concurrentRef: number; numPolls: number } = - $newZigFunction("event_loop.zig", "getActiveTasks", 0); +export const getEventLoopStats: () => { + activeTasks: number; + concurrentRef: number; + numPolls: number; + /** Reentrancy depth of `us_loop_run_bun_tick`; >= 1 when called from inside a poll-dispatch callback. Always 0 on Windows. */ + tickDepth: number; + /** Undispatched entries remaining in the live ready-poll batch after the one being dispatched. Always 0 on Windows. */ + pendingReadyPolls: number; +} = $newZigFunction("event_loop.zig", "getActiveTasks", 0); export const hostedGitInfo = { parseUrl: $newZigFunction("hosted_git_info.zig", "TestingAPIs.jsParseUrl", 1), diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index eefced1e6374..b1c597029ff8 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1229,7 +1229,7 @@ pub fn get_active_tasks(global_object: &JSGlobalObject, _frame: &CallFrame) -> J // fields and call &-methods on it for the duration of this host fn. let vm_ref = global_object.bun_vm(); let event_loop = vm_ref.event_loop_shared(); - let result = JSValue::create_empty_object(global_object, 3); + let result = JSValue::create_empty_object(global_object, 5); result.put( global_object, b"activeTasks", @@ -1245,14 +1245,38 @@ pub fn get_active_tasks(global_object: &JSGlobalObject, _frame: &CallFrame) -> J let num_polls: i32 = i32::try_from(unsafe { (*bun_sys::windows::libuv::Loop::get()).active_handles }) .expect("int cast"); + // `tick_depth` and the ready-poll cursor only exist on the POSIX uws loop; + // the libuv loop drives readiness on Windows, so report them as 0 there. + #[cfg(windows)] + let (tick_depth, pending_ready_polls): (i32, i32) = (0, 0); #[cfg(not(windows))] // SAFETY: uws::Loop::get() returns a live process-global loop. - let num_polls: i32 = unsafe { (*uws::Loop::get()).num_polls }; + let (num_polls, tick_depth, pending_ready_polls): (i32, i32, i32) = unsafe { + let loop_ = &*uws::Loop::get(); + ( + loop_.num_polls, + loop_.internal_loop_data.tick_depth, + // Undispatched entries after the one currently being dispatched. + // > 0 only from inside a poll callback with remaining siblings in + // its batch; a completed dispatch leaves current == num. + (loop_.num_ready_polls - loop_.current_ready_poll - 1).max(0), + ) + }; result.put( global_object, b"numPolls", JSValue::js_number(num_polls as f64), ); + result.put( + global_object, + b"tickDepth", + JSValue::js_number(tick_depth as f64), + ); + result.put( + global_object, + b"pendingReadyPolls", + JSValue::js_number(pending_ready_polls as f64), + ); Ok(result) } diff --git a/src/uws_sys/InternalLoopData.rs b/src/uws_sys/InternalLoopData.rs index 9ff3fee3bdbf..74df8437d991 100644 --- a/src/uws_sys/InternalLoopData.rs +++ b/src/uws_sys/InternalLoopData.rs @@ -55,12 +55,6 @@ pub struct InternalLoopData { // Higher tier (`bun_runtime`) casts this back when reading. pub jsc_vm: *const c_void, pub tick_depth: c_int, - /// LIFO stack of saved outer ready-poll batches (C - /// `struct us_ready_poll_snapshot_t`), one per active nested - /// `us_loop_run_bun_tick`. Owned and manipulated entirely on the C side; - /// mirrored here only so `InternalLoopData`'s size matches the C struct - /// (the `PosixLoop` layout assertions key `num_polls`' offset off it). - pub ready_poll_snapshots: *mut c_void, } impl InternalLoopData { diff --git a/src/uws_sys/Loop.rs b/src/uws_sys/Loop.rs index 5779cee4acc9..8a6a20a8320b 100644 --- a/src/uws_sys/Loop.rs +++ b/src/uws_sys/Loop.rs @@ -138,26 +138,6 @@ impl PosixLoop { self.ready_polls[idx] } - /// Drop `poll` (a tagged `FilePoll` pointer) from the live ready-poll batch - /// and every saved outer-batch snapshot, so a `FilePoll` torn down - /// mid-dispatch is never re-dispatched from a stale `ready_polls` entry. - /// The uSockets socket path does this via - /// `us_internal_loop_update_pending_ready_polls`; `FilePoll`s are freed on - /// the Rust side and route through here for the same protection. - /// - /// Takes `this: *mut Self` (not `&mut self`): callers hold the C-owned loop - /// as a raw pointer and the C callee touches the same loop, so a `&mut` - /// reborrow would be the noalias hazard `mod c` documents. - /// - /// # Safety - /// `this` must be the live C-allocated loop pointer; `poll` is the tagged - /// pointer stored in `ready_polls`. - #[inline] - pub unsafe fn invalidate_ready_poll(this: *mut Self, poll: *mut c_void) { - // SAFETY: per fn contract. - unsafe { c::us_loop_invalidate_ready_poll(this, poll) }; - } - pub fn inc(&mut self) { bun_core::scoped_log!(Loop, "inc {} + 1 = {}", self.num_polls, self.num_polls + 1); self.num_polls += 1; @@ -660,8 +640,6 @@ mod c { pub(super) fn uws_loop_addPreHandler(loop_: *mut Loop, ctx: *mut c_void, cb: LoopCtxCb); #[cfg(not(windows))] pub(super) fn us_loop_run_bun_tick(loop_: *mut Loop, timeout_ms: *const Timespec); - #[cfg(not(windows))] - pub(super) fn us_loop_invalidate_ready_poll(loop_: *mut Loop, poll: *mut c_void); pub(super) fn us_internal_free_closed_sockets(loop_: *mut Loop); pub(super) fn us_loop_close_all_groups(loop_: *mut Loop) -> c_int; #[cfg(not(windows))] diff --git a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts index ba7c23717433..fc4b144254be 100644 --- a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -1,13 +1,13 @@ -// A subprocess stdout/stderr pipe reader is registered one-shot on Linux -// (EPOLLONESHOT, via OneShotFlag::Dispatch). When the reader's readable/EOF -// event is dropped in user-space after epoll_wait has already returned it, the -// kernel has disarmed the fd and nothing re-arms it: `onUpdate` (which sets the -// re-arm flag) never ran. The output is then never read and the consumer waits -// forever. +// A subprocess stdout/stderr pipe reader is registered one-shot on every POSIX +// platform (`OneShotFlag::Dispatch`: EPOLLONESHOT on Linux, EV_DISPATCH on +// kqueue). When the reader's readable/EOF event is dropped in user-space after +// epoll_wait/kevent has already returned it, the kernel has disarmed the fd and +// nothing re-arms it: `onUpdate` (which sets the re-arm flag) never ran. The +// output is then never read and its consumer waits forever. // -// The drop happens when a poll callback re-enters us_loop_run_bun_tick while the -// outer us_internal_dispatch_ready_polls is still iterating the batch. The inner -// tick runs epoll_wait again, overwriting the shared loop->ready_polls / +// The drop happens when a poll callback re-enters us_loop_run_bun_tick while +// the outer us_internal_dispatch_ready_polls is still iterating the batch. The +// inner tick's epoll_wait/kevent overwrites the shared loop->ready_polls / // num_ready_polls / current_ready_poll, so the outer loop resumes against the // inner batch and silently skips its own remaining events. // @@ -16,51 +16,88 @@ // drains microtasks inline, running the command's .then continuation *during* // the poll dispatch. If that continuation synchronously waits on a promise // (waitForPromise -> autoTick), the nested tick clobbers the batch and sibling -// commands' one-shot pipe-EOF events are lost. The command's shell never sees -// EOF, so its promise never resolves. +// commands' one-shot pipe-EOF events are lost. Those commands' shells never see +// EOF, so their promises never resolve. // -// PR #30301 fixed this for the pidfd by making it level-triggered, but left the -// pipe readers one-shot and assumed a dropped pipe event is reported again via -// EPOLLHUP on the next wait. It is not: a disarmed EPOLLONESHOT fd reports -// nothing until it is re-armed, which never happens. +// PR #30301 fixed the same batch corruption for the Linux pidfd by making it +// level-triggered, but left the pipe readers one-shot and assumed a dropped +// pipe event is reported again via EPOLLHUP on the next wait. It is not: a +// disarmed one-shot fd reports nothing until it is re-armed, which never +// happens. On macOS the process-exit watch (EVFILT_PROC) is also still +// one-shot, so the batch corruption loses exit events there too. // -// Fix: us_loop_run_bun_tick snapshots the outer ready-poll batch before a nested -// tick can clobber it and restores it afterward, so no one-shot event is dropped. +// Fix: when us_loop_run_bun_tick detects it is nested inside a mid-iteration +// dispatch, it dispatches the outer batch's remaining entries before its own +// epoll_wait/kevent can overwrite them, so no one-shot event is dropped. import { expect, test } from "bun:test"; -import { isLinux } from "harness"; +import { getEventLoopStats } from "bun:internal-for-testing"; +import { isWindows } from "harness"; -// One-shot pipe polls are the POSIX event-loop path; on Windows libuv drives -// readiness. The deterministic repro relies on EPOLLONESHOT pipe readers, so gate -// it to Linux like the sibling pidfd regression test. -test.skipIf(!isLinux)("a batch of Bun.$ commands survives a nested tick from one command's continuation", async () => { - const N = 34; - let nested = false; +// The uws ready-poll batch only exists on the POSIX event loop; on Windows +// libuv drives readiness through a different path (and the stats below read 0). +test.skipIf(isWindows)( + "a batch of Bun.$ commands survives a nested tick from one command's continuation", + async () => { + const N = 34; + let nested = false; + // Captured from inside the first continuation to run, then asserted after + // the batch settles. They make the trigger self-checking: if either + // implementation detail this test leans on is refactored away, these fail + // loudly instead of leaving the test vacuously green against a broken + // event loop. + let tickDepthInContinuation = -1; + let pendingSiblingsInContinuation = -1; + let sawNestedTick = false; - const cmds = Array.from({ length: N }, (_, i) => { - const cmd = Bun.$`printf %s out-${i}`.quiet(); - // The first command to settle runs this continuation inline, during the - // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on a - // promise here forces a nested us_loop_run_bun_tick; without the fix it - // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF - // events, which EPOLLONESHOT has already disarmed in the kernel. - cmd.then( - () => { - if (!nested) { + const cmds = Array.from({ length: N }, (_, i) => { + const cmd = Bun.$`printf %s out-${i}`.quiet(); + // The first command to settle runs this continuation inline, during the + // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on + // a promise here forces a nested us_loop_run_bun_tick; without the fix it + // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF + // events, which the kernel has already disarmed. + cmd.then( + () => { + if (nested) return; nested = true; + + // Precondition 1: we really are running inline from inside a poll + // dispatch (tickDepth >= 1) with undispatched sibling events still in + // the live batch (pendingReadyPolls > 0). If finish() stops draining + // microtasks inline, tickDepth reads 0 here. If the continuation no + // longer lands inside the batch that holds the siblings' events, + // pendingReadyPolls reads 0. Either way the test fails instead of + // silently not exercising the bug. + const stats = getEventLoopStats(); + tickDepthInContinuation = stats.tickDepth; + pendingSiblingsInContinuation = stats.pendingReadyPolls; + + // Precondition 2: a nested tick actually runs before this + // continuation returns. Bun.sleep(0)'s continuation can only have run + // by the time the synchronous wait below returns if an event-loop + // tick ran inside it. If expect().resolves stops blocking + // synchronously, `sawNestedTick` is still false right afterwards. + Bun.sleep(0).then(() => { + sawNestedTick = true; + }); expect(Bun.sleep(1)).resolves.toBe(undefined); - } - }, - () => {}, - ); - return cmd; - }); + }, + () => {}, + ); + return cmd; + }); + + // With the dropped-slot bug, the commands whose pipe-EOF was skipped never + // finish and this hangs until the test times out. There is no other wake + // source for a disarmed one-shot pipe. + const results = await Promise.all(cmds); - // With the dropped-slot bug, the commands whose pipe-EOF was skipped never - // finish and this hangs until the test times out. There is no other wake - // source for a disarmed one-shot pipe. - const results = await Promise.all(cmds); + expect(tickDepthInContinuation).toBeGreaterThanOrEqual(1); + expect(pendingSiblingsInContinuation).toBeGreaterThan(0); + expect(sawNestedTick).toBe(true); - for (let i = 0; i < N; i++) { - expect(results[i].stdout.toString()).toBe(`out-${i}`); - } -}); + for (let i = 0; i < N; i++) { + expect(results[i].stdout.toString()).toBe(`out-${i}`); + } + }, +); From f600a09c2a27fc82f3673da3d53360191155dbe0 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 1 Jul 2026 20:18:24 +0000 Subject: [PATCH 5/7] [autofix.ci] apply automated fixes --- .../bun/spawn/pipe-reader-nested-tick.test.ts | 119 +++++++++--------- 1 file changed, 58 insertions(+), 61 deletions(-) diff --git a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts index fc4b144254be..8a3df7296bec 100644 --- a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -29,75 +29,72 @@ // Fix: when us_loop_run_bun_tick detects it is nested inside a mid-iteration // dispatch, it dispatches the outer batch's remaining entries before its own // epoll_wait/kevent can overwrite them, so no one-shot event is dropped. -import { expect, test } from "bun:test"; import { getEventLoopStats } from "bun:internal-for-testing"; +import { expect, test } from "bun:test"; import { isWindows } from "harness"; // The uws ready-poll batch only exists on the POSIX event loop; on Windows // libuv drives readiness through a different path (and the stats below read 0). -test.skipIf(isWindows)( - "a batch of Bun.$ commands survives a nested tick from one command's continuation", - async () => { - const N = 34; - let nested = false; - // Captured from inside the first continuation to run, then asserted after - // the batch settles. They make the trigger self-checking: if either - // implementation detail this test leans on is refactored away, these fail - // loudly instead of leaving the test vacuously green against a broken - // event loop. - let tickDepthInContinuation = -1; - let pendingSiblingsInContinuation = -1; - let sawNestedTick = false; +test.skipIf(isWindows)("a batch of Bun.$ commands survives a nested tick from one command's continuation", async () => { + const N = 34; + let nested = false; + // Captured from inside the first continuation to run, then asserted after + // the batch settles. They make the trigger self-checking: if either + // implementation detail this test leans on is refactored away, these fail + // loudly instead of leaving the test vacuously green against a broken + // event loop. + let tickDepthInContinuation = -1; + let pendingSiblingsInContinuation = -1; + let sawNestedTick = false; - const cmds = Array.from({ length: N }, (_, i) => { - const cmd = Bun.$`printf %s out-${i}`.quiet(); - // The first command to settle runs this continuation inline, during the - // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on - // a promise here forces a nested us_loop_run_bun_tick; without the fix it - // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF - // events, which the kernel has already disarmed. - cmd.then( - () => { - if (nested) return; - nested = true; + const cmds = Array.from({ length: N }, (_, i) => { + const cmd = Bun.$`printf %s out-${i}`.quiet(); + // The first command to settle runs this continuation inline, during the + // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on + // a promise here forces a nested us_loop_run_bun_tick; without the fix it + // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF + // events, which the kernel has already disarmed. + cmd.then( + () => { + if (nested) return; + nested = true; - // Precondition 1: we really are running inline from inside a poll - // dispatch (tickDepth >= 1) with undispatched sibling events still in - // the live batch (pendingReadyPolls > 0). If finish() stops draining - // microtasks inline, tickDepth reads 0 here. If the continuation no - // longer lands inside the batch that holds the siblings' events, - // pendingReadyPolls reads 0. Either way the test fails instead of - // silently not exercising the bug. - const stats = getEventLoopStats(); - tickDepthInContinuation = stats.tickDepth; - pendingSiblingsInContinuation = stats.pendingReadyPolls; + // Precondition 1: we really are running inline from inside a poll + // dispatch (tickDepth >= 1) with undispatched sibling events still in + // the live batch (pendingReadyPolls > 0). If finish() stops draining + // microtasks inline, tickDepth reads 0 here. If the continuation no + // longer lands inside the batch that holds the siblings' events, + // pendingReadyPolls reads 0. Either way the test fails instead of + // silently not exercising the bug. + const stats = getEventLoopStats(); + tickDepthInContinuation = stats.tickDepth; + pendingSiblingsInContinuation = stats.pendingReadyPolls; - // Precondition 2: a nested tick actually runs before this - // continuation returns. Bun.sleep(0)'s continuation can only have run - // by the time the synchronous wait below returns if an event-loop - // tick ran inside it. If expect().resolves stops blocking - // synchronously, `sawNestedTick` is still false right afterwards. - Bun.sleep(0).then(() => { - sawNestedTick = true; - }); - expect(Bun.sleep(1)).resolves.toBe(undefined); - }, - () => {}, - ); - return cmd; - }); + // Precondition 2: a nested tick actually runs before this + // continuation returns. Bun.sleep(0)'s continuation can only have run + // by the time the synchronous wait below returns if an event-loop + // tick ran inside it. If expect().resolves stops blocking + // synchronously, `sawNestedTick` is still false right afterwards. + Bun.sleep(0).then(() => { + sawNestedTick = true; + }); + expect(Bun.sleep(1)).resolves.toBe(undefined); + }, + () => {}, + ); + return cmd; + }); - // With the dropped-slot bug, the commands whose pipe-EOF was skipped never - // finish and this hangs until the test times out. There is no other wake - // source for a disarmed one-shot pipe. - const results = await Promise.all(cmds); + // With the dropped-slot bug, the commands whose pipe-EOF was skipped never + // finish and this hangs until the test times out. There is no other wake + // source for a disarmed one-shot pipe. + const results = await Promise.all(cmds); - expect(tickDepthInContinuation).toBeGreaterThanOrEqual(1); - expect(pendingSiblingsInContinuation).toBeGreaterThan(0); - expect(sawNestedTick).toBe(true); + expect(tickDepthInContinuation).toBeGreaterThanOrEqual(1); + expect(pendingSiblingsInContinuation).toBeGreaterThan(0); + expect(sawNestedTick).toBe(true); - for (let i = 0; i < N; i++) { - expect(results[i].stdout.toString()).toBe(`out-${i}`); - } - }, -); + for (let i = 0; i < N; i++) { + expect(results[i].stdout.toString()).toBe(`out-${i}`); + } +}); From eca4e42ceb5909537e6a1865f5699ccdc1a71a4e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 1 Jul 2026 20:53:52 +0000 Subject: [PATCH 6/7] usockets: adopt the reviewed drain implementation Takes the implementation and test from review verbatim. Beyond shortening the comments and dropping the _from wrapper, it fixes a liveness bug in the previous revision: after dispatching the outer remainder, the nested tick must not idle on the timeout its caller computed before the drained callbacks ran, since one of them may have settled the very promise the caller is waiting on. Poll with a zero timeout instead. Also reverts the getEventLoopStats additions (tickDepth, pendingReadyPolls): the replacement test does not use them. --- .../bun-usockets/src/eventing/epoll_kqueue.c | 100 ++++---------- src/js/internal-for-testing.ts | 11 +- src/jsc/event_loop.rs | 28 +--- .../bun/spawn/pipe-reader-nested-tick.test.ts | 129 +++++++----------- 4 files changed, 82 insertions(+), 186 deletions(-) diff --git a/packages/bun-usockets/src/eventing/epoll_kqueue.c b/packages/bun-usockets/src/eventing/epoll_kqueue.c index d159cf59384c..b3ab0be3da64 100644 --- a/packages/bun-usockets/src/eventing/epoll_kqueue.c +++ b/packages/bun-usockets/src/eventing/epoll_kqueue.c @@ -52,6 +52,8 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout #endif #endif +static const struct timespec us_zero_timespec = {0, 0}; + /* Loop */ void us_loop_free(struct us_loop_t *loop) { us_internal_loop_data_free(loop); @@ -192,16 +194,12 @@ struct us_loop_t *us_create_loop(void *hint, void (*wakeup_cb)(struct us_loop_t return loop; } -/* Shared dispatch loop for both us_loop_run and us_loop_run_bun_tick. - * - * `start` is the first index of ready_polls to dispatch. Every normal caller - * passes 0. A nested us_loop_run_bun_tick passes the interrupted outer - * dispatch's cursor + 1 so the outer batch's remaining entries run before the - * inner epoll_wait/kevent overwrites them (see the drain in - * us_loop_run_bun_tick). Always leaves current_ready_poll == num_ready_polls. */ -static void us_internal_dispatch_ready_polls_from(struct us_loop_t *loop, int start) { +/* Shared dispatch loop for both us_loop_run and us_loop_run_bun_tick. A fresh + * batch passes first_index 0; a nested tick passes the first not-yet-dispatched + * index so it finishes the outer remainder before its own wait overwrites it. */ +static void us_internal_dispatch_ready_polls(struct us_loop_t *loop, int first_index) { #ifdef LIBUS_USE_EPOLL - for (loop->current_ready_poll = start; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { + for (loop->current_ready_poll = first_index; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { struct us_poll_t *poll = GET_READY_POLL(loop, loop->current_ready_poll); if (LIKELY(poll)) { if (CLEAR_POINTER_TAG(poll) != poll) { @@ -235,22 +233,14 @@ static void us_internal_dispatch_ready_polls_from(struct us_loop_t *loop, int st }; _Static_assert(sizeof(struct kevent_flags) == 1, "kevent_flags must be 1 byte"); - struct kevent_flags coalesced[LIBUS_MAX_READY_POLLS]; /* no zeroing needed — every index in [start, n) is written in the first pass */ - - /* First pass: decode kevents and coalesce same-poll entries. - * - * The merge window is [start, n): entries below `start` were already - * dispatched by the interrupted outer pass, so merging into one would lose - * the event (its slot will never be dispatched again). The residual when - * start > 0 is the opposite direction and is benign: a socket whose two - * filters straddle `start` had the later one already folded into the - * earlier dispatch by the OUTER pass's (full-range) coalescing, and this - * pass re-dispatches the later filter on its own. If the earlier callback - * closed the socket, us_poll_stop nulled this slot and it is skipped; if - * not, it is one extra callback on a live level-triggered socket, which - * the next kevent() would deliver anyway. Tagged (FilePoll) entries never - * coalesce, so they are unaffected. */ - for (int i = start; i < loop->num_ready_polls; i++) { + struct kevent_flags coalesced[LIBUS_MAX_READY_POLLS]; /* no zeroing needed — every index in [first_index, n) is written in the first pass */ + + /* First pass: decode kevents and coalesce same-poll entries. Bounded to + * [first_index, n): consumed entries are never consulted (they may hold + * freed polls). A pair straddling first_index dispatches once from each + * side; level-triggered sockets already tolerate that (spurious wakeups), + * and a poll closed by the first delivery has its later entries nulled. */ + for (int i = first_index; i < loop->num_ready_polls; i++) { struct us_poll_t *poll = GET_READY_POLL(loop, i); if (!poll || CLEAR_POINTER_TAG(poll) != poll) { coalesced[i] = (struct kevent_flags){ .skip = 1 }; @@ -271,10 +261,9 @@ static void us_internal_dispatch_ready_polls_from(struct us_loop_t *loop, int st }; /* Look backward for a prior entry with the same poll to coalesce into. - * Kqueue returns at most 2 kevents per fd (READ + WRITE). Bounded by - * `start`: see the pass comment above. */ + * Kqueue returns at most 2 kevents per fd (READ + WRITE). */ int merged = 0; - for (int j = i - 1; j >= start; j--) { + for (int j = i - 1; j >= first_index; j--) { if (!coalesced[j].skip && GET_READY_POLL(loop, j) == poll) { coalesced[j].readable |= bits.readable; coalesced[j].writable |= bits.writable; @@ -291,7 +280,7 @@ static void us_internal_dispatch_ready_polls_from(struct us_loop_t *loop, int st } /* Second pass: dispatch everything in order — tagged pointers and coalesced events */ - for (loop->current_ready_poll = start; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { + for (loop->current_ready_poll = first_index; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) { struct us_poll_t *poll = GET_READY_POLL(loop, loop->current_ready_poll); if (!poll) continue; @@ -315,10 +304,6 @@ static void us_internal_dispatch_ready_polls_from(struct us_loop_t *loop, int st #endif } -static void us_internal_dispatch_ready_polls(struct us_loop_t *loop) { - us_internal_dispatch_ready_polls_from(loop, 0); -} - /* If the kernel filled our entire buffer, more events are likely already queued. * Re-poll non-blocking and dispatch again before running pre/post callbacks, so a * single tick covers all pending I/O instead of one 1024-event slice per roundtrip. @@ -328,8 +313,7 @@ static void us_internal_drain_ready_polls(struct us_loop_t *loop) { int drain_count = 48; while (UNLIKELY(loop->num_ready_polls == LIBUS_MAX_READY_POLLS) && --drain_count != 0 && loop->num_polls > 0) { #ifdef LIBUS_USE_EPOLL - static const struct timespec zero = {0, 0}; - loop->num_ready_polls = bun_epoll_pwait2(loop->fd, loop->ready_polls, LIBUS_MAX_READY_POLLS, &zero); + loop->num_ready_polls = bun_epoll_pwait2(loop->fd, loop->ready_polls, LIBUS_MAX_READY_POLLS, &us_zero_timespec); #else do { loop->num_ready_polls = kevent64(loop->fd, NULL, 0, loop->ready_polls, LIBUS_MAX_READY_POLLS, KEVENT_FLAG_IMMEDIATE, NULL); @@ -339,7 +323,7 @@ static void us_internal_drain_ready_polls(struct us_loop_t *loop) { loop->num_ready_polls = 0; break; } - us_internal_dispatch_ready_polls(loop); + us_internal_dispatch_ready_polls(loop, 0); } } @@ -361,7 +345,7 @@ void us_loop_run(struct us_loop_t *loop) { } while (IS_EINTR(loop->num_ready_polls)); #endif - us_internal_dispatch_ready_polls(loop); + us_internal_dispatch_ready_polls(loop, 0); us_internal_drain_ready_polls(loop); /* Emit post callback */ @@ -378,39 +362,15 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout loop->data.tick_depth++; - /* current_ready_poll < num_ready_polls holds only while an outer - * us_internal_dispatch_ready_polls is mid-iteration (a completed dispatch - * always leaves them equal), i.e. we are a nested tick: a poll callback - * re-entered us_loop_run_bun_tick (e.g. via waitForPromise -> autoTick). - * The epoll_wait/kevent below is about to overwrite the shared ready_polls - * and its counters, which would silently skip the outer batch's remaining - * entries. For a level-triggered fd that is harmless (the kernel reports - * it again), but a one-shot fd (EPOLLONESHOT / EV_DISPATCH pipe readers, - * EV_ONESHOT EVFILT_PROC on macOS) was already disarmed by the kernel, so - * a skipped entry is lost forever and its owner waits for an event that - * never comes. - * - * Dispatch the outer remainder now, before it is overwritten. This does - * not introduce a new reentrancy class: every still-ready level-triggered - * fd in that remainder would be re-reported by our epoll_wait below and - * dispatched at this depth anyway, with the outer callback on the stack; - * we just extend the same treatment to the one-shot entries the kernel - * can no longer re-report. Callbacks that stop/change/free a sibling poll - * are covered by us_internal_loop_update_pending_ready_polls exactly as in - * a flat dispatch (its [current_ready_poll, num) window is our cursor), - * and closed sockets stay deferred to the outermost loop_post because - * tick_depth is already >= 2 here. - * - * Afterwards current_ready_poll == num_ready_polls, which is the outer - * for-loop's normal exit state, so when we return the outer dispatch - * terminates correctly instead of skipping. That postcondition also makes - * this recurse cleanly: if one of the drained callbacks re-enters, the - * deeper tick drains *our* remainder the same way, and each enclosing - * frame exits on the same check when control unwinds. Nothing depends on - * the remainder running at the outer depth (level-triggered entries - * already did not). */ + /* A poll callback re-entered the event loop mid-dispatch: the wait below + * overwrites ready_polls, dropping the outer batch's remaining events — + * unrecoverable for one-shot fds. Dispatch the remainder before that. */ if (loop->current_ready_poll < loop->num_ready_polls) { - us_internal_dispatch_ready_polls_from(loop, loop->current_ready_poll + 1); + us_internal_dispatch_ready_polls(loop, loop->current_ready_poll + 1); + /* The remainder's callbacks may have queued JS work that only our + * caller can run once this tick returns, and it chose `timeout` before + * they ran: poll for new events, never idle in the kernel. */ + timeout = &us_zero_timespec; } struct us_internal_callback_t *timer_callback = (struct us_internal_callback_t*)loop->data.sweep_timer; @@ -464,7 +424,7 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout } while (IS_EINTR(loop->num_ready_polls)); #endif - us_internal_dispatch_ready_polls(loop); + us_internal_dispatch_ready_polls(loop, 0); us_internal_drain_ready_polls(loop); /* Emit post callback */ diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index f2704fd0c8cc..e0d3d9252a85 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -359,15 +359,8 @@ export const isMemoryPressureWatcherInstalled: () => boolean = $newCppFunction( 0, ); -export const getEventLoopStats: () => { - activeTasks: number; - concurrentRef: number; - numPolls: number; - /** Reentrancy depth of `us_loop_run_bun_tick`; >= 1 when called from inside a poll-dispatch callback. Always 0 on Windows. */ - tickDepth: number; - /** Undispatched entries remaining in the live ready-poll batch after the one being dispatched. Always 0 on Windows. */ - pendingReadyPolls: number; -} = $newRustFunction("event_loop.rs", "getActiveTasks", 0); +export const getEventLoopStats: () => { activeTasks: number; concurrentRef: number; numPolls: number } = + $newRustFunction("event_loop.rs", "getActiveTasks", 0); export const hostedGitInfo = { parseUrl: $newRustFunction("hosted_git_info.rs", "TestingAPIs.jsParseUrl", 1), diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index 5573a24dc4b8..9e7cdf41a2ed 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -1150,7 +1150,7 @@ pub fn get_active_tasks(global_object: &JSGlobalObject, _frame: &CallFrame) -> J // fields and call &-methods on it for the duration of this host fn. let vm_ref = global_object.bun_vm(); let event_loop = vm_ref.event_loop_shared(); - let result = JSValue::create_empty_object(global_object, 5); + let result = JSValue::create_empty_object(global_object, 3); result.put( global_object, b"activeTasks", @@ -1166,38 +1166,14 @@ pub fn get_active_tasks(global_object: &JSGlobalObject, _frame: &CallFrame) -> J let num_polls: i32 = i32::try_from(unsafe { (*bun_sys::windows::libuv::Loop::get()).active_handles }) .expect("int cast"); - // `tick_depth` and the ready-poll cursor only exist on the POSIX uws loop; - // the libuv loop drives readiness on Windows, so report them as 0 there. - #[cfg(windows)] - let (tick_depth, pending_ready_polls): (i32, i32) = (0, 0); #[cfg(not(windows))] // SAFETY: uws::Loop::get() returns a live process-global loop. - let (num_polls, tick_depth, pending_ready_polls): (i32, i32, i32) = unsafe { - let loop_ = &*uws::Loop::get(); - ( - loop_.num_polls, - loop_.internal_loop_data.tick_depth, - // Undispatched entries after the one currently being dispatched. - // > 0 only from inside a poll callback with remaining siblings in - // its batch; a completed dispatch leaves current == num. - (loop_.num_ready_polls - loop_.current_ready_poll - 1).max(0), - ) - }; + let num_polls: i32 = unsafe { (*uws::Loop::get()).num_polls }; result.put( global_object, b"numPolls", JSValue::js_number(num_polls as f64), ); - result.put( - global_object, - b"tickDepth", - JSValue::js_number(tick_depth as f64), - ); - result.put( - global_object, - b"pendingReadyPolls", - JSValue::js_number(pending_ready_polls as f64), - ); Ok(result) } diff --git a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts index 8a3df7296bec..6b8fabe55fc5 100644 --- a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -1,100 +1,67 @@ -// A subprocess stdout/stderr pipe reader is registered one-shot on every POSIX -// platform (`OneShotFlag::Dispatch`: EPOLLONESHOT on Linux, EV_DISPATCH on -// kqueue). When the reader's readable/EOF event is dropped in user-space after -// epoll_wait/kevent has already returned it, the kernel has disarmed the fd and -// nothing re-arms it: `onUpdate` (which sets the re-arm flag) never ran. The -// output is then never read and its consumer waits forever. -// -// The drop happens when a poll callback re-enters us_loop_run_bun_tick while -// the outer us_internal_dispatch_ready_polls is still iterating the batch. The -// inner tick's epoll_wait/kevent overwrites the shared loop->ready_polls / -// num_ready_polls / current_ready_poll, so the outer loop resumes against the -// inner batch and silently skips its own remaining events. -// -// Bun.$ hits this without any test-only poke: when a command finishes, finish() -// wraps the promise resolution in loop.enter()/loop.exit(), and loop.exit() -// drains microtasks inline, running the command's .then continuation *during* -// the poll dispatch. If that continuation synchronously waits on a promise -// (waitForPromise -> autoTick), the nested tick clobbers the batch and sibling -// commands' one-shot pipe-EOF events are lost. Those commands' shells never see -// EOF, so their promises never resolve. -// -// PR #30301 fixed the same batch corruption for the Linux pidfd by making it -// level-triggered, but left the pipe readers one-shot and assumed a dropped -// pipe event is reported again via EPOLLHUP on the next wait. It is not: a -// disarmed one-shot fd reports nothing until it is re-armed, which never -// happens. On macOS the process-exit watch (EVFILT_PROC) is also still -// one-shot, so the batch corruption loses exit events there too. -// -// Fix: when us_loop_run_bun_tick detects it is nested inside a mid-iteration -// dispatch, it dispatches the outer batch's remaining entries before its own -// epoll_wait/kevent can overwrite them, so no one-shot event is dropped. -import { getEventLoopStats } from "bun:internal-for-testing"; +// https://github.com/oven-sh/bun/pull/32233 +// Subprocess pipe readers are one-shot (EPOLLONESHOT / EV_DISPATCH): if a poll +// callback re-enters the event loop while the outer ready-poll batch is still +// being dispatched, the batch's remaining (already-disarmed) events must not be +// dropped by the nested tick's wait, or their owners hang forever. import { expect, test } from "bun:test"; import { isWindows } from "harness"; -// The uws ready-poll batch only exists on the POSIX event loop; on Windows -// libuv drives readiness through a different path (and the stats below read 0). +const N = 34; +const expected = Array.from({ length: N }, (_, i) => `out-${i}`); + +// Windows readiness is driven by libuv, not this code path. Both macOS +// (kqueue, EV_DISPATCH) and Linux (epoll, EPOLLONESHOT) reproduce the hang. test.skipIf(isWindows)("a batch of Bun.$ commands survives a nested tick from one command's continuation", async () => { - const N = 34; let nested = false; - // Captured from inside the first continuation to run, then asserted after - // the batch settles. They make the trigger self-checking: if either - // implementation detail this test leans on is refactored away, these fail - // loudly instead of leaving the test vacuously green against a broken - // event loop. - let tickDepthInContinuation = -1; - let pendingSiblingsInContinuation = -1; - let sawNestedTick = false; - const cmds = Array.from({ length: N }, (_, i) => { - const cmd = Bun.$`printf %s out-${i}`.quiet(); + const cmds = expected.map(out => { + const cmd = Bun.$`printf %s ${out}`.quiet(); // The first command to settle runs this continuation inline, during the - // poll dispatch (finish() -> loop.exit() -> drainMicrotasks). Waiting on - // a promise here forces a nested us_loop_run_bun_tick; without the fix it - // clobbers the outer batch and drops sibling commands' one-shot pipe-EOF - // events, which the kernel has already disarmed. + // poll dispatch. Synchronously waiting on a promise (bun:test's .resolves + // blocks via waitForPromise) forces a nested tick while the sibling + // commands' one-shot pipe-EOF events are still in the outer batch. cmd.then( () => { - if (nested) return; - nested = true; - - // Precondition 1: we really are running inline from inside a poll - // dispatch (tickDepth >= 1) with undispatched sibling events still in - // the live batch (pendingReadyPolls > 0). If finish() stops draining - // microtasks inline, tickDepth reads 0 here. If the continuation no - // longer lands inside the batch that holds the siblings' events, - // pendingReadyPolls reads 0. Either way the test fails instead of - // silently not exercising the bug. - const stats = getEventLoopStats(); - tickDepthInContinuation = stats.tickDepth; - pendingSiblingsInContinuation = stats.pendingReadyPolls; - - // Precondition 2: a nested tick actually runs before this - // continuation returns. Bun.sleep(0)'s continuation can only have run - // by the time the synchronous wait below returns if an event-loop - // tick ran inside it. If expect().resolves stops blocking - // synchronously, `sawNestedTick` is still false right afterwards. - Bun.sleep(0).then(() => { - sawNestedTick = true; - }); - expect(Bun.sleep(1)).resolves.toBe(undefined); + if (!nested) { + nested = true; + expect(Bun.sleep(1)).resolves.toBe(undefined); + } }, () => {}, ); return cmd; }); - // With the dropped-slot bug, the commands whose pipe-EOF was skipped never - // finish and this hangs until the test times out. There is no other wake - // source for a disarmed one-shot pipe. + // Without the fix, the commands whose pipe-EOF event was dropped never + // finish and this times out; nothing re-arms a disarmed one-shot pipe. const results = await Promise.all(cmds); - expect(tickDepthInContinuation).toBeGreaterThanOrEqual(1); - expect(pendingSiblingsInContinuation).toBeGreaterThan(0); - expect(sawNestedTick).toBe(true); + expect(nested).toBe(true); + expect(results.map(r => r.stdout.toString())).toEqual(expected); +}); + +// Same bug without the shell: the nested tick comes from a Bun.spawn onExit +// callback while sibling subprocesses' pipe-EOF events sit in the same batch. +test.skipIf(isWindows)("a batch of Bun.spawn pipe readers survives a nested tick from an onExit callback", async () => { + let nested = false; + + const procs = expected.map(out => + Bun.spawn({ + cmd: ["printf", "%s", out], + stdout: "pipe", + stderr: "ignore", + onExit() { + if (!nested) { + nested = true; + expect(Bun.sleep(1)).resolves.toBe(undefined); + } + }, + }), + ); + + const outs = await Promise.all(procs.map(p => p.stdout.text())); + await Promise.all(procs.map(p => p.exited)); - for (let i = 0; i < N; i++) { - expect(results[i].stdout.toString()).toBe(`out-${i}`); - } + expect(nested).toBe(true); + expect(outs).toEqual(expected); }); From 7e1e70262497fcbd2bfb3d738f7dd198c1d9f2e7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 2 Jul 2026 03:17:03 +0000 Subject: [PATCH 7/7] test: cover the nested tick with an HTMLRewriter async handler The two existing cases force the nested tick through expect().resolves, which blocks synchronously only as an implementation detail of bun:test's matcher. HTMLRewriter.transform with an async element handler must wait for the handler's promise before returning, so this case cannot be defused by a future matcher refactor. Same batch geometry, no test-runner machinery in the trigger. Times out on an unfixed build and passes with the fix, like the others. --- .../bun/spawn/pipe-reader-nested-tick.test.ts | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts index 6b8fabe55fc5..41195bd403ab 100644 --- a/test/js/bun/spawn/pipe-reader-nested-tick.test.ts +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -40,6 +40,43 @@ test.skipIf(isWindows)("a batch of Bun.$ commands survives a nested tick from on expect(results.map(r => r.stdout.toString())).toEqual(expected); }); +// Same bug without bun:test as the trigger. The two tests above nest via +// expect().resolves, which blocks only as an implementation detail of the +// matcher. HTMLRewriter.transform with an async handler is *contractually* +// synchronous (it must wait for the handler's promise before returning), so +// this case keeps failing even if the matcher is ever made non-blocking. +test.skipIf(isWindows)( + "a batch of Bun.$ commands survives a nested tick from an HTMLRewriter async handler", + async () => { + let nested = false; + + const cmds = expected.map(out => { + const cmd = Bun.$`printf %s ${out}`.quiet(); + cmd.then( + () => { + if (!nested) { + nested = true; + new HTMLRewriter() + .on("p", { + async element() { + await Bun.sleep(1); + }, + }) + .transform("
x
"); + } + }, + () => {}, + ); + return cmd; + }); + + const results = await Promise.all(cmds); + + expect(nested).toBe(true); + expect(results.map(r => r.stdout.toString())).toEqual(expected); + }, +); + // Same bug without the shell: the nested tick comes from a Bun.spawn onExit // callback while sibling subprocesses' pipe-EOF events sit in the same batch. test.skipIf(isWindows)("a batch of Bun.spawn pipe readers survives a nested tick from an onExit callback", async () => {