Skip to content

The JS event loop waits again when a signal interrupts select, as the C loop does - #1036

Merged
nicolas-abril merged 1 commit into
bendlang:mainfrom
aldeni:js-select-eintr
Sep 25, 2026
Merged

nicolas-abril merged 1 commit into
bendlang:mainfrom
aldeni:js-select-eintr

Conversation

@aldeni

@aldeni aldeni commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Bug

The JS lane's io_wait (bend2/comp.ts) ignores what select returns. If a signal arrives while the loop sleeps in select, select fails with EINTR, and Linux leaves the fd sets unchanged. The loop then treats every bit it set as ready and calls the more of every parked computation. Most effects just park again on EAGAIN. tcp_connect doesn't: on wake it reads SO_ERROR, which is 0 while the connect is still in progress, so it answers Done with a socket that never connected.

Repro on Linux: a user effect installs a no-op SIGINT handler, then the program connects to TEST-NET-1, which drops its packets.

# repro.bend
import Base

def Hush.arm() -> IO(Unit):
  import "./hush.c"
  import "./hush.js"

def got(r: Result<&1, &1, (U32 & String), Socket>) -> IO(Unit):
  match r:
    case Done{s}:
      do IO<Unit>:
        Unit <- IO.print("Done: connected")
        Socket.close(s)
    case Fail{e}:
      IO.print("Fail")

def main() -> IO(Unit):
  do IO<Unit>:
    Unit <- Hush.arm()
    r : Result<&1, &1, (U32 & String), Socket> <- TCP.connect("192.0.2.1", 80)
    got(r)
// hush.js
function hush_arm() {
  process.on("SIGINT", () => {});
  return { $: CID(Unit) };
}

io_eff(CID(Hush.arm), hush_arm);
// hush.c
static void hush(int sig) {
}

Term hush_arm_run(Env e, Term* f, IoWork* w) {
  struct sigaction sa = { .sa_handler = hush };
  sigaction(SIGINT, &sa, NULL);
  return term_pak(CID(Unit), 0);
}

static void __attribute__((constructor)) hush_arm_use(void) {
  io_eff(CID(Hush.arm), hush_arm_run, 0);
}
$ bend repro.bend & sleep 0.5; kill -INT $!
All terms check, but 2 defs rely on unsafe or foreign code:
- Hush.arm
- main
Done: connected

A build with bend repro.bend -o repro.js run as bun repro.js also prints Done: connected. The native build (-o repro) stays pending, which is correct. Its io_wait already does this:

while (select(...) < 0) {
  if (errno != EINTR) {
    err_fail("the poller failed");
  }
}

Fix

The JS io_wait now works the same way. On EINTR (4 on Linux and macOS) it calls select again with the same sets, and with the time that is left, recomputed from the deadline: macOS leaves the timeout as it was after EINTR (Linux counts it down), so a retry there waited the whole timeout again. The C loop now recomputes it the same way. On any other error it throws "bend: the poller failed", which the JS lanes print before exiting with status 1, as the native lane does. After the fix the repro stays pending on the interpreted and JS lanes too: the process is still running 3 s after the SIGINT.

The fix also changes what happens on errors other than EINTR. When a parked fd is closed under the loop, select fails with EBADF. Before, the JS lanes woke every parked computation. Now they print bend: the poller failed and exit 1, as the native binary already did. I checked this with a scratch effect that parks on a closed fd: before the fix the interpreted and JS lanes woke that computation; after it, all three lanes print the line and exit 1.

Test

tests/io/select_eintr.bend needs a signal to arrive while the loop waits in select. Base has no signal API, so the test brings its own effect files. It follows the layout of tests/io/fifo_eof: a .c and a .js next to the .bend, which the tests/<ns>/<name>.(c|js) line of gates/repo.ts allows, each registering the effect with io_eff(CID(Idle.park), ...).

