Skip to content

fix(io): stop Process.run draining descendant pipes - #1054

Merged
nicolas-abril merged 3 commits into
bendlang:mainfrom
Yi-111-a:fix/process-run-descendant-drain
Sep 25, 2026
Merged

nicolas-abril merged 3 commits into
bendlang:mainfrom
Yi-111-a:fix/process-run-descendant-drain

Conversation

@Yi-111-a

Copy link
Copy Markdown
Contributor

Summary

  • bound post-reap stdout/stderr draining to the bytes readable when the direct child is reaped
  • stop the native loop after that bounded drain so a descendant holding an inherited pipe cannot extend Process.run
  • retry interrupted FIONREAD and treat nonblocking reads as drained
  • add a regression for a background writer holding the inherited stdout pipe

Fixes #1051

Verification

  • BEND_NO_TELEMETRY=1 bun bend2/main.ts tests/io/process_run.bend --check-only
  • emitted native C compiled with clang 19 and executed; all Process.run checks returned True
  • git diff --check
  • bun gates/repo.ts could not run because ttok is not installed in this environment

The local Linux/Bun 1.4.2 JS lane reports max-buffer/timeout differences for descendant cases; the issue was reported on macOS/Bun, where the JS lane returns Done.

@nicolas-abril nicolas-abril self-assigned this Sep 25, 2026

@nicolas-abril nicolas-abril left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for picking up #1051. Bounding the post-reap drain with FIONREAD is the right idea. A child can't exit while blocked on a write, so all of its own output is already in the pipe when it's reaped. But on macOS this doesn't fix the issue yet, and the new test fails on the C lane there. The test gate runs on Macs, so it would go red.

What I see on macOS (M4)

  • tests/io/process_run.bend from this branch: every JS line is True. The C lane prints descendant output: unexpected failure.
  • The issue's call, Process.run("/bin/sh", ["-c", "yes & echo hi"], "", 65536, 1500), run 10 times:
    • C: Fail 27 File too large 10/10.
    • JS: Done, with stdout exactly hi\n, every time.
  • The same call with max_output at 1 MB: C answers Done, but with 57–74 KB of stdout.

Why

The loop only notices the child's exit at its next waitpid. Meanwhile poll can sleep up to 50 ms after sh has already exited:

  1. yes writes, which wakes poll.
  2. The loop reads 8 KB of yes output.
  3. The next pass reaps sh, but by then yes has refilled the pipe.
  4. The FIONREAD drain takes a full 64 KB pipe of yes output.

That adds up to 3 + 8192 + 65536 = 73731 bytes, which is exactly the size seen, and it's over 65536.

Suggested fix: wake on the child's exit

Add one more descriptor to the existing poll set that becomes readable when the child exits:

  • macOS: a kqueue watching the child's exit (EVFILT_PROC / NOTE_EXIT). poll does report a kqueue as readable on macOS.
  • Linux: a pidfd_open descriptor.

The loop then sleeps until a pipe is ready, stdin is writable, the child exits, or the deadline passes, and the 50 ms tick goes away. If the descriptor can't be created, the loop falls back to today's 50 ms tick. Your FIONREAD drain then runs at the moment of exit, which is what Bun.spawnSync effectively does.

I prototyped this on top of your branch (diff below). On the same M4:

  • The issue's call: Done 0 with stdout hi\n, 10/10, the same as JS.
  • The full test file: every line True.
  • Not tested: the Linux (pidfd) path.

Smaller points

  • drain flag: it is always equal to child < 0, so it can go.
  • Dead code: once the loop breaks right after the drain, int ms = 0 (the post-reap case), if (child < 0 && count == 0) and if (ready == 0 && child < 0) can never run.
  • The test stays timing-dependent: under load (20 runs in parallel), even the prototype failed the issue's call once in 40 runs. Nothing can tell the child's bytes from the grandchild's in a shared pipe, so the result depends on whether yes is scheduled before sh exits. Please use a larger max_output in the test, for example 1 MB. main still fails it deterministically, because it drains yes forever, while a fixed version answers Done.
  • Linux JS lane: the max-buffer and timeout differences you saw for descendant cases are Bun's behaviour and a separate issue. Feel free to open one.
Prototype diff (on top of this branch)
diff --git a/bend2/effs/process_run.c b/bend2/effs/process_run.c
index e4ccb52a..add7688e 100644
--- a/bend2/effs/process_run.c
+++ b/bend2/effs/process_run.c
@@ -4,6 +4,11 @@
 #include <spawn.h>
 #include <sys/ioctl.h>
 #include <sys/wait.h>
+#ifdef __APPLE__
+#include <sys/event.h>
+#else
+#include <sys/syscall.h>
+#endif
 
 extern char** environ;
 
@@ -94,6 +99,22 @@ static bool process_drain(ProcessCall* p, int fd, bool error) {
   return true;
 }
 
