Repository navigation
Conversation
…p 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.
|
Found 3 issues this PR may fix:
🤖 Generated with Claude Code |
WalkthroughRefactors uSockets' ready-poll dispatch to support a starting cursor, allowing nested event loop ticks to flush the outer batch's remaining ready-polls before kernel wait calls overwrite them. Adds ChangesReady-poll dispatch windowing
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Assessment of the three issues the bot flagged. This PR fixes the nested-tick #26580 (shell hangs intermittently, #32178 (deterministic segfault, 3 subprocesses) crashes on exactly the path this PR hardens: #27766 (100% CPU busy-spin, macOS, ~20 concurrent bun + Ink + fetch) presents as a busy-spin, not a silent hang. A dropped one-shot event (the bug here) produces a stuck reader with no CPU, not a spin, so this looks like a separate macOS/kqueue wakeup-storm issue rather than this one. Not adding |
There was a problem hiding this comment.
I didn't find any bugs, but this touches the core epoll/kqueue dispatch path and adds heap-allocated state that must stay coherent across nested ticks and C↔Rust struct layouts — worth a human look.
Extended reasoning...
Overview
This PR fixes nested-tick corruption of loop->ready_polls by snapshotting the outer dispatch batch onto a LIFO stack before a re-entrant us_loop_run_bun_tick clobbers it, and restoring it on return. It touches epoll_kqueue.c (snapshot struct, save/restore in us_loop_run_bun_tick, snapshot fixup in us_internal_loop_update_pending_ready_polls, new us_loop_invalidate_ready_poll), adds a field to us_internal_loop_data_t, mirrors that field in the Rust InternalLoopData repr(C) struct, adds a Rust FFI wrapper, wires FilePoll::deinit_possibly_defer to invalidate stale entries, and adds a Linux regression test.
Security risks
None apparent — no parsing, auth, or external input handling. The new heap allocation is bounded by num_ready_polls (≤1024) and freed on the same stack frame's exit path.
Level of scrutiny
High. This is the innermost event-loop dispatch path that every poll-driven I/O operation in Bun flows through. Subtle mistakes here manifest as hangs, double-dispatch, or use-after-free across the entire runtime. Specific areas I'd want a human to confirm: (1) the snapshot is taken before tick_depth++'s effects but the restore happens after us_internal_drain_ready_polls, which itself loops and rewrites ready_polls — restoring the outer cursor over whatever drain left behind looks correct but is non-obvious; (2) on kqueue the restored batch re-runs the first-pass coalescing in the outer us_internal_dispatch_ready_polls, which already completed before the nested tick — actually it doesn't, since the outer dispatch resumes mid-second-pass with the snapshot's events but the stack-local coalesced[] array from before the nested call; (3) the C struct gained a trailing void* after int tick_depth, and the Rust mirror must match padding exactly for the PosixLoop offset assertions to hold.
Other factors
CI showed build-rust failures on macOS x64 and aarch64-musl for the pre-autofix commit; the autofix commit may or may not have resolved them. The change is well-documented and includes a targeted regression test, but the blast radius (every nested-tick scenario on every POSIX platform) and the cross-language struct layout coupling put it well outside what I'd approve without human review.
|
Thanks, addressing the three points for a human reviewer: Restore ordering (after kqueue Struct layout. The On CI: build #62250 (current) is green on |
Status: diff is green, CI red is unrelated flakeThe change itself is verified and passing:
The two red runs are both external/infra flake, not this diff:
I have used my one CI re-roll (commit |
There was a problem hiding this comment.
I didn't find issues, but this changes core event-loop reentrancy semantics (snapshot/restore of ready-poll batches across nested ticks, plus cross-language struct layout and freed-poll invalidation), so it warrants a human look before merging.
Extended reasoning...
Overview
This PR modifies the core POSIX event-loop dispatch in bun-usockets to fix lost EPOLLONESHOT events when us_loop_run_bun_tick re-enters itself. It adds a heap-allocated LIFO snapshot stack of the outer ready_polls batch (in epoll_kqueue.c), a new ready_poll_snapshots field on us_internal_loop_data_t (mirrored in the Rust InternalLoopData repr(C) struct), extends us_internal_loop_update_pending_ready_polls to walk and rewrite all saved snapshots, exposes a new us_loop_invalidate_ready_poll C entry point with a Rust FFI wrapper, and reorders FilePoll::deinit_possibly_defer to call it before unregister. A Linux-only regression test exercises 34 concurrent Bun.$ commands with a forced nested tick.
Security risks
None apparent — this is internal event-loop bookkeeping with no auth, crypto, or untrusted-input handling. The risk surface is correctness/stability (UAF on stale poll re-dispatch, missed events, struct-layout mismatch across the C/Rust boundary) rather than security.
Level of scrutiny
High. This is the hot path every I/O operation in Bun flows through, and the change relies on subtle invariants: that current_ready_poll < num_ready_polls is true only mid-dispatch, that the inner tick leaves nothing un-dispatched before restore overwrites it, that kqueue's stack-local coalesced[] stays consistent with the restored ready_polls, that every poll-free path (uSockets sockets and Rust FilePolls) now nulls the entry in every snapshot to avoid re-dispatching freed memory, and that the new void* field's padding matches on all 10 Rust targets. The author has addressed several of these points in-thread with convincing reasoning, but the consequences of a mistake here are crashes or hangs across all of subprocess/pipe/socket I/O.
Other factors
The bug-hunting system found nothing, the PR is well-documented with a deterministic regression test, CI is reported green, and the author has already engaged with reviewer-style questions about restore ordering, kqueue coalescing, and struct layout. Still, the combination of reentrancy + manual memory management + cross-language ABI in the most critical loop in the runtime is exactly the kind of change a maintainer should sign off on rather than a bot.
alii
left a comment
There was a problem hiding this comment.
The root-cause work here is excellent, and the bug is real — I reproduced it on macOS as well (this PR's exact test body hangs 4/4 against an unfixed debug build on my machine, and passes without the nested-tick forcer), so it isn't Linux-specific. See the comment on the isLinux gate.
I don't want to take this shape of fix, though. It's a lot of new surface for the bug: a heap-allocated snapshot stack with a malloc/free + two ~12KB memcpys per nested tick, a new C API (us_loop_invalidate_ready_poll), a Rust FFI shim, a new InternalLoopData field, and a hook in FilePoll::deinit_possibly_defer. And the tell is why most of that exists: the whole invalidation half isn't fixing the original bug — it's defending the snapshot from what can happen during a nested tick (a FilePoll freed while its entry sits in the preserved copy). A fix that needs a second fix to protect itself is usually sitting at the wrong end of the invariant.
The alternative I'd like evaluated first: dispatch the outer remainder instead of preserving it
In the same current_ready_poll < num_ready_polls branch this PR adds at the top of us_loop_run_bun_tick, finish dispatching the outer batch's remaining entries (from current + 1) before the nested epoll_wait/kevent runs, instead of copying them aside. From reading the current code I think that's sound:
- A completed dispatch's postcondition is
current_ready_poll == num_ready_polls(epoll_kqueue.c:198,:275) — which is exactly the state a nested tick leaves behind, and why today's failure is a silent skip rather than a double dispatch. Drain the remainder first and that end state becomes correct. No snapshot, no restore, no LIFO. - Level-triggered sockets already get precisely this treatment today: the nested
epoll_waitre-reports every still-ready LT fd from the outer remainder, and the nested dispatch runs their callbacks at the deeper nesting level while the outer callback is still on the stack. Only one-shot (EPOLLONESHOT/EV_DISPATCH) entries are trapped, because the kernel already disarmed them. So draining doesn't introduce a new reentrancy class — it extends to one-shot entries what LT entries already get. - With no preserved batch there is nothing to invalidate:
us_loop_invalidate_ready_poll, its FFI declaration, theInternalLoopDatafield, and thedeinit_possibly_deferhook all disappear — along with the (currently untested) use-after-free hazard they exist to prevent. Frees in the live batch stay covered byus_internal_loop_update_pending_ready_polls+ the deferred hive free, exactly as before this PR.
Two honest caveats so nobody thinks it's free:
- On kqueue, the dispatcher's coalescing pass merges duplicate kevents backward across the whole batch; a
..._from(start)variant must bound that merge window to[start, n), or a pending entry can coalesce into an already-dispatched slot and get lost. - It changes when the remainder runs (inside the nested tick, before the awaited promise settles). I couldn't find anything that depends on running at the outer depth — LT sockets already violate that today — but if there is such a consumer, that's a legitimate reason to reject the drain; it just needs to be written down.
If we want to kill the bug class, not just this instance
Stepping back: the reason this bug (and #30301's pidfd variant) exists at all is that a stack frame's iteration state — which batch is being dispatched and how far along it is — lives on the shared loop object (ready_polls / num_ready_polls / current_ready_poll), so any reentrant tick aliases it. The drain removes the harmful state at the reentry point; the structural end-state is for each dispatch to own its batch: read events into a frame-local buffer, iterate a frame-local cursor, and link live frames through an intrusive prev pointer on the loop so us_internal_loop_update_pending_ready_polls can scrub freed polls from every live frame's remainder (that one walk replaces both today's single-batch fixup and this PR's snapshot walk). Then a nested tick physically cannot clobber its parent — for this and any future reentrancy source — with no copies and no heap. That's a bigger refactor than either this PR or the drain, so I'm not asking for it here; but if we're adding machinery around this invariant, I'd rather it converge toward "the frame owns its batch" than toward "the shared batch gets copied aside and patched back". Either the drain now, or that refactor, would leave this file simpler than this PR does.
FWIW I went looking for problems in the snapshot mechanism itself — double dispatch of LT entries after the restore, the LIFO at depth ≥ 2, the cursor arithmetic, us_poll_resize/adopt against a live snapshot — and didn't find any. The mechanism is right; it's the amount of it, and the number of new invariants it hands to future readers, that I'm pushing back on.
So: either take the drain shape (happy to look at it quickly), or reject it explicitly in the PR description with the concrete reason. If the snapshot stays, the line comments below need addressing — the OOM fallback, the untested invalidation path, and the test's gate/trigger are each independently important.
|
Agreed on all of it. I'm switching this PR to the drain shape; thanks for the macOS repro and for writing the alternative up so precisely. You're right about what the invalidation half is: it is not part of fixing the bug, it is defending the snapshot from a hazard the snapshot itself creates (a I independently checked the two things the drain leans on and both hold:
On the kqueue caveat: agreed, and I'll implement it as On the tests, taking all three:
Pushing the drain shortly. |
…k 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.
|
Pushed the drain in a841c0d and updated the title and description to match. Net diff vs main is now: Every line comment is answered and resolved in its thread. The one I want to surface here rather than bury: I attempted the shell-free Verified locally: the test passes 5/5 in ~0.4s on the drain build and hangs 8/8 on the unfixed release binary; |
…s-nested-tick-ready-polls # Conflicts: # src/js/internal-for-testing.ts
alii
left a comment
There was a problem hiding this comment.
Too many comments. These comments don't need to be so long
|
@robobun ^ |
|
To make the review request concrete, here is the drain implementation, built and verified locally on macOS. @robobun please adopt this shape for this PR:
Fixdiff --git a/packages/bun-usockets/src/eventing/epoll_kqueue.c b/packages/bun-usockets/src/eventing/epoll_kqueue.c
index 7e347a378d..b3ab0be3da 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 */
+ 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 */
- for (int i = 0; i < loop->num_ready_polls; i++) {
+ /* 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 */Why this is sufficient:
Two subtleties are deliberate — please keep them if you adopt this:
Test// 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 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);
});Verification (macOS, kqueue, Apple Silicon, debug build)
The spawn variant is worth keeping: on an unfixed build it wedges the whole runner (not even the per-test timeout fires), i.e. the lost-event class is not limited to shell pipe EOFs. |
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.
|
Adopted verbatim in eca4e42, thanks. The Also in that commit: your test file replaces mine, the Linux verification: |
|
Status: do not merge yet. CI caught a real regression in the drain (both my version and the adopted one), and I want to be the one to say it clearly.
The failing test is I could not reproduce it on my box and I now distrust every local timing I collected: this container shares a host that is sitting at load 60-100, and with events trickling in one per batch there is never a mid-iteration remainder, so (per temporary instrumentation) the drain never even executes locally. On CI, where the child's stdout EOF, stderr EOF, and exit land in one batch, it does. I am instrumenting from here to get the mechanism rather than guessing; the one honest hypothesis I have is that dispatching the remainder inside the interrupted callback's own stack frame can deliver a sibling event of the same logical object (the same command's other pipe, its exit) reentrantly into a state machine that is mid-transition below it, which is a stronger reentrancy than the level-triggered precedent we both leaned on (those are re-delivered by the nested wait, from a fresh batch, and evidently in an order this test depends on). I will follow up with either the mechanism and a corrected fix, or a revert of the drain commit plus what I learned. Sorry for the churn; your review direction (no snapshot, no invalidation machinery) still stands, the remaining question is only how the preserved remainder gets delivered. |
|
Correction, and I want to be precise because my previous comment told you the drain regressed CI: it did not. I withdraw that, with apologies; here is the evidence that overturned it.
So the facts stand as they were before my false alarm: this PR's own tests pass on every lane, nothing red in either build is attributable to the diff, and the drain has no counter-evidence against it. The only thing my wrong conclusion was built on was an invalid baseline plus an oversubscribed local box, and I should have checked other branches' builds before pointing at the code. The do-not-merge is withdrawn; CI will stay red on the unrelated bake test until #33214 is fixed, so that is the only thing between this and a clean board. |
|
@robobun Hi |
|
Hi @cnrad! Quick status in case that is what you are after: the fix here is the shape alii proposed (dispatch the outer ready-poll remainder before a nested tick overwrites it), adopted verbatim in eca4e42 along with their test. This PR's own tests pass on every lane. The remaining CI red is |
|
@robobun — one more datapoint would make the coverage story airtight, and only your Linux box can produce it cheaply. The regression test forces the nested tick explicitly (the
If the raw shape genuinely doesn't reproduce on your box either, that's important too — say so, and we'll know the one-shot loss needs some synchronous-wait source in the process (module loader, macros, |
|
Done. Numbers first; 20 cold
// withrewriter.mjs: the only difference from raw.mjs
cmds[0].then(() => {
new HTMLRewriter().on("p", { async element(el) { await Bun.sleep(30); } }).transform("<p>x</p>");
});So you are right, and thank you for pressing on it: the raw shape does not reproduce on Linux either (consistent with your 0/8 on macOS), and the PR description overstated it. I am correcting the description. A bare The stack you asked for, captured on the unfixed binary during the nested window ( gdb cannot name the native frames below the JS boundary, so instead of showing No code changes from any of this; |
|
Thanks — that's exactly the datapoint set I wanted, and the
|
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.
|
All three folded in, pushed as 7e1e702.
|
|
Thanks for the review and for the better fix shape. For whoever merges: the only red on CI is |
|
I'm closing this, and I owe the PR a precise explanation, because the code here is not wrong — I approved it earlier today — and the investigation behind it is some of the best diagnostic work this bug class has gotten. This is a direction decision, not a correctness one. The decision. A nested Teaching the dispatch loop to tolerate mid-batch re-entry (which is what the drain does — correctly!) locks in the wrong invariant. Once it lands, the next blocking API someone adds is silently fine instead of loudly wrong, and the reentrancy never goes away. I would rather fix the callers and forbid the state. What we'll do instead (tracking issue to follow):
What this PR established, which all of the above stands on: the loss mechanism (one-shot fds + a clobbered The honest cost of closing: until (1) and (2) ship, the |
|
Tracking issue for the direction above (de-block the blocking callers, then assert that nothing re-enters the loop mid-dispatch): #33261 |
|
That is the right call, and thank you for writing it down so precisely. "The dispatcher should not learn to survive a state that is itself a bug" is a better invariant than the one this patch would have locked in, and the debug assertion in #33261 is the part I wish I had proposed: it turns every future blocking API added inside an I/O callback into a loud CI failure instead of a one-in-a-thousand hang. Everything transferable is already here for whoever picks up #33261: the Thanks for the three rounds of review. The patch got better each time, and the thing that replaced it is better still. |
…run (#46335) ### Problem - A callback of a TLS socket over a stream turns the event loop synchronously while the socket closes. Debug builds report `AddressSanitizer: heap-use-after-free` in `us_ssl_wrapper_keylog` under `SSL_do_handshake`, or in `SSLWrapper::flush_pending_events`. Release builds end with `panic: RefCell already borrowed` or stay silent. - `DuplexUpgradeContext::on_close` (`src/runtime/socket/socket_body.rs`) queued the task that frees the context at once. The nested turn ran it under the TLS engine. - Found by audit. No issue or crash report names it. ### Fix - `DuplexUpgradeContext` is refcounted. The open connection holds one ref, and each `UpgradedDuplex` entry point holds one while it runs. The free task is queued at zero. - No free task exists while an entry point runs. A debug assertion checks that handlers run under a ref. - Verified: `test/js/node/tls/node-tls-duplex-close-throw-uaf.test.ts`. Ten cases abort on the base build and pass with the fix. Also twelve TLS, http2 and module-graph suites (Notes). - Self-reviewed: 12 concerns raised, 11 addressed. One exit has no test (Notes). ### Background - `DuplexUpgradeContext` owns `UpgradedDuplex`, which owns the TLS engine (`SSLWrapper`) behind `tls.connect({socket})`. - `expect(promise).resolves` and `Bun.build` with an async plugin `setup()` run queued tasks while they wait. - Considered a check in the free task. It parks the free and polls. `WindowsNamedPipe` (#39983) holds a ref at its entry points. ### Downsides - Duplex TLS pays 9 instructions per guarded entry. An echo measures +0.11% instructions, and a control with no guard +0.06%. - A transport error before the engine starts takes 2 queue entries, not 1. - The binary grows by 8,192 bytes and one test-only host function. <details><summary>Notes</summary> #### What turns the loop, and what closes the socket - The wait is `EventLoop::wait_for_promise` (`src/jsc/event_loop.rs`). It calls `tick()`, which runs the task queue. The fixture uses two callers: a `bun:test` promise matcher in a plain script, and `Bun.build` with an async plugin `setup()` (`src/runtime/api/JSBundler.rs`). - The callback does not have to close the socket. Three of the ten cases close it from elsewhere: a `destroy()` in a later turn (the callback is the transport's `final()`), a transport that closes during the turn, and a `Bun.ModuleGraph` that is disposed. - #44618 covered an ALPNCallback that destroys its socket with no loop turn (it kept the `SSL` until the pass ends). The owner was still freed by the queued task. #### The ten cases on the base build (debug, ASAN) Each one ends in `heap-use-after-free`. The free is `DuplexUpgradeContext::deinit` from `run_event`, or from `release_unrun` for the disposed graph. | Case | Top frames of the read | |---|---| | ALPNCallback | `us_ssl_wrapper_keylog` < `us_ssl_keylog_cb` < `SSL_do_handshake` | | server 'keylog' | `SSLWrapper::flush_pending_events` < `traffic_pass` | | client 'secureConnect' | `UpgradedDuplex::is_shutdown` < `UpgradedDuplex::on_handshake` | | server 'data' | `SSLWrapper::dispatch_read` < `handle_reading` | | server 'data', turned by `Bun.build()` | `SSLWrapper::dispatch_read` < `handle_reading` | | client 'data' | `SSLWrapper::dispatch_read` < `handle_reading` | | the transport's `write()` | `SSLWrapper::handle_writing` < `write_data` | | the transport's `final()`, `destroy()` in a later turn | `UpgradedDuplex::finish_close` < `on_close` | | server 'data', the transport closes during the turn | `SSLWrapper::dispatch_read` < `handle_reading` | | server 'data', its `Bun.ModuleGraph` is disposed | `SSLWrapper::dispatch_read` < `handle_reading` | Release build of the base, original repro (ALPNCallback destroys the socket, then `expect().resolves`): `panic: RefCell already borrowed`, 5 of 5 runs. The 'keylog' variant printed OK 5 of 5 (silent). Sentry was not queried. #### How the tests decide - The fixture counts live contexts through `duplexTLSInternals.liveCount()`, so the tests do not need ASAN to fail. - Each callback case has a third context that nothing holds. The turn frees it. That shows that the turn ran the queued tasks: the report is `{ before: 3, afterTurn: 2, afterClose: 0 }`. With no turn it is 3, and with the fault it is 1. - The turn is a promise that a microtask settles, so one `tick()` runs. One case turns with `Bun.build()` instead, so the test does not depend on the matcher alone. - The fourth test ends a connection in seven ways and expects zero contexts left. It does not abort on the base build. There it fails because the counter does not exist. - Each guard clause was removed once on the debug build (by a jump in gdb) to confirm that a test notices: - no `teardown()` in `release_unrun`: a string from the transport reaches the disposed graph as `ERR_STREAM_WRAP`. - no `abort_handle.leave()`: `DuplexUpgradeContext entered after its last ref was released`. - the count check in `release_unrun`: the graph case reaches it with a count of 1, so an unconditional free trips the assertion in `deinit`. #### Direction - #33261 asks that nothing re-enters the event loop from a dispatch callback. #32233 was closed for that reason: it made the dispatcher tolerate re-entry. #33289 moves the `bun:test` matchers off the nested wait. - This change does not touch the dispatcher or the loop. It fixes a memory fault at one owner, in the shape of `REVIEW.md` ("bracket entry points that can reach synchronous teardown with ref()/defer deref()") and of #39983. - The trigger stays reachable after #33289: `Bun.build` still waits for an async `setup()` (#33271 was closed without a merge). #### Sequencing - This lands first. Two open PRs add entry points to `UpgradedDuplex` and need the guard after it: - #45471: `UpgradedDuplex::resolve_server_name` (an SNICallback that answers in a later turn) needs the `keep_alive()` guard as its first statement, and `DuplexUpgradeContext::on_server_name` needs the `debug_assert_kept_alive()` call. Without them the debug build aborts on the assertion. - #43877: the `on_write_done` thunk needs the guard. - #40139 rewrites the same lines and keeps the unconditional free in the `Close` arm. A rebase must keep the rule: the `Close` hop is queued only at zero. #### Not in this change - `WindowsNamedPipe`: #39983 guards `on_read`, `on_read_error`, `on_error`, `on_handshake` and `get_accepted_by`. Seven entries that dispatch have no guard: `on_writable`, `flush`, `on_timeout`, `encode_and_write`, `raw_write`, `close`, `shutdown`. No fault is known there: its transport is libuv and runs no script in write, end, pause or resume. Read from the code, not run on Windows. Do not copy `keep_alive` to those entries as is: there, a ref taken at zero queues the free twice. - `ProxyTunnel` (`src/http/ProxyTunnel.rs`) runs on the HTTP thread, where no script runs. - The start-failure exit of the `StartTLS` arm now releases the connection's ref. It has no test. `node:tls` and `node:http2` pass a prebuilt `SSL_CTX`, so the start fails only if `SSL_new` fails. #### Measurements (linux x64, base 71bc818) - Instructions: `perf` is not installed here. The counts are `perf_event_open` (`PERF_COUNT_HW_INSTRUCTIONS`, user only) around the release binaries. One TLS echo over an in-process Duplex pair, 100,000 round trips of 1 KiB, `BUN_JSC_useJIT=0`, 10 interleaved runs each. - base 32,160,640,513, this PR 32,197,252,048: +366 per round trip of 321,600 (+0.11%). Run-to-run spread: 0.09% to 0.13%. - The same echo over loopback TCP (no guard on the path): base 20,199,900,220, this PR 20,211,412,604 (+0.06%). Spread: 0.07% to 0.11%. - Disassembly of `UpgradedDuplex__flush`: 4 instructions at entry and 5 at exit. A round trip takes 4 guards (gdb count on the debug build). - `sizeof(DuplexUpgradeContext)`: 568 B -> 568 B (gdb on the debug builds). The two fields fit in padding. - Queue entries per duplex TLS socket (gdb hit counts on `run_event`, 50 cycles): normal close 2 -> 2, `destroy()` before the engine starts 2 -> 2, transport error before the engine starts 1 -> 2. - Live contexts: 2 of 3 inside the callback after the turn, 0 after unwinding. 0 after 1,000 cycles of each of three orders on the release build (4,000 sockets). - Release binary (`llvm-size`): `.text` 81,904,741 -> 81,909,861 (+5,120), `.rodata` +4,096, file 107,497,184 -> 107,505,376 (+8,192). Host functions: +1, testing only. #### Suites (debug build, `--timeout 90000`) Same results as the base build: `node-tls-duplex-end-verify` (115), `node-tls-duplex-write-throw-error-value` (1), `node-tls-wrapped-socket-close` (113), `node-tls-server` (218), `node-tls-upgrade` (21), `node-http2-upgrade` (23), `renegotiation` (58), `node-tls-context` (83), `tls-fatal-error-closes` (38), `tls-reject-before-client-cert` (126), `module-graph-io` (28), `module-graph-isolation` (413). `node-tls-connect` has the same 4 failures on both builds: those tests contact bun.sh, which this machine cannot reach. `cargo clippy -p bun_runtime` and `test/internal/source-lints/` are clean. </details>
What
Concurrent
Bun.$commands could hang forever: the subprocess exits and is reaped (psshows nothing), but the command's promise never resolves.Repro
Concurrency alone is not sufficient: plain concurrent
Bun.$does not hang by itself (0/20 on an unfixed Linux release build, 0/8 on unfixed macOS), and a bare.thenchain never re-enters the event loop. The loss needs the interrupted callback, or a continuation it drains inline, to synchronously wait on the event loop, that is, one of thewaitForPromisecallers: bun:test's async matchers,HTMLRewriter.transformwith an async handler,Bun.buildplugin callbacks that return promises, macros, the module and entry loaders, bake's render paths, the REPL. That wait re-entersus_loop_run_bun_tickwhile the outer batch is mid-dispatch.Plain
require()of an ordinary module is not a trigger (it resolves inside the task drain without a nested kernel wait), andrequire()of a module with top-level await is refused, so lazy requires in callbacks do not re-enter either.Root cause
A shell command resolves only once it has both the process-exit event and the stdout/stderr pipe-EOF events (
Cmd::has_finished). The pipe readers register one-shot on every POSIX platform (EPOLLONESHOTon Linux,EV_DISPATCHon kqueue).The event loop fetches a batch of ready events into the shared
loop->ready_pollsand iterates it byloop->current_ready_poll. When a poll callback re-entersus_loop_run_bun_tick(observed live asepoll_pwait2 <- us_loop_run_bun_tick <- auto_tick <- wait_for_promise <- ...withloop->data.tick_depth == 2), the nested tick'sepoll_waitoverwritesloop->ready_polls,num_ready_polls, andcurrent_ready_poll. When the outer dispatch resumes it points at the inner batch, so its remaining events are silently skipped.For a one-shot fd a skipped event is unrecoverable:
epoll_waitalready disarmed the fd, andonUpdate(which sets the re-arm flag) never ran, so nothing re-arms it. #30301 fixed this for the Linux pidfd by registering it level-triggered, but noted it "doesn't address the underlying nested-tickready_pollscorruption (which also affects other one-shotFilePollowners)" and assumed pipes self-heal viaEPOLLHUP. They do not. This is not Linux-specific: the pipe readers are one-shot on kqueue too, and on macOS the process-exit watch (EVFILT_PROC) is also still one-shot.Fix
When
us_loop_run_bun_tickdetects it is nested inside a mid-iteration dispatch (current_ready_poll < num_ready_polls, never true after a completed dispatch), it dispatches the outer batch's remaining entries before its ownepoll_wait/keventcan overwrite them.Why this is the smallest correct shape:
current_ready_poll == num_ready_polls, which is exactly the state a nested tick leaves behind (and why today's failure is a silent skip rather than a double dispatch). Draining the remainder first makes that end state correct, with no saved state, and it recurses at any depth: a drained callback that re-enters gets its own remainder drained the same way.epoll_waitand dispatched at the deeper level with the outer callback on the stack; this extends the same treatment to the one-shot entries the kernel can no longer re-report. Callbacks that stop, change, or free a sibling poll are covered byus_internal_loop_update_pending_ready_pollsexactly as in a flat dispatch, and closed-socket frees stay deferred to the outermostloop_postbecausetick_depthis already >= 2 when the drain runs.[first_index, n)so a pending kevent cannot merge into an already-dispatched slot and get lost.epoll_kqueue.cplus the test.Verification
test/js/bun/spawn/pipe-reader-nested-tick.test.tscovers three triggers with the same 34-command batch geometry:Bun.$with a bun:test matcher continuation,Bun.$with anHTMLRewriterasync handler continuation (a contractually synchronous runtime API, so the coverage does not depend on the matcher's blocking behavior), andBun.spawnpipe readers with anonExittrigger.bun bdBun.$+Bun.spawncases, macOS (reviewer)Bun.$hangs 4/4;Bun.spawnvariant wedges the runner 4/4Bun.$+HTMLRewritercontinuation, 20 cold processes, LinuxBun.$only, 20 cold processes, Linuxpidfd-exit-nested-tick.test.tsand the fullbunshell.test.tssuite pass against the change (377 pass, 0 fail). The unrelated CI red on this PR is a fleet-widebake/dev/production.test.tsfailure affecting every current PR, tracked in #33214.