Idle.park(5) installs a no-op handler and has the signal land 5 ms later, while the loop waits in select:

  • C: sigaction without SA_RESTART. A detached thread then calls pthread_kill on the loop's thread.
  • JS: process.on("SIGALRM", ...), which makes Bun install its handler, and setitimer(ITIMER_REAL) through bun:ffi, so the kernel sends the signal whatever the loop is doing then. A child process cannot promise that: a kill spawned from the test lands about 0.5 ms later on Linux, most often before the loop reaches select: on upstream it caught the bug in 2 of 40 interpreted runs and 3 of 40 JS runs, where the timer catches it in 40 of 40. A setTimeout would never run here either, because the loop blocks in a synchronous select.

After that, the computation parks on the read end of a pipe that nobody writes to, so any wake is spurious. main sleeps 30 ms, prints slept, and ends the process with IO.die(U32, 0, ""), because the park is still live at that point.

Two design choices:

  • SIGWINCH (C) and SIGALRM (JS) are ignored by default. If a lane failed to install the handler, the signal would not kill the run. That matters because the interpreted lane shares one process with the rest of its shard.
  • The test parks on a pipe rather than connecting to 192.0.2.1, so it needs no network. A network that intercepts port 80 would let the connect complete.

Twenty runs per lane on Linux:

upstream 95317d9 (spurious wake) this branch (only slept) this branch, median
interp 20 / 20 20 / 20 164 ms (with the check)
JS 20 / 20 20 / 20 47 ms
C 0 / 20 20 / 20 32 ms

An empty program takes 18 ms on JS and 1 ms on C here. On the native lane, a build with a print in its EINTR branch shows that the signal interrupts select there too, so the test exercises both loops.

Regression

On Linux with Bun 1.3.11, mirroring what gates/test.ts does:

  • The tests/io checkup (118 modules, checked and interpreted in one process) is identical on this branch and on upstream 95317d9 with the test added, but for the test's own the idle park woke line, gone on the branch.
  • The nine tests of tests/io that wait on a timer or a poll (fifo_eof, sleep_order, sleep_timer, spawn_outlives_main, spawn_sleep, tcp_poll, tcp_spawn, udp_poll, and this one) pass on the JS and C lanes.
  • gates/repo.ts: 46 / 46. comp.ts is 62810 ttok (cap 64000).

Not tested here

  • macOS. The itimerval goes through the same BigInt64Array shape io_wait already uses for tv, so it should hold there as that does, but this branch was not run on a Mac.

Related to #1034 (timeouts and cancellation) and to the review of #1011, where a wake that doesn't say why it happened came up. In this bug, the loop treated an interrupted wait as a ready fd.

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

Thank you, the fix is right, and it holds on macOS too. On an Apple M4 merged onto main (ac0ddb7b), select_eintr wakes the idle park on main in 10 of 10 runs on the interpreted and JS lanes (never on C), and prints only slept on all three lanes with this branch. A C probe answers both of your macOS questions: select fails with EINTR even under SA_RESTART, and it leaves the fd sets untouched, so the retry with the same sets is sound. The tests/io checkup is byte-identical to main (the new test runs 91st in the shared process, with 24 after it), the C and JS lanes of tests/io match main, and gates/repo.ts passes 46/46.

Two changes.

1. The test's cost. It takes about 1.2 s per lane here (signal at 200 ms, IO.sleep(1000), and macOS restarts the full timeout after the interrupt), which is a lot against the gate's 30 s cap across ~1000 tests. The constants can't simply shrink, because of how the JS side sends the signal:

  • sh -c 'sleep …; kill …' needs ~30 ms or more just to start here, so with small constants the signal often lands after the process exited;
  • the child inherits the test's stderr, so a late signal prints sh: line 0: kill: (…) - No such process into the output, and the gate fails the run. At 5/30 this happened in about a third of the runs.

Spawning kill directly, with its output discarded, removes both: its own startup is the delay, and nothing can reach the test's output.

  process.on("SIGWINCH", () => {});
  Bun.spawn(["kill", "-s", "WINCH", String(process.pid)],
    { stdout: "ignore", stderr: "ignore" });

With that, Idle.park(5) and IO.sleep(30), 20 runs per lane:

main (spurious wake) this branch (only slept) this branch, median
interp 20 / 20 20 / 20 108 ms
JS 20 / 20 20 / 20 59 ms
C 0 / 20 20 / 20 55 ms