+// A descriptor that polls readable once the child exits.
+static int process_exitfd(pid_t child) {
+#ifdef __APPLE__
+  int kq = kqueue();
+  struct kevent ev;
+  EV_SET(&ev, child, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
+  if (kq >= 0 && kevent(kq, &ev, 1, NULL, 0, NULL) != 0) {
+    close(kq);
+    kq = -1;
+  }
+  return kq;
+#else
+  return (int)syscall(SYS_pidfd_open, child, 0);
+#endif
+}
+
 static int process_nonblock(int fd) {
   int flags = fcntl(fd, F_GETFL);
   return flags < 0 ? -1 : fcntl(fd, F_SETFL, flags | O_NONBLOCK);
@@ -124,7 +145,7 @@ static void process_call(IoWork* w) {
   int pipes[3][2] = {{-1, -1}, {-1, -1}, {-1, -1}};
   pid_t child = -1;
   int status = 0;
-  bool drain = false;
+  int exitfd = -1;
   for (int i = 0; i < 3; i += 1) {
     if (process_pipe(pipes[i]) != 0) {
       p->code = errno;
@@ -191,6 +212,7 @@ static void process_call(IoWork* w) {
   if (p->input_len == 0) {
     close(pipes[0][1]); pipes[0][1] = -1;
   }
+  exitfd = process_exitfd(child);
   u64 deadline = io_tick() + (u64)p->timeout * 1000000ull;
   u64 written  = 0;
   while (p->code == 0) {
@@ -198,7 +220,6 @@ static void process_call(IoWork* w) {
       pid_t got = waitpid(child, &status, WNOHANG);
       if (got == child) {
         child = -1;
-        drain = true;
         if (pipes[0][1] >= 0) {
           close(pipes[0][1]); pipes[0][1] = -1;
         }
@@ -207,7 +228,7 @@ static void process_call(IoWork* w) {
         break;
       }
     }
-    if (drain) {
+    if (child < 0) {
       for (int i = 1; i < 3; i += 1) {
         if (pipes[i][0] >= 0 && !process_drain(p, pipes[i][0], i == 2)) {
           break;
@@ -220,8 +241,8 @@ static void process_call(IoWork* w) {
       p->code = ETIMEDOUT;
       break;
     }
-    struct pollfd fds[3];
-    int roles[3];
+    struct pollfd fds[4];
+    int roles[4];
     nfds_t count = 0;
     for (int i = 0; i < 3; i += 1) {
       int fd = i == 0 ? pipes[0][1] : pipes[i][0];
@@ -230,15 +251,13 @@ static void process_call(IoWork* w) {
         roles[count++] = i;
       }
     }
-    if (child < 0 && count == 0) {
-      break;
-    }
-    int ms = 0;
-    if (child >= 0) {
-      u64 left = (deadline - now + 999999ull) / 1000000ull;
-      ms = (int)(left > 50 ? 50 : left);
+    if (exitfd >= 0) {
+      fds[count] = (struct pollfd){exitfd, POLLIN, 0};
+      roles[count++] = 3;
     }
-    int ready = poll(fds, count, ms);
+    u64 left = (deadline - now + 999999ull) / 1000000ull;
+    u64 most = exitfd >= 0 ? 1000000 : 50;
+    int ready = poll(fds, count, (int)(left > most ? most : left));
     if (ready < 0) {
       if (errno == EINTR) {
         continue;
@@ -246,8 +265,8 @@ static void process_call(IoWork* w) {
       p->code = errno;
       break;
     }
-    if (ready == 0 && child < 0) {
-      break;
+    if (exitfd >= 0 && fds[count - 1].revents != 0) {
+      continue;
     }
     for (nfds_t k = 0; k < count && p->code == 0; k += 1) {
       if (fds[k].revents == 0) {
@@ -292,6 +311,9 @@ static void process_call(IoWork* w) {
       : WIFSIGNALED(status) ? 128 + (u32)WTERMSIG(status) : 1;
   }
 done:
+  if (exitfd >= 0) {
+    close(exitfd);
+  }
   for (int i = 0; i < 3; i += 1) {
     for (int j = 0; j < 2; j += 1) {
       if (pipes[i][j] >= 0) {

This review was written with AI assistance (Claude Code) and checked by me.

The post-reap drain only ran once the loop noticed the child at its next
waitpid, up to 50 ms after it exited, so a descendant that refilled the
pipe in that window was drained whole. Poll an extra descriptor that
becomes readable at exit -- a kqueue on NOTE_EXIT for macOS, a pidfd on
Linux -- and fall back to the tick where neither exists.

The drain flag was always equal to child < 0, and the count == 0 and
ready == 0 branches below it could never run, so they go too. Role 3 is
the exit descriptor, which carries no pipe.

The descendant test takes 1 MB of headroom: nothing in a shared pipe
tells the child's bytes from its descendants', so whether "hi" survives
depends on whether the grandchild is scheduled first.
@Yi-111-a

Copy link
Copy Markdown
Contributor Author

Pushed d4db1a3. All of it: the EVFILT_PROC/NOTE_EXIT kqueue and the pidfd in the poll set, the drain flag gone, the three dead branches gone, and the test at 1 MB.

Your diagnosis matched what I measured. I pulled the real process_call out into a standalone harness (gcc, so I can iterate; the box has no clang) and ran the issue's call against the pre-fix code, and it reproduces your arithmetic exactly:

stdout bytes for Process.run("/bin/sh", ["-c", "yes & echo hi"], "", <max>, 1500)
pre-fix 3, 8195, 65539, 73731, 139267, 212995
with the exit descriptor 3 (10/12), 8195 (1/12)

73731 is your 3 + 8192 + 65536. The spread is the point: without the descriptor the drain reads whatever yes managed to put in the pipe during the tick, so the result is a function of scheduling. With it, the drain runs at the exit, and the only residue is the one partial 8 KB read that wins the race against the notification, which is your 8195.

Two things I could not test, so you will have to:

  • The kqueue path. I have no Mac, so EV_SET/EVFILT_PROC/NOTE_EXIT and poll reporting a kqueue as readable are unverified here. I took your prototype verbatim for that branch. The pidfd path is the one I exercised.
  • Your 10/10. On Linux the pre-fix code is not deterministic the way it is on your M4, it fails 22% of the time (66/300) rather than 10/10, because a 50 ms tick is short enough that the reap usually lands near the exit. Your gate is on Macs, so your 10/10 is the number that counts, but it does mean the Linux numbers below understate the fix.

On the test, I took your 1 MB. Measured sequentially, which is how gates/test.ts runs the binaries (only the builds use xargs -P 10):

max_output pre-fix with the descriptor
65536 (was) 66/300 25/300
1048576 (now) 5/300 7/300

So the 1 MB buys the ~10x, not the descriptor. At 1 MB the remaining failures are pre-exit volume rather than post-exit drain, which is the part neither of us can fix from the runtime. Worth knowing: 7/300 is still ~2%, and every one I caught is EFBIG at exactly 1048576 with "hi" absent, yes filling the megabyte before echo gets to write, so the marker never lands in the buffer. This is a shared VM, so that is a loaded box; on a quiet mini it should be well clear, and your prototype's 10/10 agrees. If you would rather not carry 2% at all, the same hazard with none of the scheduling is to give the grandchild a bounded budget instead of an unbounded yes, for example (head -c 200000 /dev/zero | tr '\0' x) & printf hi, which still fills a pipe but cannot approach max_output. I left it as you asked since it is your call.

One deviation from the diff you posted, and one guard:

  • poll can report the exit descriptor and a pipe ready in the same call. Your continue on the descriptor's revents covers that, but the read loop below it indexes pipes[i][0] for any role it has not skipped, and role 3 is the descriptor, so I added if (i == 3) continue;. It is unreachable behind your continue; I would rather not depend on the descriptor staying the last slot.
  • #elif defined(SYS_pidfd_open) rather than a bare SYS_pidfd_open, so an old kernel or a libc without the constant compiles and falls back to the tick instead of failing the build. There is no -Werror, so the unused child in that branch is quiet.

Also checked: no fd leak over 200 runs, and the two other loop changes are covered, the timeout path (Process.run("/bin/sleep", ["2"], "", 128, 30) still answers 110) and the both streams closed early case where the descriptor is the only thing left in the poll set.

Happy to put the bounded-grandchild test in instead of the 1 MB if you prefer the gate not to carry the flake.

…le the child lives, process_drain reads what FIONREAD counts, and the exit descriptor is the poll set's last slot

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@nicolas-abril nicolas-abril left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Verified on macOS (M4), where the kqueue path runs: the issue's call answers Done 0 with stdout "hi\n" 20/20 on C (Fail 27 on main), the same as JS; process_run and process_run_parallel pass on the check, interpreted, C and JS lanes, 100/100 sequential. I pushed one simplification on top (7db24b2): the loop waits only while the child lives, process_drain reads what FIONREAD counts, and the exit descriptor is the poll set's last slot. Thanks!

@nicolas-abril
nicolas-abril merged commit 11c65a2 into bendlang:main Sep 25, 2026
MattCozendey added a commit to MattCozendey/bend that referenced this pull request Sep 25, 2026
…g its pipes cannot extend it

As bendlang#1054 did on POSIX: once the child exits, the Windows loop reads only
the bytes already in the pipes (PeekNamedPipe) and stops. The descendant
case moves to process_run_posix, as Bun's spawnSync on Windows reads
until every writer closes the pipes, so the JS lane cannot stop at the
child's exit. process_run.c's cap takes bendlang#1054's growth.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Process.run: a grandchild that keeps writing makes C answer Fail where JS answers Done

3 participants