Repository navigation
fix(spawn): avoid blocking macOS ESRCH exit waits - #11
Merged
Merged
Conversation
Retry unreapable macOS process exits with a 10ms one-shot kqueue timer on the existing FilePoll. Preserve process and event-loop references without growing Process (120 bytes before and after on macOS arm64). A deterministic terminal test delays real EVFILT_PROC registration until child exit; the supplied baseline blocks until SIGKILL, while the fixed release build drains 512 bytes and returns exit code 3. Release validation: 325 passed, 29 skipped, 0 failed across 11 files. Windows x64 and arm64 workspace type checks pass.
This was referenced Sep 27, 2026
Author
# Conflicts: # CHANGELOG.md
steipete
added a commit
that referenced
this pull request
Sep 28, 2026
… control (#10) Bun.Terminal read the PTY master unconditionally, so a consumer had no way to push back on a fast child; drain only covers input. node-pty exposes pause() and resume() on its tty.ReadStream, and OpenClaw's Gateway terminals rely on them to stop a child once a viewer falls behind. pause() sets PAUSED and pauses the reader, unregistering its poll: no data callback fires after pause() returns, including from inside a data callback, and the POSIX PipeReader loop now stops when a pause lands during dispatch, even after HUP. resume() re-arms on a later event-loop turn through a deferred task that holds a native reference and never dispatches synchronously; close() and dispose cancel a pending resume. A terminal-owned KeepAlive covers the paused interval and honors ref()/unref(). Windows maps to WindowsBufferedReader pause/unpause, and close() unpauses so ConPTY can drain during shutdown. While paused, a child blocks once the PTY queue fills and the exit callback fires only after output resumes and drains. On macOS an exiting session leader also stays in exit until its output is drained, so proc.exited may resolve only after resume(); the ESRCH exit fix (#11) is what keeps that path from blocking the event loop, and it ships with this change.
steipete
pushed a commit
to fuller-stack-dev/bun
that referenced
this pull request
Oct 20, 2026
…module-graph.test.ts (oven-sh#45674) ### What does this PR do? Fixes the flaky "50 graphs alive at once, each with its own state, then all exit and are collected" in `test/js/bun/module-graph/module-graph.test.ts`. It failed in 2 of 31 builds of main, 125686 to 127114 (Ubuntu 25.04 x64, Windows 11 aarch64) and passed on the retry. The test registered one array, `graphs[25].big`, with a `FinalizationRegistry` and failed if 100 collections did not finalize it. It now tracks the array of every one of the 50 graphs with `Lifetimes` from `module-graph-lifetimes.ts`, as `module-graph-gc.test.ts` does. There, an object that is not finalized counts as kept alive only if a root reaches it in the debugging heap snapshot, and the failure message is the path from that root. Two things change with the helper, and the first is what makes the runs below pass: 1. **Where the collection runs.** The helper calls `Bun.gc(true)` from a timer callback, main's `collected()` from the continuation of the async test. The `runInternalMicrotask` frame that holds the stale word (artifact 2) is not on the stack in a timer callback. In 240 of 240 runs all 50 arrays were finalized by the first collection. 2. **What is asserted if one is left.** Not that it was finalized, but that no root reaches it. ### Why it failed On main one of the 50 graphs outlives the collections in almost every run, and the test fails when that one is number 25. Whole file, CI's environment, 840 runs: | graphs left after the collections | 0 | 1 | 2 | 3 | |---|---|---|---|---| | runs | 2 | 802 | 3 | 33 | 12 of the 840 failed. In the failing runs looked at (9 heap snapshots, 12 stack dumps) nothing in the heap holds the one that is left, and one word on the native stack points at it. All of what follows is the Linux x64 binary that CI built for main at 7f3bc6a, with `BUN_GARBAGE_COLLECTOR_LEVEL=1 BUN_RUNTIME_TRANSPILER_CACHE_PATH=0` as in `scripts/runner.node.ts`. The failure needs both that environment and the whole file: 0 of 240 without the environment, 0 of 1600 with the test alone. I did not look at the Windows failure. <details><summary>Artifact 1: the heap snapshot</summary> `generateHeapSnapshotForDebugging()` right after the 100 collections. These are the array and every cell from which it can be reached: ``` snapshot: 27033 cells, 99750 edges, 586 roots; arrays named `big` still in it: 1 cell 1532 Promise 0x34cf520fa40 incoming edges 0 in `roots` no a root reaches it no cell 1555 ModuleRecord 0x34cf527e980 incoming edges 3 in `roots` no a root reaches it no cell 1573 ModuleNamespaceObject 0x34cef51dd50 incoming edges 3 in `roots` no a root reaches it no cell 1591 JSModuleEnvironment 0x34cf5278950 incoming edges 3 in `roots` no a root reaches it no cell 1626 Array 0x34cef3755a0 incoming edges 2 in `roots` no a root reaches it no cell 1631 Function 0x34cef45a100 incoming edges 2 in `roots` no a root reaches it no cell 1653 Function 0x34cef45a0e0 incoming edges 2 in `roots` no a root reaches it no ``` The snapshots of 8 other failing runs have the same seven kinds of cell, with the `Promise` (fulfilled with the `ModuleRecord`) as the only one without an incoming edge. </details> <details><summary>Artifact 2: the stack word and the frame that owns it (gdb, same run as artifact 1)</summary> The test writes the snapshot and sends itself SIGUSR2, and gdb stops there. ``` Thread 1 "bun-profile" received signal SIGUSR2, User defined signal 2. (gdb) info registers rsp rbp rsp 0x7fffffffa0c8 rbp 0x7fffffffa240 words in [rsp, end of stack) = [0x7fffffffa0c8, 0x7ffffffff000) that point into one of those cells: 1 0x7fffffffa8a0 holds 0x34cf520fa40 = Promise+0; it lies in the frame with rbp 0x7fffffffa8f0, at rbp-0x50 (gdb) x/gx 0x7fffffffa8a0 0x7fffffffa8a0: 0x0000034cf520fa40 (gdb) info symbol 0x1bccee0 # where that frame's callee returns to JSC::runInternalMicrotask(...) + 6976 rbp chain openclaw#3 rbp 0x7fffffffa540 Bun::Process_functionKill openclaw#4 rbp 0x7fffffffa550 (JIT code) openclaw#5 rbp 0x7fffffffa5d0 op_call_ignore_result_return_location openclaw#6 rbp 0x7fffffffa680 llint_call_javascript openclaw#7 rbp 0x7fffffffa7e0 JSC::asyncFunctionGeneratorBodyCall openclaw#8 rbp 0x7fffffffa8f0 JSC::runInternalMicrotask <- owns 0x7fffffffa8a0 openclaw#9 rbp 0x7fffffffab70 JSC::MicrotaskQueue::drainWithUseCallOnEachMicrotask openclaw#10 rbp 0x7fffffffac00 JSC::VM::drainMicrotasks openclaw#11 rbp 0x7fffffffac20 Zig::GlobalObject::drainMicrotasks openclaw#12 rbp 0x7fffffffac50 <bun_jsc::event_loop::EventLoop>::exit openclaw#13 rbp 0x7fffffffacf0 TimerObjectInternals::fire ``` 12 failing runs that dumped their own stack from `/proc/self/mem` show the same: one word, `Promise+0`, at `rbp-0x50` of `runInternalMicrotask`. In the 5 of them where I looked for it, the frame's callee returns to the same `0x1bccee0`, which is `JSMicrotask.cpp:2053`. **Who wrote it.** A hardware watchpoint on `0x7fffffffa8a0`, set at the first line of the test, sees 10 writes. The last one is the `Promise`: `pushq %r14` in the prologue of `JSC::ModuleGraphLoadingState::create` (`ModuleGraphLoadingState.cpp:71`, rbp `0x7fffffffa8b0`), which saves a register of its caller. **Why it stays.** The 100 collections run in the continuation of an async function, so each runs under a `runInternalMicrotask` frame at that same address. In the disassembly the function has 9 stores to `-0x50(%rbp)`. Following the jump table and every branch, only case 14 of the switch (resume an async function) reaches the call at `JSMicrotask.cpp:2053`, and none of the 9 stores is on a way to it. The slot is inside a live frame, so stack sanitizing does not cover it. So the graph that is left is the one whose load called `create` last at that depth. </details> ### How did you verify your code works? **Failure rate.** Whole file, 12 copies side by side, main and this PR in alternating rounds: | | main | this PR | |---|---|---| | runs that failed | 12 of 1200 (all this test) | 0 of 1200 | **What the snapshot says about a survivor.** With this PR there was none to ask about: in those 240 runs, with a logging copy of the helper, the snapshot was never taken. So this is main's test as it is, followed by the helper's `Heap` asked about the 50 addresses, 1080 runs. The old assertion failed in 12 of them. In 11 the array was in the snapshot with no root reaching it, in 1 it was gone by then, in 0 a root reached it. In 7 of the 1080 runs a root did reach two other arrays. In the one run whose paths were printed, both start at `root(JITWorkList)`, a compilation that is still running. `stillAlive` goes on collecting while a root reaches something. **Real references must fail.** One line added before `graphs.length = 0`. All 9 fail, with these messages: | graph 25 is held by | message | |---|---| | a global, the namespace | `root(ProtectedValues) GlobalObject -Property:held-> ModuleNamespaceObject -> ModuleRecord -> JSModuleEnvironment -> Array` | | a global closure over `inc` | `root(ProtectedValues) GlobalObject -Property:held-> Function -> JSLexicalEnvironment -Variable:inc-> Function(inc) -> JSModuleEnvironment -> Array` | | a local of the suspended test | `root(Output) FunctionCodeBlock -> ... -Variable:pendingHeap-> Promise -> AsyncFunctionGenerator -> ...` | | `setInterval(inc)` | `root(StrongHandles) StrongRootBlock -> Timeout -Property:callback-> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | | `process.on(..., inc)` | `root(ProtectedValues) GlobalObject -> Process -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | | a reaction of a pending promise | `root(ProtectedValues) GlobalObject -Property:held-> Promise -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | | a `FinalizationRegistry` held value | `root(ProtectedValues) GlobalObject -Property:held-> FinalizationRegistry -> Array` | | a `WeakMap` value of a live key | `root(Output) Array` | | an `AbortSignal` listener | `root(WeakSets) AbortSignal -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` | With `globalThis.held = graphs[7]` instead, main's test passes 5 of 5 and this PR's fails 5 of 5. **Debug build**, default timeout: the test passes 6 of 6 alone and in 6 of 6 runs of the whole file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Stops macOS process-exit handling from blocking the event loop when kqueue reports
ESRCHfor a child that is still exiting.Process::on_wait_pid(andwatch_or_reapat spawn time) handledEVFILT_PROCattach failing withESRCHby calling a blockingwait4(pid, 0)on the event-loop thread, on the assumption that the status "should become available basically immediately". That assumption is false for PTY children. macOS refusesEVFILT_PROConce a process has entered exit, but a session leader with a controlling terminal stays in exit (STAT E) until its PTY output queue is drained, and only this same event loop drains it. The result is a permanent deadlock. It was observed as a Bun thread stuck for minutes in__wait4_nocancelviaspawn_maybe_sync→Process::on_wait_pid, triggered by inline-terminal children that print and exit before Bun registers the process watch (load-dependent).FilePollregistration for a process on macOS turns anESRCHfromEVFILT_PROCinto a 10 ms one-shotEVFILT_TIMERon the same poll (Flags::ProcessRetry). When it fires, the existing process wakeup retrieswait4(WNOHANG)and re-registers until the child is reapable. References and keep-alive are unchanged, andProcessstays 120 bytes.watch_or_reapno longer takes the synchronous wait on macOS.on_wait_pidloses the blocking branch and its misleading comment.spawnSync's own blocking path are unchanged.How did you verify your code works?
macOS arm64 release builds:
terminal-spawn.test.tscase "ESRCH while a terminal child exits does not block PTY reads". A test-localDYLDinterposer onkevent64delays the realEVFILT_PROCattach until the child has entered exit. It does not fakeESRCH; the kernel returns it. The unmodified base build blocks until the watchdog's SIGKILL; this build drains all 512 bytes and reports exit code 3. The test needs the macOS C compiler.terminal/terminal,terminal/terminal-platform-gaps,terminal/terminal-spawn,spawn/spawn,spawn/exit-code,spawn/spawn-signal,spawn/spawn_waiter_thread,spawn/spawn-stress,spawn/spawnsync-isolated-event-loop,spawn/spawnsync-no-microtask-drain;pidfd-exit-nested-tickis Linux-only).