diff --git a/packages/bun-usockets/src/eventing/epoll_kqueue.c b/packages/bun-usockets/src/eventing/epoll_kqueue.c index 7e347a378d5b..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,10 +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 */ -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. 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 = 0; 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) { @@ -229,10 +233,14 @@ 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 [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 }; @@ -255,7 +263,7 @@ 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). */ int merged = 0; - for (int j = i - 1; j >= 0; 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; @@ -272,7 +280,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 = 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; @@ -305,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); @@ -316,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); } } @@ -338,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 */ @@ -355,6 +362,17 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, const struct timespec* timeout loop->data.tick_depth++; + /* 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(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; // Only integrate the loop if we haven't already. @@ -406,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/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..41195bd403ab --- /dev/null +++ b/test/js/bun/spawn/pipe-reader-nested-tick.test.ts @@ -0,0 +1,104 @@ +// 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"; + +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 () => { + let nested = false; + + 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. 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) { + nested = true; + expect(Bun.sleep(1)).resolves.toBe(undefined); + } + }, + () => {}, + ); + return cmd; + }); + + // 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(nested).toBe(true); + 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 () => { + 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)); + + expect(nested).toBe(true); + expect(outs).toEqual(expected); +});