Repository navigation
process: drop EPOLLONESHOT for Linux pidfd exit poll - #30301
Conversation
A pidfd becomes readable when its process exits and stays readable until closed, so a level-triggered EPOLLIN watch is sufficient. EPOLLONESHOT is actively harmful here: the kernel disarms the fd the moment epoll_wait returns it, before user-space dispatches it. If a poll callback then re-enters us_loop_run_bun_tick (waitForPromise -> autoTick, which expect().resolves and a few other paths do), the inner tick overwrites loop->ready_polls / num_ready_polls / current_ready_poll and the outer dispatch silently skips its remaining events. A dropped one-shot pidfd event is unrecoverable -- the fd is disarmed with no re-arm path, so the subprocess's 'exit' event arrives only when the next unrelated timer wakes the loop. Level-triggered makes a dropped ready_polls slot harmless: the next epoll_wait returns the pidfd again. After a successful wait4 we close the pidfd (removing it from epoll), so there's no busy-loop. macOS/FreeBSD EVFILT_PROC+NOTE_EXIT stays EV_ONESHOT -- that filter is inherently once-per-process and the kernel auto-removes it. The test spawns 20 stdio:'ignore' children and does a nested autoTick from the first onExit; without the fix the siblings whose events were in the same batch never fire onExit.
|
Updated 11:26 PM PT - May 5th, 2026
❌ @robobun, your commit 9bea577 has 3 failures in
🧪 To try this PR locally: bunx bun-pr 30301That installs a local version of the PR into your bun-30301 --bun |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughIntroduces a public compile-time constant ChangesProcess poll one-shot + pidfd nested-tick test
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/js/bun/spawn/pidfd-exit-nested-tick.test.ts`:
- Around line 68-71: The test introduces a timing-sensitive Promise.race with a
setTimeout fallback; remove the timer branch and await the condition directly:
replace the Promise.race([...]) usage (referencing Promise.race, setTimeout, ms,
exits, t0) with a direct await Promise.all(exits) and then compute ms =
Date.now() - t0; adjust any subsequent assertions to use this ms value so the
test asserts the CONDITION (exits resolved) rather than relying on wall-clock
fallback.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 33d7a139-bcb2-40cb-8613-a9518c053ea2
📒 Files selected for processing (2)
src/runtime/api/bun/process.zigtest/js/bun/spawn/pidfd-exit-nested-tick.test.ts
Without the fix, Promise.all(exits) hangs because the dropped children's onExit callbacks never fire -- the test's default 5s timeout catches that.
Matches spawn-stdin-pipe-fd-leak.test.ts; avoids ENOENT on distros without /bin/true (NixOS, minimal container rootfs).
There was a problem hiding this comment.
The reasoning here is solid and the level-triggered pidfd argument checks out against FilePoll.register/unregister/onUpdate, but since this flips epoll trigger semantics for every Linux subprocess's exit poll (and robobun is still showing build-zig failures on 32c09f0), I'd like a human to sanity-check the rewatchPosix ref/CTL_MOD interaction and confirm CI is green on 9bea577 before merge.
Extended reasoning...
Overview
This PR changes two call sites in src/runtime/api/bun/process.zig (Process.watch and Process.rewatchPosix) to pass a new comptime constant process_poll_one_shot = !Environment.isLinux instead of a literal true to FilePoll.register. On Linux this drops EPOLLONESHOT from the pidfd registration so it becomes level-triggered; macOS/FreeBSD keep EV_ONESHOT with EVFILT_PROC. A new Linux-only regression test (pidfd-exit-nested-tick.test.ts) reproduces the dropped-event scenario by forcing a nested autoTick from inside the first onExit callback.
I traced the change through src/aio/posix_event_loop.zig: with one_shot = .none, the .one_shot flag is never inserted, so onUpdate does not set .needs_rearm, registerWithFd omits EPOLL.ONESHOT, and unregisterWithFd will now perform a real CTL_DEL (previously skipped via the needs_rearm short-circuit). After wait4 succeeds, onExit → detach → close → fd.deinit() removes the fd from epoll, so the level-triggered watch cannot busy-loop. rewatchPosix on a still-registered poll resolves to CTL_MOD via isRegistered(), which is harmless. The root-cause analysis (nested us_loop_run_bun_tick clobbering ready_polls) is consistent with the tick_depth guard in loop.c.
Security risks
None. No user-controlled input reaches the changed code; this is purely an internal epoll registration flag for an fd Bun itself opens via pidfd_open.
Level of scrutiny
High. The change is two lines of logic, but it sits on the hot path for every Linux subprocess exit (Bun.spawn, child_process, Bun.$, shell, etc.). Switching from one-shot to level-triggered changes which branches onUpdate/unregister take and how the kernel re-reports readiness; a mistake here would manifest as hung children, busy loops, or refcount leaks across the whole runtime. The PR description is unusually thorough and the regression test is a clean fail/pass gate, but this is exactly the kind of change a maintainer who owns the uws/usockets event-loop integration should sign off on.
Other factors
- Both prior review comments (CodeRabbit's
setTimeoutremoval, my/bin/true→"true"nit) have been addressed in 32c09f0 and 9bea577 respectively. - robobun's most recent CI report still shows
build-zigfailing on all targets for 32c09f0; 9bea577 only touches the test file, so if that failure is real (vs. infra flake) it would persist. CI status should be confirmed green before merge. - The PR explicitly notes it does not fix the underlying nested-tick
ready_pollscorruption for other one-shotFilePollowners — that's a reasonable scoping decision but worth a maintainer acknowledging. rewatchPosixstill callsthis.ref()on success; with level-triggered the fd is already armed, so a defensive re-register now adds a ref without a corresponding extraonUpdate/deref. In practicewait4(WNOHANG)should never return 0 once a pidfd is readable, so this path shouldn't fire — but it's the one interaction I'd want a human to double-check.
…255) CI on Linux intermittently fails (~50% of x86-64 runs) with "a beforeEach/afterEach hook timed out" at exactly ~5001ms in integration.test.ts, then 1-2 cascading hook timeouts and "killed N dangling processes" lines. Root cause is a Linux-only Bun bug fixed upstream in oven-sh/bun#30301 (commit ff38b2b7): the pidfd that signals a child process's exit was registered with EPOLLONESHOT, and a nested event-loop tick could drop the event from the dispatch batch before user-space saw it. The kernel already disarmed the fd, so the subprocess's 'exit' event never fires. Both socat bridges are SIGTERM'd in the same synchronous run and exit within ~1ms of each other, so their pidfd events land in the same epoll_wait batch — when one is dropped, reset()'s only escape was a setTimeout(5000) fallback. bun's default test/hook timeout is also 5000ms, and the hook starts a couple ms before reset() reaches its timer, so the hook always loses the race. That Bun fix is not in any released version yet (it landed after 1.3.13). Until it ships, harden reset() so the bug degrades to a slower reset() instead of a test failure: - Replace the 5000ms bridge-exit fallback with BRIDGE_EXIT_TIMEOUT_MS (1500ms). socat exits in <100ms; 1500ms is generous and leaves ~3.5s of margin against the hook timeout. Re-check liveness at the deadline and only escalate to SIGKILL when the process is actually still alive. - Skip registering the once('exit') listener when the process has already exited (exitCode/signalCode set) — a listener registered after the event was emitted never fires. - Force-close in-flight HTTP proxy connections via closeAllConnections() before close(), so close() does not hang on a curl killed mid-request. - Track and destroy SOCKS server connections in close() for the same reason — net.Server.close()'s callback waits for fully-open sockets. - Type createHttpProxyServer's return as http.Server (it always was; the previous net.Server type hid closeAllConnections from the type). - Factor the duplicated HTTP/SOCKS bridge teardown into killBridgeProcess.
## What On Linux, a subprocess's pidfd was registered with `EPOLLONESHOT`. If the event was dropped in user-space after `epoll_wait` returned it (before `onUpdate` ran), the kernel had already disarmed the fd, so the process's `'exit'` event never fired — it only arrived when the next unrelated timer happened to wake the loop. Observed in the wild as a 5s `afterAll` timeout in `anthropic-experimental/sandbox-runtime` on GH Actions `ubuntu-24.04` x86 runners (~80% hit rate): two `socat` bridges with `stdio: 'ignore'` are SIGTERM'd together; both exit within a few ms, but one's `'exit'` event doesn't fire until the 5000ms `setTimeout` fallback. ## Root cause `epoll_wait` returns a batch of ready events into `loop->ready_polls` and disarms every `EPOLLONESHOT` fd in that batch before user-space sees any of them. `us_internal_dispatch_ready_polls` then iterates the batch via `loop->current_ready_poll`. A poll callback can re-enter `us_loop_run_bun_tick` — the `tick_depth` guard in `loop.c` acknowledges this for `expect().toThrow()` → `waitForPromise` → `autoTick`, and the same applies to `expect().resolves`/`.rejects` and any other `waitForPromise` caller. The inner tick calls `epoll_wait` again, overwriting `loop->ready_polls`, `num_ready_polls`, and `current_ready_poll`. When control returns to the *outer* dispatch loop, its remaining indices now point at the inner tick's data (or past the new `num_ready_polls`), so those events are silently skipped. For a one-shot pidfd, a skipped event is unrecoverable: the fd is disarmed in the kernel, `onUpdate` never ran so `.needs_rearm` was never set, and nothing re-arms it. The next `epoll_wait` can't return it. ## Fix Register the pidfd level-triggered (no `EPOLLONESHOT`) on Linux. A pidfd stays readable from process exit until `close()`, so a dropped `ready_polls` slot is harmless — the next `epoll_wait` just returns it again. After `wait4` succeeds we close the pidfd anyway (via `Process.close()`), which removes it from epoll, so there's no busy-loop. `rewatchPosix` still defensively re-registers if `wait4(WNOHANG)` returns 0; with level-triggered that's a harmless `CTL_MOD`. macOS/FreeBSD continue to use `EV_ONESHOT` with `EVFILT_PROC` + `NOTE_EXIT`, which is inherently once-per-process and auto-removed by the kernel. This doesn't address the underlying nested-tick `ready_polls` corruption (which also affects other one-shot `FilePoll` owners), but pidfds are the case where it's both silent and common — pipes/sockets report the drop via `EPOLLHUP` on the next wait, whereas a disarmed pidfd has no second signal. ## Verification `test/js/bun/spawn/pidfd-exit-nested-tick.test.ts` spawns 20 `stdio: 'ignore'` children so their pidfd events land in one `epoll_wait` batch, then forces a nested `autoTick` from the first `onExit` via `expect(Bun.sleep(1)).resolves.toBe(undefined)`. | | system bun 1.3.14 | `bun bd` without fix | `bun bd` with fix | | --- | --- | --- | --- | | result | fail 5/5 (4001–4016ms) | fail 5/5 (4009–4068ms) | pass 5/5 (46–76ms) | `bun run zig:check-all` passes for all targets. --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…nd consumer shutdown Bun 1.3.x drops one-shot pidfd and pipe events when a callback re-enters the event loop, as bun:test expect().resolves/.rejects does (oven-sh/bun#30301). An execFile child whose exit is dropped stays a zombie and its callback, and its own timeout, never fire. The persistence consumer's durability probe (isDurabilityHardenedAsync, async since v0.60.10.0) spawns two git children per git effect, so a test awaiting .rejects while effects drained could leave the effects worker waiting forever; consumer.stop() awaits that worker, so disposePersistenceConsumer and every later fixture in the file hung ("killed N dangling process" is Bun reporting the unreaped children at the timeout). Seen in managed-maintenance, persistence-reconcile and google-attachments E2E. execFileBounded settles from its own timer at the deadline or on abort and SIGKILLs the child. The durability probe and the persistence Git runner use it; the topology clone's exit wait also returns once its deadline kill fires.
…cannot strand consumer shutdown (#5787) * fix(persistence): bound async git children so a lost exit cannot strand consumer shutdown Bun 1.3.x drops one-shot pidfd and pipe events when a callback re-enters the event loop, as bun:test expect().resolves/.rejects does (oven-sh/bun#30301). An execFile child whose exit is dropped stays a zombie and its callback, and its own timeout, never fire. The persistence consumer's durability probe (isDurabilityHardenedAsync, async since v0.60.10.0) spawns two git children per git effect, so a test awaiting .rejects while effects drained could leave the effects worker waiting forever; consumer.stop() awaits that worker, so disposePersistenceConsumer and every later fixture in the file hung ("killed N dangling process" is Bun reporting the unreaped children at the timeout). Seen in managed-maintenance, persistence-reconcile and google-attachments E2E. execFileBounded settles from its own timer at the deadline or on abort and SIGKILLs the child. The durability probe and the persistence Git runner use it; the topology clone's exit wait also returns once its deadline kill fires. * v0.60.16.0 fix(persistence): bound async git children so a lost exit cannot strand consumer shutdown
setup-bun's default goes from 1.3.13 to 1.4.4. The test-cli job's own `bun-version: "1.3.14"` override is dropped: it existed because 1.3.13 watched a child's pidfd with EPOLLONESHOT, so an exit event skipped when a callback re-entered the loop was lost and spawnSync spun beside a zombie tmux client until the watchdog stopped the suite (ct-71000, fixed in bun by oven-sh/bun#30301); 1.4.4 is past that fix. The setup-bun comment recorded that the pin stayed below 1.3.14 because 1.3.14 under --isolate ran a test preload once instead of per file, so a mock the web preload installs handed each file the first file's modules. Whether 1.4.4 still does that is not known; the web job on this branch is the check. The comment now states only the constraint. The cli unit step runs `bun test src/ --parallel --bail=5` instead of `--isolate`: parallel implies a fresh global per file and spreads the files over one worker per CPU. Measured on Linux in an ubuntu 24.04 container, bun 1.4.2, the same command: serial `--isolate` on 4 CPUs 1157s, `--parallel=4` on 4 CPUs 391s, `--parallel` with 16 workers 196s. No test collided on shared state; the two that failed under load are fixed in the previous commit. Left alone: the web job's sequential shard loop, the release workflows (accelerate-cli-staging, cut-cli-release, cut-extension-release, finalize-cli-release, all 1.3.14), the root packageManager, eas.json, and scripts/ci/quiet-watchdog.sh. The watchdog still fits: it only watches the log's size, names the last `src/...test.ts` line it saw (any worker's, which is still where output stopped) and SEGVs every `bun` process, workers included. `bun test scripts/ci/` passes (150 tests). No other job in ci.yml passes its own bun-version.
setup-bun's default goes from 1.3.13 to 1.4.4. The test-cli job's own `bun-version: "1.3.14"` override is dropped: it existed because 1.3.13 watched a child's pidfd with EPOLLONESHOT, so an exit event skipped when a callback re-entered the loop was lost and spawnSync spun beside a zombie tmux client until the watchdog stopped the suite (ct-71000, fixed in bun by oven-sh/bun#30301); 1.4.4 is past that fix. The setup-bun comment recorded that the pin stayed below 1.3.14 because 1.3.14 under --isolate ran a test preload once instead of per file, so a mock the web preload installs handed each file the first file's modules. Whether 1.4.4 still does that is not known; the web job on this branch is the check. The comment now states only the constraint. The cli unit step runs `bun test src/ --parallel --bail=5` instead of `--isolate`: parallel implies a fresh global per file and spreads the files over one worker per CPU. Measured on Linux in an ubuntu 24.04 container, bun 1.4.2, the same command: serial `--isolate` on 4 CPUs 1157s, `--parallel=4` on 4 CPUs 391s, `--parallel` with 16 workers 196s. No test collided on shared state; the two that failed under load are fixed in the previous commit. Left alone: the web job's sequential shard loop, the release workflows (accelerate-cli-staging, cut-cli-release, cut-extension-release, finalize-cli-release, all 1.3.14), the root packageManager, eas.json, and scripts/ci/quiet-watchdog.sh. The watchdog still fits: it only watches the log's size, names the last `src/...test.ts` line it saw (any worker's, which is still where output stopped) and SEGVs every `bun` process, workers included. `bun test scripts/ci/` passes (150 tests). No other job in ci.yml passes its own bun-version.
What
On Linux, a subprocess's pidfd was registered with
EPOLLONESHOT. If the event was dropped in user-space afterepoll_waitreturned it (beforeonUpdateran), the kernel had already disarmed the fd, so the process's'exit'event never fired — it only arrived when the next unrelated timer happened to wake the loop.Observed in the wild as a 5s
afterAlltimeout inanthropic-experimental/sandbox-runtimeon GH Actionsubuntu-24.04x86 runners (~80% hit rate): twosocatbridges withstdio: 'ignore'are SIGTERM'd together; both exit within a few ms, but one's'exit'event doesn't fire until the 5000mssetTimeoutfallback.Root cause
epoll_waitreturns a batch of ready events intoloop->ready_pollsand disarms everyEPOLLONESHOTfd in that batch before user-space sees any of them.us_internal_dispatch_ready_pollsthen iterates the batch vialoop->current_ready_poll.A poll callback can re-enter
us_loop_run_bun_tick— thetick_depthguard inloop.cacknowledges this forexpect().toThrow()→waitForPromise→autoTick, and the same applies toexpect().resolves/.rejectsand any otherwaitForPromisecaller. The inner tick callsepoll_waitagain, overwritingloop->ready_polls,num_ready_polls, andcurrent_ready_poll. When control returns to the outer dispatch loop, its remaining indices now point at the inner tick's data (or past the newnum_ready_polls), so those events are silently skipped.For a one-shot pidfd, a skipped event is unrecoverable: the fd is disarmed in the kernel,
onUpdatenever ran so.needs_rearmwas never set, and nothing re-arms it. The nextepoll_waitcan't return it.Fix
Register the pidfd level-triggered (no
EPOLLONESHOT) on Linux. A pidfd stays readable from process exit untilclose(), so a droppedready_pollsslot is harmless — the nextepoll_waitjust returns it again. Afterwait4succeeds we close the pidfd anyway (viaProcess.close()), which removes it from epoll, so there's no busy-loop.rewatchPosixstill defensively re-registers ifwait4(WNOHANG)returns 0; with level-triggered that's a harmlessCTL_MOD.macOS/FreeBSD continue to use
EV_ONESHOTwithEVFILT_PROC+NOTE_EXIT, which is inherently once-per-process and auto-removed by the kernel.This doesn't address the underlying nested-tick
ready_pollscorruption (which also affects other one-shotFilePollowners), but pidfds are the case where it's both silent and common — pipes/sockets report the drop viaEPOLLHUPon the next wait, whereas a disarmed pidfd has no second signal.Verification
test/js/bun/spawn/pidfd-exit-nested-tick.test.tsspawns 20stdio: 'ignore'children so their pidfd events land in oneepoll_waitbatch, then forces a nestedautoTickfrom the firstonExitviaexpect(Bun.sleep(1)).resolves.toBe(undefined).bun bdwithout fixbun bdwith fixbun run zig:check-allpasses for all targets.