For reference, an empty program takes about 40 ms on JS and 18 ms on C here, so the test costs a few tens of ms instead of ~1.2 s per lane. The ms argument then only serves the C thread.

2. Retry with the time that's left. macOS leaves the timeout unchanged after EINTR (Linux updates it to the time left), so each retry waits the full timeout again. The PR's own test shows it: with the signal at 200 ms, IO.sleep(1000) ends at ~1.22 s on both lanes. The C loop already did this, but the retry is the code this PR adds, so please recompute the timeout from the deadline before each retry, in both loops; the sets can be reused as they are:

    if (sys.errno() !== 4) {
      throw "bend: the poller failed";
    }
    if (ms >= 0) {
      const left = Math.max(0, Math.ceil(soon - performance.now()));
      tv[0] = BigInt(left / 1000 | 0);
      tv[1] = BigInt(left % 1000 * 1000);
    }
    if (errno != EINTR) {
      err_fail("the poller failed");
    }
    tick = io_tick();
    ms   = soon > tick ? (soon - tick) / 1000000 + 1 : 0;
    tv   = (struct timeval){ ms / 1000, ms % 1000 * 1000 };

On Linux this changes nothing. It needs no test of its own: the error it removes is only as large as the signal's delay, 5 ms with the constants above.

Note: this review was written by an AI after it tested the PR for me and I reviewed the findings. If anything here is wrong, reply and I will review it myself.

@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for testing it on the M4, and for the probe answers. Both changes are in, with one difference from the snippet, and the reason is measured.

1. The test's cost. Idle.park(5) and IO.sleep(30), as you proposed. But a kill spawned directly from the test does not do here what it does on your Mac: on Linux, Bun.spawn(["kill", ...]) delivers the signal about 0.5 ms after the spawn (0.4–1.0 ms over five spellings, five runs each; sh -c takes 1.5 ms), before the loop reaches select. Nothing is interrupted, so the test passes on upstream too: 0 of 20 spurious wakes on ac0ddb7, against 15 of 15 with the 200 ms shell. On the M4, where the spawn takes a few ms, it lands inside the wait, which is why it looked right there.

The JS twin now asks the kernel instead: setitimer(ITIMER_REAL) sends SIGALRM 5 ms later whatever the loop is doing, with no child and nothing that could print into the test's output (the C twin keeps its thread and pthread_kill; ms paces both). Twenty runs per lane, Linux:

upstream ac0ddb7 (spurious wake) this branch (only slept) this branch, median
interp 20 / 20 20 / 20 165 ms (with the check)
JS 20 / 20 20 / 20 48 ms
C 0 / 20 20 / 20 33 ms

An empty program takes 17 ms on JS and 2 ms on C here. The itimerval goes through the same BigInt64Array shape io_wait already uses for tv, so it should hold on macOS as that does, but I could not run it there: if you can spare one run of select_eintr on the M4, that would settle it.

2. Retry with the time that is left. Both loops recompute the timeout from the deadline before each retry, as in your snippets; the sets are reused. The tests/io checkup (116 modules, one process) is identical to upstream but for the test's own line, the nine tests of tests/io that wait on a timer or a poll pass on JS and C, gates/repo.ts is 46 / 46, and comp.ts is 62423 ttok.

The commit is amended and the description updated.

… C loop does

JS io_wait now does what the C one does: it selects again on EINTR, and
on any other error fails with "bend: the poller failed" (a parked fd
that is closed gives EBADF: the JS lanes used to wake every parked
computation, and now print that line and exit 1, as the native lane did
already). Both loops retry with the time that is left, recomputed from
the deadline: macOS leaves select's timeout as it was after EINTR (Linux
counts it down), so a retry there waited the whole timeout again.

tests/io/select_eintr: Base has no signal API, so the test ships its own
effect twins, each registered with io_eff(CID(Idle.park), ...).
Idle.park(5) installs a no-op handler and has the signal land 5 ms
later, while the loop waits in select (C: sigaction without SA_RESTART,
and a thread that pthread_kills the loop's thread; JS: a process.on
listener for SIGALRM, and setitimer, so the kernel sends it whatever the
loop is doing then -- a kill spawned from the test lands about 0.5 ms
later on Linux, most often before the loop reaches select: on upstream
it caught the bug in 2 of 40 interpreted runs and 3 of 40 JS runs, the
timer in 40 of 40), then parks on a pipe nobody writes; main sleeps
30 ms, prints "slept" and ends the process with IO.die. Twenty runs per
lane on Linux: on upstream (95317d9) the interpreted and JS lanes print
"the idle park woke" before "slept" 20 of 20 times; on this branch all
three lanes print only "slept" 20 of 20 times, in 47 ms (JS) and 32 ms
(C) a run, an empty program taking 18 ms and 1 ms.

