Skip to content

process: drop EPOLLONESHOT for Linux pidfd exit poll - #30301

Merged
Jarred-Sumner merged 4 commits into
mainfrom
farm/e8e306ad/pidfd-no-oneshot
May 6, 2026
Merged

Jarred-Sumner merged 4 commits into
mainfrom
farm/e8e306ad/pidfd-no-oneshot

Conversation

@robobun

@robobun robobun commented May 5, 2026

Copy link
Copy Markdown
Collaborator

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.

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.
@robobun

robobun commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:26 PM PT - May 5th, 2026

❌ @robobun, your commit 9bea577 has 3 failures in Build #51943 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 30301

That installs a local version of the PR into your bun-30301 executable, so you can run:

bun-30301 --bun

@github-actions github-actions Bot added the claude label May 5, 2026
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: dc1c461d-a387-48ed-9632-3a47471fde04

📥 Commits

Reviewing files that changed from the base of the PR and between 32c09f0 and 9bea577.

📒 Files selected for processing (1)
  • test/js/bun/spawn/pidfd-exit-nested-tick.test.ts

Walkthrough

Introduces a public compile-time constant process_poll_one_shot that disables one-shot polling on Linux and uses it when registering process-exit polls. Adds a Linux-only test that spawns many short-lived children and forces a nested tick to validate pidfd exit notifications under level-triggered behavior.

Changes

Process poll one-shot + pidfd nested-tick test

Layer / File(s) Summary
Polling Configuration
src/runtime/api/bun/process.zig
Adds pub const process_poll_one_shot = !Environment.isLinux with documentation describing platform-specific one-shot vs level-triggered behavior.
Core Registration Changes
src/runtime/api/bun/process.zig
Replaces literal true arguments to poller.fd.register in Process.watch and Process.rewatchPosix with process_poll_one_shot to make one-shot registration conditional on platform.
Tests
test/js/bun/spawn/pidfd-exit-nested-tick.test.ts
Adds a Linux-only test that spawns 20 short-lived child processes, triggers a synchronous nested tick inside onExit (via Bun.sleep(1)), and awaits all exits to ensure pidfd exit notifications are reliably observed under nested ticks.
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR addresses process exit event handling on Linux but is unrelated to linked issue #39 about Node.js bundler output compatibility. The PR should either be linked to a relevant issue about pidfd exit event handling, or the incorrect issue #39 should be removed from linked issues.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: dropping EPOLLONESHOT for Linux pidfd exit polling, which is the core fix.
Description check ✅ Passed The description provides excellent detail about what, why, root cause, fix, and verification, exceeding template requirements despite template being minimal.
Out of Scope Changes check ✅ Passed All changes are within scope: platform-dependent pidfd polling constant in process.zig and a Linux-only test for pidfd nested-tick behavior directly support the stated objective.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b009453 and 75e5954.

📒 Files selected for processing (2)
  • src/runtime/api/bun/process.zig
  • test/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).
@Jarred-Sumner
Jarred-Sumner merged commit ff38b2b into main May 6, 2026
48 of 60 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/e8e306ad/pidfd-no-oneshot branch May 6, 2026 00:50

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 setTimeout removal, my /bin/true → "true" nit) have been addressed in 32c09f0 and 9bea577 respectively.
  • robobun's most recent CI report still shows build-zig failing 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_polls corruption for other one-shot FilePoll owners — that's a reasonable scoping decision but worth a maintainer acknowledging.
  • rewatchPosix still calls this.ref() on success; with level-triggered the fd is already armed, so a defensive re-register now adds a ref without a corresponding extra onUpdate/deref. In practice wait4(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.

dylan-conway added a commit to anthropics/sandbox-runtime that referenced this pull request May 7, 2026
…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.
xhjkl pushed a commit to xhjkl/bun that referenced this pull request May 14, 2026
## 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>
garrytan added a commit to garrytan/gbrain that referenced this pull request Sep 30, 2026
…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.
capy-ai Bot pushed a commit to garrytan/gbrain that referenced this pull request Sep 30, 2026
…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
ashot pushed a commit to stevenpollack/codecast that referenced this pull request Nov 1, 2026
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.
ashot pushed a commit to codecast-sh/codecast that referenced this pull request Nov 2, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants