Skip to content

Commit 1f43832

Browse files
committed
fix(spawn): avoid blocking macOS ESRCH exit waits
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. (cherry picked from commit c45701b)
1 parent c46b1aa commit 1f43832

4 files changed

Lines changed: 121 additions & 45 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased
44

55
- Add `Bun.Terminal.pause()` and `resume()` for output backpressure: child writes block when the PTY queue fills, and PTY exit follows resumed output delivery.
6+
- Keep macOS subprocess exit handling non-blocking when kqueue reports ESRCH before a terminal child can be reaped.
67

78
- Preserve file-URL entry identity and literal `?` paths in `Bun.ModuleGraph`, and avoid retaining GC-backed string views across macro transpilation.
89
- Prepare daily or manually requested upstream merges as frozen draft PRs, preserving fork history and stopping visibly on conflicts or permission failures.

‎src/io/posix_event_loop.rs‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,9 @@ static MAX_GENERATION_NUMBER: core::sync::atomic::AtomicUsize =
153153
/// generation number); FreeBSD only has the plain `struct kevent`.
154154
#[cfg(target_os = "macos")]
155155
type KQueueEvent = bun_sys::darwin::kevent64_s;
156+
157+
#[cfg(target_os = "macos")]
158+
const PROCESS_REAP_RETRY_MS: i64 = 10;
156159
#[cfg(target_os = "freebsd")]
157160
type KQueueEvent = bun_sys::freebsd::Kevent;
158161

@@ -691,9 +694,21 @@ impl FilePoll {
691694
},
692695
Flags::Process => kevent64_s {
693696
ident: u64::try_from(fd.native()).expect("int cast"),
694-
filter: EVFILT::PROC,
695-
data: 0,
696-
fflags: NOTE::EXIT,
697+
filter: if self.flags.contains(Flags::ProcessRetry) {
698+
libc::EVFILT_TIMER
699+
} else {
700+
EVFILT::PROC
701+
},
702+
data: if self.flags.contains(Flags::ProcessRetry) {
703+
PROCESS_REAP_RETRY_MS
704+
} else {
705+
0
706+
},
707+
fflags: if self.flags.contains(Flags::ProcessRetry) {
708+
0
709+
} else {
710+
NOTE::EXIT
711+
},
697712
udata: Pollable::init(self).ptr() as u64,
698713
flags: EV::ADD | one_shot_flag,
699714
ext: [self.generation_number as u64, 0],
@@ -743,7 +758,17 @@ impl FilePoll {
743758
&raw const TIMEOUT,
744759
)
745760
};
746-
if sys::get_errno(rc) == sys::E::EINTR {
761+
let errno = sys::get_errno(rc);
762+
if errno == sys::E::EINTR {
763+
continue;
764+
}
765+
if errno == sys::E::ESRCH && changelist[0].filter == EVFILT::PROC {
766+
// An exiting PTY session leader may need this loop to drain output before wait4 can reap it.
767+
self.flags.insert(Flags::ProcessRetry);
768+
changelist[0].filter = libc::EVFILT_TIMER;
769+
changelist[0].flags = EV::ADD | EV::ONESHOT;
770+
changelist[0].fflags = 0;
771+
changelist[0].data = PROCESS_REAP_RETRY_MS;
747772
continue;
748773
}
749774
break 'rc rc;
@@ -977,7 +1002,7 @@ impl FilePoll {
9771002
}
9781003
#[cfg(target_os = "macos")]
9791004
{
980-
use bun_sys::darwin::{EV, EVFILT, NOTE, kevent64, kevent64_s};
1005+
use bun_sys::darwin::{EV, EVFILT, kevent64, kevent64_s};
9811006
// SAFETY: all-zero is a valid kevent64_s
9821007
let mut changelist: [kevent64_s; 2] = bun_core::ffi::zeroed();
9831008

@@ -1011,9 +1036,13 @@ impl FilePoll {
10111036
},
10121037
Flags::Process => kevent64_s {
10131038
ident: u64::try_from(fd.native()).expect("int cast"),
1014-
filter: EVFILT::PROC,
1039+
filter: if self.flags.contains(Flags::ProcessRetry) {
1040+
libc::EVFILT_TIMER
1041+
} else {
1042+
EVFILT::PROC
1043+
},
10151044
data: 0,
1016-
fflags: NOTE::EXIT,
1045+
fflags: 0,
10171046
udata: Pollable::init(self).ptr() as u64,
10181047
flags: EV::DELETE,
10191048
ext: [0, 0],
@@ -1146,6 +1175,8 @@ impl FilePoll {
11461175
self.flags.remove(Flags::PollProcess);
11471176
self.flags.remove(Flags::PollMachport);
11481177
self.flags.remove(Flags::PollMemoryPressure);
1178+
#[cfg(target_os = "macos")]
1179+
self.flags.remove(Flags::ProcessRetry);
11491180

11501181
sys::Result::Ok(())
11511182
}
@@ -1210,6 +1241,9 @@ pub enum Flags {
12101241
IgnoreUpdates,
12111242

12121243
Socket,
1244+
1245+
#[cfg(target_os = "macos")]
1246+
ProcessRetry,
12131247
}
12141248

12151249
pub type FlagsSet = enumset::EnumSet<Flags>;

‎src/spawn/process.rs‎

Lines changed: 4 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -362,44 +362,10 @@ impl Process {
362362

363363
#[cfg(unix)]
364364
fn on_wait_pid(&mut self, waitpid_result: &bun_sys::Result<WaitPidResult>, rusage: &Rusage) {
365-
let pid = self.pid;
366-
// Mutated only on the macOS ESRCH retry path below.
367-
#[cfg(target_os = "macos")]
368-
let mut rusage_result = *rusage;
369-
#[cfg(not(target_os = "macos"))]
370-
let rusage_result = *rusage;
371-
372-
let status: Option<Status> = Status::from(pid, waitpid_result).or_else(|| 'brk: {
373-
match self.rewatch_posix() {
374-
Ok(()) => {}
375-
Err(err_) => {
376-
#[cfg(target_os = "macos")]
377-
if err_.get_errno() == bun_sys::E::ESRCH {
378-
break 'brk Status::from(
379-
pid,
380-
&posix_spawn::wait4(
381-
pid,
382-
// Normally we would use WNOHANG to avoid blocking the event loop.
383-
// However, there seems to be a race condition where the operating system
384-
// tells us that the process has already exited (ESRCH) but the waitpid
385-
// call with WNOHANG doesn't return the status yet.
386-
// As a workaround, we use 0 to block the event loop until the status is available.
387-
// This should be fine because the process has already exited, so the data
388-
// should become available basically immediately. Also, testing has shown that this
389-
// occurs extremely rarely and only under high load.
390-
0,
391-
Some(&mut rusage_result),
392-
),
393-
);
394-
}
395-
break 'brk Some(Status::Err(err_));
396-
}
397-
}
398-
None
399-
});
400-
365+
let status = Status::from(self.pid, waitpid_result)
366+
.or_else(|| self.rewatch_posix().err().map(Status::Err));
401367
let Some(status) = status else { return };
402-
self.on_exit(status, &rusage_result);
368+
self.on_exit(status, rusage);
403369
}
404370

405371
pub fn watch_or_reap(&mut self) -> bun_sys::Result<bool> {
@@ -413,7 +379,7 @@ impl Process {
413379
Err(err) => {
414380
#[cfg(unix)]
415381
if err.get_errno() == bun_sys::E::ESRCH {
416-
self.wait(true);
382+
self.wait(!cfg!(target_os = "macos"));
417383
return Ok(self.has_exited());
418384
}
419385
Err(err)

‎test/js/bun/terminal/terminal-spawn.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -807,3 +807,78 @@ describe("Bun.Terminal output flow control", () => {
807807
expect(code).toBe(0);
808808
});
809809
});
810+
811+
// macOS can reject EVFILT_PROC while a PTY session leader is still draining in exit().
812+
// Delay the real registration until exit starts; do not synthesize ESRCH.
813+
test.skipIf(process.platform !== "darwin")("ESRCH while a terminal child exits does not block PTY reads", async () => {
814+
using dir = tempDir("terminal-esrch", {
815+
"delay-watch.c": `
816+
#include <sys/event.h>
817+
#include <libproc.h>
818+
#include <sys/proc_info.h>
819+
#include <time.h>
820+
#include <unistd.h>
821+
#include <errno.h>
822+
823+
static int delayed_kevent64(int kq, const struct kevent64_s *changes, int count,
824+
struct kevent64_s *events, int capacity, unsigned int flags, const struct timespec *timeout) {
825+
for (int i = 0; i < count; i++) {
826+
if (changes[i].filter != EVFILT_PROC || !(changes[i].flags & EV_ADD)) continue;
827+
struct timespec start, now;
828+
clock_gettime(CLOCK_MONOTONIC, &start);
829+
for (;;) {
830+
struct proc_bsdinfo info;
831+
int size = proc_pidinfo((int)changes[i].ident, PROC_PIDTBSDINFO, 0, &info, sizeof(info));
832+
if (size != sizeof(info) || (info.pbi_flags & PROC_FLAG_INEXIT)) break;
833+
clock_gettime(CLOCK_MONOTONIC, &now);
834+
if (now.tv_sec - start.tv_sec >= 2) break;
835+
struct timespec pause = {0, 100000};
836+
nanosleep(&pause, NULL);
837+
}
838+
}
839+
int result = kevent64(kq, changes, count, events, capacity, flags, timeout);
840+
if (result == -1 && errno == ESRCH) {
841+
int saved = errno;
842+
write(2, "ESRCH-before-reap\\n", 18);
843+
errno = saved;
844+
}
845+
return result;
846+
}
847+
__attribute__((used, section("__DATA,__interpose")))
848+
static const struct { const void *replacement; const void *original; } interpose = {
849+
(const void *)delayed_kevent64, (const void *)kevent64
850+
};
851+
`,
852+
"fixture.js": `
853+
let output = "";
854+
const proc = Bun.spawn(["/bin/sh", "-c", 'printf "%0512d" 0; exit 3'], {
855+
terminal: { data(_, bytes) { output += new TextDecoder().decode(bytes); } },
856+
});
857+
const code = await proc.exited;
858+
proc.terminal.close();
859+
console.log(JSON.stringify({ length: output.length, code }));
860+
`,
861+
});
862+
const library = `${dir}/delay-watch.dylib`;
863+
await using compiler = Bun.spawn({
864+
cmd: ["cc", "-dynamiclib", `${dir}/delay-watch.c`, "-o", library],
865+
env: bunEnv,
866+
stdout: "pipe",
867+
stderr: "pipe",
868+
});
869+
const compilerError = await compiler.stderr.text();
870+
expect(compilerError).toBe("");
871+
expect(await compiler.exited).toBe(0);
872+
await using proc = Bun.spawn({
873+
cmd: [bunExe(), `${dir}/fixture.js`],
874+
env: { ...bunEnv, DYLD_INSERT_LIBRARIES: library },
875+
stdout: "pipe",
876+
stderr: "pipe",
877+
timeout: 3000,
878+
killSignal: "SIGKILL",
879+
});
880+
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
881+
expect(stderr).toContain("ESRCH-before-reap");
882+
expect(JSON.parse(stdout)).toEqual({ length: 512, code: 3 });
883+
expect(exitCode).toBe(0);
884+
});

0 commit comments

Comments
 (0)