The tests/io checkup (118 modules, one process, as gates/test.ts runs
it) is identical on this branch and on upstream with the test added but
for the test's own "the idle park woke" line, gone on the branch; the
nine tests of tests/io that wait on a timer or a poll pass on the JS and
C lanes; gates/repo.ts passes 46 / 46; comp.ts is 62810 ttok (cap
64000). macOS was not run here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (95317d9), since #1042 changed how an effect file names things: the test's twins now register with io_eff(CID(Idle.park), ...) and spell CID(Unit). Without that, the branch still merged cleanly, but the interpreted and JS lanes stopped at no effect registers Idle.park. The fix itself, in both io_wait loops, is unchanged.

Re-run on the new base, Linux:

  • select_eintr, 20 runs per lane: on main with the test added, the interpreted and JS lanes wake the idle park 20 of 20 times (C never); on this branch all three lanes print only slept 20 of 20 times.
  • The tests/io checkup (118 modules) matches main with the test added, but for that the idle park woke line. The nine tests that wait on a timer or a poll pass on the JS and C lanes, gates/repo.ts is 46 / 46, and comp.ts is 62810 ttok.
  • The repro in the description now uses the new names. It still shows the bug on main (Done: connected on the interpreted and JS lanes) and stays pending on this branch.

One correction to my last comment: re-measured on this base, a kill spawned from the test catches the bug in 2 of 40 interpreted runs and 3 of 40 JS runs, not 0 of 20. The kernel timer catches it in 40 of 40, so the choice stands; the test's comment and the description say so now.

macOS is still not run here, so the one M4 run of select_eintr I asked for would still settle it.

@nicolas-abril
nicolas-abril merged commit 1e70bed into bendlang:main Sep 25, 2026
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Thank you @aldeni! Thorough work, and switching to a kernel timer was the right call. Here is the macOS run you asked for, on an Apple M4 with this branch merged onto current main (20 runs per lane):

select_eintr main + the test only this PR
interpreter woke 20 / 20 only slept 20 / 20
JS woke 20 / 20 only slept 20 / 20
C only slept 20 / 20 only slept 20 / 20

The setitimer call works on macOS through bun:ffi, and the test takes about 50–100 ms per lane. Retrying with the time that is left matters on macOS: with a signal 150 ms into a 300 ms sleep, main's C lane took 473 ms (median) and this branch 318 ms. Under a signal every 50 µs, main's C lane never finished on macOS, since each retry restarted the full timeout. The local test gate passes except for the two gfx tests that need a machine without a display, which fail on main too. Merged.

Right after the merge we simplified the fix in 3276efacc17af57d2db37c2d0c2a13f6ce4a4b5a. Both event loops already call io_wait again when nothing is runnable, and that call rebuilds the sets and the remaining time. So on EINTR, io_wait now clears its sets (memset in C, set.fill(0) in JS) instead of retrying: no parked fd reads as ready, a timer that is due still fires, and the loop waits again. That removes the retry loop and its timeout arithmetic from both loops, and the comment with them. comp.ts grows 54 ttok over main instead of 208.

We measured it with a small program that does nothing but go through io_wait, for main, your branch and the simplified version. Over 200k IO.sleep(0), with or without 100 parked fds, all three take the same time. Under a signal every 50 µs, the wall time is the same as your retry, and each interrupt costs a few µs more CPU on JS (about 0.1 µs on C) because the sets are rebuilt. select_eintr and the timer, poll and channel tests pass on every lane with the simplification.

Thanks again 🙏

Note: this comment was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

@Lorenzobattistela Lorenzobattistela mentioned this pull request Sep 25, 2026
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.

2 participants