Skip to content

Deliver signals when process.stdin has a flowing 'data' listener on /dev/zero - #30192

Closed
robobun wants to merge 28 commits into
mainfrom
farm/949e0656/fix-signals-flowing-stdin-dev-zero
Closed

robobun wants to merge 28 commits into
mainfrom
farm/949e0656/fix-signals-flowing-stdin-dev-zero

Conversation

@robobun

@robobun robobun commented May 3, 2026

Copy link
Copy Markdown
Collaborator

Fixes #30189.

Repro

// multi-sig.js
process.on('SIGTERM', () => { console.error('SIGTERM'); process.exit(0); });
process.stdin.on('data', () => {});
console.error('READY pid=' + process.pid);
bun multi-sig.js < /dev/zero &
PID=$!
sleep 0.3
kill -TERM $PID    # process survives on bun < fix; SIGKILL required

Same failure for SIGINT / SIGUSR1 / SIGUSR2, and for `setInterval` — the event loop was wedged entirely.

Cause

`process.stdin` is wrapped in a native `ReadableStream` (`Bun.stdin.stream()`) whose `onPull` on non-pollable fds runs a synchronous blocking read loop. On pollable fds (pipes, sockets) that's fine because the `FilePoll` callback gives the event loop a natural yield; on non-pollable fds (regular files, `/dev/zero`, `/dev/urandom`, other character devices) there is no yield and the chain

await reader.read() -> resolve promise -> await continuation -> stream.push -> _read -> triggerRead -> internalRead -> await reader.read() -> ...

stays entirely inside microtasks. `EventLoop.tickConcurrentWithCount` never runs, so the ring buffer that `Bun__onPosixSignal` writes to never drains — the `PosixSignalTask`s that would invoke the JS handlers are never enqueued.

`setInterval` / `setTimeout` stall for the same reason: timers run in `autoTick()` after `tick()` returns, and `tick()` never returns while the task queue keeps refilling from the microtask chain.

Fix

`src/js/builtins/ProcessObjectInternals.ts`: when `process.stdin`'s fdType is `file` and not a TTY (i.e. non-pollable), route the next `internalRead()` through `setImmediate` instead of calling it inline from `_read`. `setImmediate` enqueues an `ImmediateObject` task which is drained in `autoTick()` (after timers and I/O), forcing `tick()` to return between reads. The immediate is `.unref()`d — the underlying native `source` already holds a process-alive ref while flowing; the immediate is purely a tick-yield mechanism.

Pipe and socket fdTypes are unchanged (they already yield through their poll).

Verification

New tests in `test/js/node/process/process-stdin.test.ts`:

  • `SIGTERM is delivered with flowing stdin on /dev/zero`
  • `SIGINT is delivered with flowing stdin on /dev/zero`
  • `setInterval fires with flowing stdin on /dev/zero`

All three fail on main (subprocess exits 143 = 128+SIGTERM default disposition, or test times out) and pass with the fix. Existing stdin tests (`process-stdin.test.ts`, `process-stdio.test.ts`, `stdin-pause-resume.test.ts`, `tty-reopen-after-stdin-eof.test.ts`, `process-stdin-stale-hup.test.ts`) still pass.

@robobun

robobun commented May 3, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:23 AM PT - May 4th, 2026

@robobun, your commit 874e869 is building: #50967

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

coderabbitai Bot commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Defers synchronous stdin reads for non‑TTY file fds by introducing needsEventLoopYield and scheduling internalRead via setImmediate().unref() with runtime guards. Adds POSIX-only (skipped) tests that exercise signal delivery and timer liveness when stdin flows from /dev/zero.

Changes

Signal delivery with flowing stdin

Layer / File(s) Summary
Rationale / Comment
src/js/builtins/ProcessObjectInternals.ts
Adds comment explaining why file-like, non‑TTY stdin should yield to the event loop before performing internal reads.
Data / Flag
src/js/builtins/ProcessObjectInternals.ts
Introduces needsEventLoopYield = fdType === BunProcessStdinFdType.file && !isTTY.
Core Behavior Change
src/js/builtins/ProcessObjectInternals.ts
triggerRead(_size) now: if reader && !shouldDisown and needsEventLoopYield is true, schedules internalRead(this) via setImmediate(...).unref() with guards (reader && !shouldDisown && !stream_destroyed) and sets needsInternalReadRefresh = true when guards fail; otherwise calls internalRead(this) synchronously as before.
Tests / Harness
test/js/node/process/process-stdin.test.ts
Adds isPosix import, waitForLine(proc, needle) helper, and a POSIX‑only (skipped) regression suite that parameterizes SIGTERM, SIGINT, SIGUSR1, SIGUSR2 and includes a setInterval tick test; each spawns a child with flowing /dev/zero stdin, waits for readiness, sends signals, and asserts stderr/stdout and exit codes.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main fix: delivering signals when process.stdin has a flowing data listener on /dev/zero, which directly matches the core change in ProcessObjectInternals.ts that defers internalRead via setImmediate for non-TTY file descriptors.
Description check ✅ Passed The description covers both template sections: 'What does this PR do?' (detailed explanation of the cause and fix) and 'How did you verify your code works?' (repro steps and new tests). It provides comprehensive context beyond the template requirements.
Linked Issues check ✅ Passed The PR fully addresses issue #30189 by fixing signal delivery when process.stdin has a flowing data listener on /dev/zero through setImmediate deferral for non-pollable fds. Issue #39 is listed but unrelated to this PR's objectives and changes.
Out of Scope Changes check ✅ Passed All changes are focused on fixing signal delivery with flowing stdin: ProcessObjectInternals.ts adds needsEventLoopYield logic for file fds, and process-stdin.test.ts adds regression tests. No unrelated modifications detected.

✏️ 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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/js/builtins/ProcessObjectInternals.ts`:
- Around line 268-279: The deferred call to internalRead can run after disown()
clears reader, causing an assertion failure; change the needsEventLoopYield path
to schedule a wrapper callback that re-checks the live reader/ownership before
invoking internalRead. Replace setImmediate(internalRead, this).unref() with a
lambda that does something like: setImmediate(() => { if (this.reader &&
!shouldDisown) internalRead(this); }).unref(); (also consider adding the same
guard in the immediate synchronous branch if relevant) so the deferred tick does
nothing when the reader was released by disown()/nextTick.

In `@test/js/node/process/process-stdin.test.ts`:
- Around line 165-243: The two nearly identical tests ("SIGTERM is delivered..."
and "SIGINT is delivered...") should be combined into a single parameterized
test using describe.each() or test.each() to cover SIGTERM, SIGINT, SIGUSR1, and
SIGUSR2; keep the Bun.spawn invocation (the cmd script, stdin:
Bun.file("/dev/zero"), stdout/stderr pipes, and bunEnv), the readiness reader
logic that waits for "READY" from proc.stdout, then call proc.kill(signal),
await proc.exited and assert the expected exit code and that proc.stderr.text()
contains the signal string; ensure the whole parameterized block is wrapped with
test.skipIf(!isPosix) as before and map each signal to the correct expected exit
code/string inside the table so the single block replaces the two existing tests
and adds SIGUSR1/SIGUSR2 coverage.
🪄 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: a0ada686-763f-4639-a144-592966cb6d30

📥 Commits

Reviewing files that changed from the base of the PR and between d484fd6 and b7a20e9.

📒 Files selected for processing (2)
  • src/js/builtins/ProcessObjectInternals.ts
  • test/js/node/process/process-stdin.test.ts

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

♻️ Duplicate comments (1)
test/js/node/process/process-stdin.test.ts (1)

182-220: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Use describe.each() for this table-driven signal suite.

This now covers the right four signals, but the parameterization is still on test.each() instead of the repo's required describe.each() shape for test/**/*.test.ts.

As per coding guidelines, "Use describe.each() for parameterized tests."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/js/node/process/process-stdin.test.ts` around lines 182 - 220, The test
is table-driven but uses test.each instead of the repo-required describe.each
shape; change the parameterization from test.each(cases) to describe.each(cases)
so the suite is parameterized at the describe level (i.e. replace
describe.skipIf(!isPosix)("signals with flowing stdin on /dev/zero", () => { ...
test.each(cases)("$signal handler fires", async ({ signal, exit }) => { ... })
}) with describe.skipIf(!isPosix)("signals with flowing stdin on /dev/zero", ()
=> { describe.each(cases)({ signal, exit }) => { test("$signal handler fires",
async () => { /* use signal and exit from the describe block */ }) } }) — keep
the same cases array, the existing process spawn code, waitForLine, proc.kill,
and assertions, but move the parameter destructuring out of test and into the
describe.each block so each case becomes its own nested describe and test
remains a regular test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@test/js/node/process/process-stdin.test.ts`:
- Around line 182-220: The test is table-driven but uses test.each instead of
the repo-required describe.each shape; change the parameterization from
test.each(cases) to describe.each(cases) so the suite is parameterized at the
describe level (i.e. replace describe.skipIf(!isPosix)("signals with flowing
stdin on /dev/zero", () => { ... test.each(cases)("$signal handler fires", async
({ signal, exit }) => { ... }) }) with describe.skipIf(!isPosix)("signals with
flowing stdin on /dev/zero", () => { describe.each(cases)({ signal, exit }) => {
test("$signal handler fires", async () => { /* use signal and exit from the
describe block */ }) } }) — keep the same cases array, the existing process
spawn code, waitForLine, proc.kill, and assertions, but move the parameter
destructuring out of test and into the describe.each block so each case becomes
its own nested describe and test remains a regular test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 30e60180-6194-4976-b6f6-19be57c52e68

📥 Commits

Reviewing files that changed from the base of the PR and between b7a20e9 and c229b93.

📒 Files selected for processing (2)
  • src/js/builtins/ProcessObjectInternals.ts
  • test/js/node/process/process-stdin.test.ts

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/js/node/process/process-stdin.test.ts`:
- Around line 288-300: waitForLine currently returns partial output when stdout
closes before the marker, causing callers to proceed incorrectly; modify
waitForLine so that inside the read loop when reader.read() yields done === true
and the accumulated seen does not include the needle, it throws an Error
(including the partial seen text and a short message like "stdout closed before
marker") instead of breaking and returning; keep the existing
reader.releaseLock() in the finally block and preserve the TextDecoder-based
accumulation and return behavior only when the needle was actually observed.
- Around line 254-269: The test uses a fixed 1s Bun.sleep after spawning a child
that runs setInterval and writes "READY", which makes the test flaky; instead
change the child snippet (the code that currently does setInterval(() => {
ticks++; }, 10); fs.writeSync(1, "READY\n"); process.stdin.on("data", () =>
{});) to emit a one-shot marker like fs.writeSync(1, "TICKED\n") on the first
interval tick (or immediately after incrementing ticks the first time), then
replace the await Bun.sleep(1000) in the test with await waitForLine(proc,
"TICKED") so the test waits for the actual condition rather than a wall-clock
delay.
🪄 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: dddcb3ec-883f-4505-8c36-cddde3547906

📥 Commits

Reviewing files that changed from the base of the PR and between 63b62d6 and d736595.

📒 Files selected for processing (1)
  • test/js/node/process/process-stdin.test.ts

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

This is a bad hack. We should instead fix the code path for reading from character-devices so it is threadpool'd.

@robobun

robobun commented May 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed the requested threadpool refactor in a6409aa.

PosixBufferedReader now carries a flags.threadpool bit that FileReader.onStart sets when the fd is blocking, non-regular, and not a TTY (matches character devices like /dev/zero). When the bit is set, each read() dispatches a heap-allocated ThreadPoolReadTask to jsc.WorkPool; the pool thread runs bun.sys.read, the completion hops back via enqueueTaskConcurrent, and tickConcurrentWithCount drains signals at the hop.

A per-task Async.KeepAlive holds the event loop open while the read is in flight (the inline path leans on the FilePoll for this, but non-pollable fds have no poll handle). close() and closeWithoutReporting() hand fd ownership to the task via detachAndClose so the pool thread can finish its syscall without touching a freed reader.

Dropped the setImmediate wrapper in ProcessObjectInternals.ts — not needed now that the yield happens in Zig.

Verified on release: without the fix, SIGTERM/INT/USR1/USR2 all hang the process on < /dev/zero; with the fix they handle at 0.3s.

Comment thread src/io/io.zig Resolved
Comment thread src/io/PipeReader.zig
Comment on lines +130 to +156
result: bun.sys.Maybe(usize) = .{ .result = 0 },
/// The owning reader. Cleared (under `lock`) by
/// `detachAndClose` when the reader tears down before this
/// task's completion runs on the JS thread. The pool thread
/// also reads this under `lock` so it can close the fd itself
/// if the reader has already been freed.
reader: ?*PosixBufferedReader,
/// The fd to read from, cached at schedule time so the pool
/// thread doesn't have to reach back through `reader`. Kept
/// valid by the detach handshake: the reader either holds the
/// fd open until completion, or takes ownership back and
/// closes it itself after `detachAndClose` returns.
fd: bun.FD,
/// The event loop to wake when the read completes. Cached
/// alongside `fd` so the pool thread never dereferences
/// `reader` to find it.
event_loop: jsc.EventLoopHandle,
/// Refs the event loop while a pool read is in flight so the
/// process doesn't exit before the completion task runs. The
/// inline path relies on the FilePoll's refcount for this, but
/// the threadpool path has no poll handle (fds used here are
/// non-pollable character devices), so we track it explicitly.
/// Ref'd in `schedule`, unref'd in `runFromJSThread` or
/// `detachAndClose` — i.e. exactly once per task lifetime.
keep_alive: Async.KeepAlive = .{},
lock: bun.Mutex = .{},

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.

🟡 nit: the reader doc comment says "The pool thread also reads this under lock so it can close the fd itself if the reader has already been freed", but runOnPoolThread (lines 202-208) never touches self.reader or self.lock — it only writes result and calls enqueueTaskConcurrent. The only two lock() callers (detachAndClose and runFromJSThread) both run on the JS thread and are already serialized, so the bun.Mutex field and its four lock/unlock calls are dead weight; the actual pool→JS happens-before is provided by enqueueTaskConcurrent. Consider dropping the mutex and rewording the comment (and the "so we can't race with detachAndClose" note in runFromJSThread).

Extended reasoning...

What

The doc comment on ThreadPoolReadTask.reader (PipeReader.zig:131-135) claims:

The pool thread also reads this under lock so it can close the fd itself if the reader has already been freed.

But runOnPoolThread — the only function that runs on the pool thread — is:

fn runOnPoolThread(task: *bun.ThreadPool.Task) void {
    const self: *ThreadPoolReadTask = @fieldParentPtr("task", task);
    self.result = bun.sys.read(self.fd, self.buf);
    self.event_loop.enqueueTaskConcurrent(...);
}

It reads self.fd and self.buf (both cached at schedule time precisely so the pool thread never dereferences reader), writes self.result, and enqueues the concurrent task. It never reads self.reader, never closes the fd, and never takes self.lock. The doc comment describes behavior that does not exist.

Who actually takes the lock

Grepping the struct, only two functions call self.lock.lock() / .unlock():

  1. detachAndClose (line 189) — doc'd as "Called on the JS thread when the reader is being torn down". Its only call sites are close() and closeWithoutReporting(), both reached via FileReader on the JS thread.
  2. runFromJSThread (line 210) — dispatched from tickQueueWithCount in Task.zig, which runs on the JS event loop.

Both execute on the same single JS thread. They cannot interleave. A mutex whose only takers are on one thread synchronizes nothing.

Step-by-step proof

Consider the lifecycle of one task:

  1. JS thread: schedule() allocates the task, sets reader.threadpool_task = self, and submits to WorkPool. No lock taken.
  2. Pool thread: runOnPoolThread runs bun.sys.read(self.fd, self.buf), writes self.result, calls enqueueTaskConcurrent. No lock taken, self.reader never read.
  3. JS thread: either (a) tickQueueWithCount dequeues the concurrent task → runFromJSThread takes the lock, reads self.reader, releases; or (b) the reader is closed first → detachAndClose takes the lock, nulls self.reader, releases.
  4. Whichever of (a)/(b) didn't run first runs second — but both are JS-thread functions, so step 3's lock release strictly happens-before step 4's lock acquire by single-threaded ordering alone, with or without the mutex.

The pool→JS happens-before that makes self.result visible to runFromJSThread is established by enqueueTaskConcurrent's atomic queue operations (the standard producer→consumer release/acquire), not by self.lock.

The second misleading comment

runFromJSThread (lines 220-222) says:

Acquire the detach lock and capture the reader pointer atomically with flags.threadpool_in_flight so we can't race with detachAndClose.

Same issue: detachAndClose runs on the JS thread, runFromJSThread runs on the JS thread. There is no race to prevent. (Also, flags.threadpool_in_flight is read after the lock is released, not under it, so the "atomically with" claim is doubly wrong.)

Impact

Zero runtime impact — an uncontended mutex is a couple of atomic ops. The code is correct as written. But this is newly-added concurrency code with detailed doc comments specifically intended to let a reader audit the threading model, and two of those comments describe a synchronization mechanism that doesn't exist while the actual mechanism (enqueueTaskConcurrent) goes unmentioned. Anyone trying to verify the detach handshake will be misled into looking for a pool-thread reader access that isn't there.

Fix

  • Drop the lock: bun.Mutex field and the four lock()/unlock() calls in detachAndClose and runFromJSThread.
  • Reword the reader doc comment to: "Cleared by detachAndClose (JS thread) when the reader tears down before the completion task runs; runFromJSThread (also JS thread) checks this and closes the inherited fd if null."
  • Drop or reword the "so we can't race with detachAndClose" comment in runFromJSThread — there is no cross-thread race; both run on the JS thread, ordered by the event loop.

Comment thread src/io/PipeReader.zig
Comment on lines +121 to +124
/// finish its syscall and schedule the completion task, and the
/// completion task sees `reader == null` (set by `detachAndClose`)
/// and destroys itself without touching the freed reader.
const ThreadPoolReadTask = struct {

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.

🟡 nit: the ## Fix section of the PR description still describes the removed setImmediate approach in src/js/builtins/ProcessObjectInternals.ts, but that file isn't in the diff anymore — the actual fix is now ThreadPoolReadTask in src/io/PipeReader.zig + the use_threadpool flag in src/bun.js/webcore/FileReader.zig (per a6409aa). Worth updating before merge so the squash-commit message / future git log archaeology points at the right layer.

Extended reasoning...

What

The PR description's ## Fix section reads:

src/js/builtins/ProcessObjectInternals.ts: when process.stdin's fdType is file and not a TTY (i.e. non-pollable), route the next internalRead() through setImmediate instead of calling it inline from _read. setImmediate enqueues an ImmediateObject task which is drained in autoTick() ...

That implementation no longer exists. Commit a6409aa ("Route character-device reads through jsc.WorkPool") replaced the JS-level setImmediate deferral with a Zig-level threadpool dispatch, and the author confirmed in a follow-up comment: "Obsolete — the entire setImmediate wrapper (and its rationale comment) is gone in a6409aa. Character-device reads go through jsc.WorkPool at the Zig layer now; no JS-level yield needed." The changed-files list is now Task.zig, FileReader.zig, PipeReader.zig, io.zig, and process-stdin.test.ts — ProcessObjectInternals.ts is not in the diff at all.

Step-by-step proof

  1. PR description's ## Fix section names exactly one source file: src/js/builtins/ProcessObjectInternals.ts.
  2. git diff main...HEAD --name-only for this PR returns: src/bun.js/event_loop/Task.zig, src/bun.js/webcore/FileReader.zig, src/io/PipeReader.zig, src/io/io.zig, test/js/node/process/process-stdin.test.ts. ProcessObjectInternals.ts does not appear.
  3. The mechanism described ("setImmediate enqueues an ImmediateObject task ... forcing tick() to return between reads") is not how the merged code works. The actual mechanism: FileReader.onStart sets reader.flags.threadpool = true for blocking non-regular non-TTY fds (FileReader.zig:154-166); PosixBufferedReader.read() then dispatches each read to jsc.WorkPool via ThreadPoolReadTask.schedule (PipeReader.zig:585-588), and the completion hops back through enqueueTaskConcurrent → tickQueueWithCount (Task.zig:265-268), which is the yield point that lets signals/timers drain.
  4. So both the file and the mechanism named in the description are wrong for the code that will actually merge.

Why this matters

oven-sh/bun squash-merges PRs, and the PR description becomes the commit body. A future reader running git log -- src/io/PipeReader.zig to understand why ThreadPoolReadTask exists will land on a commit message that says "the fix is in ProcessObjectInternals.ts via setImmediate" — pointing at a file the commit doesn't touch and a mechanism it doesn't use. The ## Cause and ## Verification sections are still accurate; only ## Fix needs updating.

On scope

One could argue PR-description text is GitHub metadata rather than merged code and therefore out of scope for code review. That's why this is filed as a nit, not a blocker — there is zero runtime impact. But the description does become the permanent squash-commit message, and the whole point of this PR's unusually detailed write-up (it cites tickConcurrentWithCount, Bun__onPosixSignal, autoTick() by name) is to make the fix auditable later. An accurate ## Cause followed by a ## Fix that names the wrong file and wrong mechanism actively undermines that.

Fix

Replace the ## Fix paragraph with something like:

src/bun.js/webcore/FileReader.zig: when the fd is a blocking, non-regular, non-TTY descriptor (character devices like /dev/zero, /dev/urandom), set reader.flags.threadpool = true. src/io/PipeReader.zig: when that flag is set, read() dispatches a heap-allocated ThreadPoolReadTask to jsc.WorkPool instead of calling read(2) inline; the pool thread runs the blocking syscall and the completion hops back via enqueueTaskConcurrent, which is drained by tickConcurrentWithCount — the same hop that drains the signal ring. A per-task Async.KeepAlive holds the loop open while a read is in flight (these fds have no poll handle). Pipe/socket fdTypes are unchanged; regular files keep the inline path since they hit EOF quickly.

Comment thread src/io/PipeReader.zig
Comment on lines +137 to +142
/// The fd to read from, cached at schedule time so the pool
/// thread doesn't have to reach back through `reader`. Kept
/// valid by the detach handshake: the reader either holds the
/// fd open until completion, or takes ownership back and
/// closes it itself after `detachAndClose` returns.
fd: bun.FD,

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.

🟡 nit: this doc comment says the reader "takes ownership back and closes it itself after detachAndClose returns", but the implementation does the opposite — detachAndClose's own comment (line 195-196) says "ownership has moved to the task, which will close it in runFromJSThread", close()/closeWithoutReporting() set this.handle = .{ .closed = {} } without closing, and runFromJSThread does self.fd.close() when reader == null. Same class of doc-vs-implementation drift as the open nit on the reader field / mutex; worth rewording to e.g. "…or hands ownership to the task via detachAndClose, which closes it in runFromJSThread".

Extended reasoning...

What

The doc comment on ThreadPoolReadTask.fd (PipeReader.zig:137-142) reads:

Kept valid by the detach handshake: the reader either holds the fd open until completion, or takes ownership back and closes it itself after detachAndClose returns.

The first clause is correct (normal path: the reader keeps handle = .{ .fd = ... } open until runFromJSThread runs with reader != null, and the task never closes self.fd in that branch). The second clause is backwards: in the detach path, fd ownership moves from the reader to the task, and the task closes it — the reader never "takes ownership back" and never closes the fd itself.

The actual detach flow

  • detachAndClose() (lines 184-200) is doc'd as "Hands ownership of the fd to the task so the pool thread can close it after its read completes", and its body says "The reader no longer owns the fd — ownership has moved to the task, which will close it in runFromJSThread".
  • close() (lines 364-374) and closeWithoutReporting() (lines 379-388): when flags.threadpool_in_flight is set, both call detachAndClose(this) and then this.handle = .{ .closed = {} } — they forget the fd without issuing a close syscall.
  • runFromJSThread() (lines 226-230): when reader == null (i.e. the reader detached), it does self.fd.close().

So two doc comments inside the same struct directly contradict each other on which side closes the fd in the detach path, and the fd field comment is the wrong one.

Step-by-step proof

Take a reader that is closed while a pool read is in flight:

  1. JS thread: schedule() caches fd = reader.getFd() into the task and submits to WorkPool. Reader's handle still holds the fd.
  2. Pool thread: runOnPoolThread calls bun.sys.read(self.fd, self.buf) (blocking).
  3. JS thread: user code closes the stream → PosixBufferedReader.close() sees flags.threadpool_in_flight → calls ThreadPoolReadTask.detachAndClose(this) → self.reader = null. Then this.handle = .{ .closed = {} }. No close syscall issued by the reader. The fd is still open; the task holds the only reference to it in self.fd.
  4. Pool thread: read returns → enqueueTaskConcurrent.
  5. JS thread: runFromJSThread runs, sees reader == null, executes self.fd.close(). Task closes the fd.

At no point does the reader "take ownership back" or close the fd itself after detachAndClose — exactly the opposite of what line 140-141 claims.

Why it matters

Zero runtime impact — the code is correct, only the comment is wrong. But this struct's doc comments are the de-facto spec for the detach handshake's threading/ownership model (there's no other documentation), and fd-close ownership is the kind of thing where getting it wrong is a use-after-close. Someone auditing the fd lifecycle from this comment would go looking for a reader-side close-after-detach that doesn't exist. This is the same class of doc-vs-implementation drift already flagged in the unresolved nit on the reader field / lock (#3179230991), just on a different field — worth fixing both together so the ownership comments in this struct are internally consistent.

Fix

Reword the second clause to match the implementation, e.g.:

Kept valid by the detach handshake: the reader either holds the fd open until the completion task runs, or hands ownership to the task via detachAndClose — in which case runFromJSThread closes it after the pool read returns.

Comment thread src/io/PipeReader.zig
Comment on lines +238 to +240
if (r.flags.is_done or r.flags.closed_without_reporting or r.flags.is_paused) {
return;
}

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 is_paused check here runs after the pool thread has already filled self.buf via bun.sys.read, so if process.stdin.pause() lands while a pool read is in flight, this early return drops up to 64 KB of already-read data (the defer frees self.buf without delivering it). The inline path checked is_paused before issuing the syscall; here it should only gate the next schedule() (which it already does at the three reschedule sites) — either remove is_paused from this guard and let onReadChunk deliver the chunk, or stash buf[0..bytes_read] into r._buffer before returning.

Extended reasoning...

What the bug is

ThreadPoolReadTask.runFromJSThread checks r.flags.is_paused and returns early after the pool thread has already executed bun.sys.read(self.fd, self.buf) and populated the buffer:

const r = reader.?;
r.threadpool_task = null;
r.flags.threadpool_in_flight = false;

if (r.flags.is_done or r.flags.closed_without_reporting or r.flags.is_paused) {
    return;   // ← self.buf already holds bytes_read bytes from the fd
}

The defer block at the top of the function then frees self.buf and destroys the task. Those bytes are never passed to onReadChunk and never appended to r._buffer, so they are silently discarded.

How is_paused becomes true mid-read

This PR's whole point is that the JS thread is free while the pool thread blocks in read(2), so user code (timers, signal handlers) can run concurrently with an in-flight pool read. process.stdin.pause() from such code reaches is_paused via:

  1. stream.pause() → emits 'pause' → handler at ProcessObjectInternals.ts:274-281 schedules process.nextTick(... disown()).
  2. disown() (line 145) calls source?.setFlowing?.(false) unconditionally, before attempting reader.releaseLock().
  3. FileReader.setFlowing(false) (FileReader.zig:672-673) → this.reader.pause().
  4. PosixBufferedReader.pause() sets flags.is_paused = true.

All of this runs on the JS thread. nextTicks drain before the concurrent-task queue, so by the time tickQueueWithCount dispatches runFromJSThread, is_paused is already set.

Why existing code doesn't prevent it

The pre-PR inline path checked is_paused at the top of read() ("Don't initiate new reads if paused") — i.e. before issuing the syscall — and the read+deliver was synchronous on a single thread, so pause() could never interleave between the syscall and delivery. The threadpool path moves the syscall to another thread but kept the same flag check, now positioned after the syscall has completed. The is_done/closed_without_reporting arms of this guard are correct (consumer is gone, dropping is intended); is_paused is not — the consumer is still attached and expects buffered delivery on resume().

Step-by-step proof

Take process.stdin redirected from a stateful character device (e.g. /dev/input/eventN, a serial port — S_ISCHR, not matched by bun.sys.isPollable's FIFO/SOCK check, not a TTY, so use_threadpool = true per FileReader.zig:160-166):

  1. .on('data', ...) → own() → first internalRead → reader.read() → onPull → PosixBufferedReader.read() → flags.threadpool ✓ → ThreadPoolReadTask.schedule(r). threadpool_in_flight = true; pool thread starts bun.sys.read(fd, buf).
  2. JS thread is free. A timer fires → user calls process.stdin.pause().
  3. 'pause' handler → nextTick → disown() → source.setFlowing(false) → reader.pause() → r.flags.is_paused = true. (The subsequent releaseLock() throws because a read request is pending; shouldDisown = true is set, but is_paused is already true regardless.)
  4. Pool thread's read(2) returns 64 KB of input events into self.buf; runOnPoolThread writes self.result = .{ .result = 65536 } and calls enqueueTaskConcurrent.
  5. tickQueueWithCount runs runFromJSThread: reader != null, clears threadpool_in_flight, hits r.flags.is_paused → returns. defer frees self.buf. The 64 KB of events are gone; the kernel's read position has advanced past them.
  6. Later, user calls resume() → own() → setFlowing(true) → unpause() + read() → schedule() issues a fresh pool read, which returns the next 64 KB. The dropped chunk is unrecoverable.

Impact

Silent data loss on pause() for any non-regular, non-pollable, non-TTY character device used as process.stdin. The PR's headline targets (/dev/zero, /dev/urandom) have fungible bytes so users won't notice, but the same gating condition matches devices where byte order/identity matters: /dev/input/event* (structured input_event records), serial ports (/dev/ttyS* when not opened as a controlling TTY), etc. Before this PR there was no window for this to happen; it's a new failure mode introduced by the threadpool refactor.

A secondary effect: the pending reader.read() promise that internalRead is awaiting is what onReadChunk would resolve. Skipping delivery leaves it pending until the next read after resume(), which is fine for liveness but means the chunk that does eventually resolve it is the wrong one.

Fix

Remove r.flags.is_paused from this early-return guard. The three reschedule sites below (after onReadChunk, after the non-streaming append, and in the EAGAIN branch) already check !r.flags.is_paused before calling schedule(r), so delivery proceeds and the next read is correctly suppressed:

if (r.flags.is_done or r.flags.closed_without_reporting) {
    return;
}

onReadChunk will resolve the pending reader.read() promise; internalRead then stream.push(value)s into the paused Readable's internal buffer, and if (shouldDisown) disown() finishes the pause cleanly. Alternatively, if you'd rather not call into JS while paused, stash the bytes before returning:

if (r.flags.is_paused) {
    if (self.result == .result and self.result.result > 0) {
        bun.handleOom(r._buffer.appendSlice(self.buf[0..self.result.result]));
    }
    return;
}

Comment thread src/io/PipeReader.zig
Comment on lines +189 to +200
fn detachAndClose(reader: *PosixBufferedReader) void {
const self = reader.threadpool_task orelse return;
reader.threadpool_task = null;
self.lock.lock();
defer self.lock.unlock();
self.reader = null;
// The reader no longer owns the fd — ownership has moved
// to the task, which will close it in `runFromJSThread`.
// Drop the keep-alive now that teardown has started so the
// completion task doesn't keep a closing process alive.
self.keep_alive.unref(self.event_loop);
}

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.

🟡 nit: detachAndClose() nulls reader.threadpool_task and self.reader but never clears reader.flags.threadpool_in_flight, and runFromJSThread only clears it in the reader != null branch — so after the detach path the reader sits with handle = .closed, threadpool_task = null, but threadpool_in_flight still true. No observable misbehavior today (every hasPendingRead() caller is gated by isDone(), and a second close() re-entering this branch is a no-op), but adding reader.flags.threadpool_in_flight = false; here keeps the state machine internally consistent.

Extended reasoning...

What

ThreadPoolReadTask.detachAndClose() (src/io/PipeReader.zig:189-200) does:

fn detachAndClose(reader: *PosixBufferedReader) void {
    const self = reader.threadpool_task orelse return;
    reader.threadpool_task = null;
    self.lock.lock();
    defer self.lock.unlock();
    self.reader = null;
    self.keep_alive.unref(self.event_loop);
}

It nulls the back-pointer on both sides and drops the keep-alive, but never touches reader.flags.threadpool_in_flight. The only place that clears that flag is runFromJSThread line ~236 (r.flags.threadpool_in_flight = false;), which is reached only when self.reader != null — i.e. not in the detached case. So after close() / closeWithoutReporting() take the detach branch, the reader is left with handle = .{ .closed = {} }, threadpool_task = null, but flags.threadpool_in_flight still true.

Step-by-step

  1. schedule() sets reader.flags.threadpool_in_flight = true and submits the task to the work pool.
  2. While the pool thread is in bun.sys.read, the JS thread closes the stream → PosixBufferedReader.close() sees flags.threadpool_in_flight → calls ThreadPoolReadTask.detachAndClose(this).
  3. detachAndClose nulls reader.threadpool_task and self.reader, unrefs the keep-alive. reader.flags.threadpool_in_flight is not touched.
  4. close() continues: this.handle = .{ .closed = {} }; if (!this.flags.is_done) this.done(); → is_done = true.
  5. Pool read returns → runOnPoolThread enqueues the concurrent task → runFromJSThread runs, sees reader == null, closes self.fd, and the defer block destroys the task. The r.flags.threadpool_in_flight = false line is in the reader != null branch, so it never runs.
  6. The PosixBufferedReader now has is_done = true, handle = .closed, threadpool_task = null, threadpool_in_flight = true.

Why it doesn't bite today

I traced every consumer of the stale flag:

  • hasPendingRead() (line 537 — if (this.flags.threadpool_in_flight) return true;): both substantive callers in FileReader.zig are guarded by isDone() first. onPull checks if (this.reader.isDone()) return .done before reaching hasPendingRead(); setFlowing checks !this.reader.isDone() and !hasPendingRead() so the short-circuit applies. After step 4, isDone() is true (is_done set via done()→finish() in the close() path; closed_without_reporting set in the closeWithoutReporting() path), so hasPendingRead() is unreachable. drain() calls it without an isDone() guard but only to choose between two ways of returning an empty buffer — functionally identical.
  • Second close() / deinit()→closeWithoutReporting(): re-enters the flags.threadpool_in_flight branch, but detachAndClose early-returns (reader.threadpool_task orelse return), handle is already .closed, and is_done / closed_without_reporting are already set → all no-ops. deinit()'s closeWithoutReporting() is additionally gated by getFd() != invalid_fd, which is false after handle = .closed.

So no observable misbehavior — this is stale state on a terminal object.

Addressing the refutation

One verifier argued this isn't actionable because (a) every reachable consumer is guarded, and (b) the flag value is arguably semantically correct — there really is still a read in flight on the pool thread when detachAndClose returns. Both points are fair, which is why this is a nit and not a bug. The counter-argument for fixing it anyway: this is brand-new concurrency code with a packed-struct flag word that from() copies verbatim, and the rest of the detach handshake is meticulous about leaving the reader in a self-consistent terminal state (threadpool_task = null, handle = .closed). Leaving one bit of that state inconsistent costs nothing today but is exactly the kind of thing that turns into a real bug the next time someone adds a hasPendingRead() call site without an isDone() guard. The one-line fix is free.

Fix

Add reader.flags.threadpool_in_flight = false; immediately after reader.threadpool_task = null; in detachAndClose() (or, equivalently, in the two callers right after invoking it).

@robobun

robobun commented May 4, 2026

Copy link
Copy Markdown
Collaborator Author

@Jarred-Sumner — this PR has been stuck in an infra-flake retry loop. Last 7 CI runs:

Build Failure
50780 fetch-http2-client AtomStringImpl ASAN flake + test-http-should-emit Win
50794 test-http-should-emit-close Windows x64-baseline
50818 test-http-should-emit-close Windows x64-baseline (2nd time)
50839 Zig ICE handleExternLibName on windows-x64-build-zig
50840 test-http-should-emit-close Windows x64 (3rd time)
50859 Zig ICE handleExternLibName (tripped at tty.zig)
50860 libjpeg-turbo GitHub fetch failed on linux-aarch64-musl-build-cpp
50864 test-http-should-emit-close Windows x64 (4th time)

All unrelated to the PR (stdin/signal code). The test-http-should-emit-close test has a pending root-cause fix — I sent #30217 with a test-level workaround which you closed in favor of a Zig UV_DISCONNECT fix; would you like me to (a) re-apply the #30217 workaround here to unblock, or (b) force-merge this once green builds are observable across the matrix?

@robobun

robobun commented May 4, 2026

Copy link
Copy Markdown
Collaborator Author

Stopping retriggers (7 same-flake failures on test-http-should-emit-close in a row). The PR's code is ready and the Linux/macOS/FreeBSD/Android test shards are all green. The failing shard is an unrelated pre-existing Windows fetch-abort flake that's blocking multiple PRs — needs either the Windows UV_DISCONNECT root-cause fix or a maintainer force-merge.

Happy to re-kick CI once infrastructure settles.

robobun and others added 9 commits May 4, 2026 10:23
…ble fd

When process.stdin had a flowing data listener on a non-pollable fd
(regular file, /dev/zero, /dev/urandom, character devices in general),
the native ReadableStream's onPull ran a synchronous blocking read and
the

  onPull -> resolve promise -> await -> push -> _read -> onPull

chain stayed entirely inside microtasks. tickConcurrentWithCount never
ran, so signals queued by Bun__onPosixSignal never drained and
setInterval/setTimeout callbacks never fired. SIGTERM/SIGINT/SIGUSR*
were effectively unreachable; the process could only be killed with
SIGKILL.

Fix: for `file` fdType stdin (non-TTY), schedule the next
internalRead() via setImmediate. That enqueues an ImmediateObject task
which is drained in autoTick() (after timers and I/O), forcing tick()
to return between reads. Pipe/socket fdTypes already yield naturally
through their FilePoll callback and use the direct path.

The immediate is .unref()d because the underlying source already holds
a ref while flowing; it's only a tick-yield mechanism and must not
keep the process alive on its own.

Fixes #30189
…rameterize signal tests

- Guard the setImmediate callback against disown()/destroy happening on
  the nextTick before the immediate fires. Without it, an internalRead()
  would hit `$assert(reader)` when the stream was paused or destroyed
  between triggerRead() and the deferred continuation.
- Fold the SIGTERM/SIGINT tests into a test.each() block that covers
  SIGTERM, SIGINT, SIGUSR1, SIGUSR2. A regression specific to one
  signal type (e.g. SIGUSR*) would now be caught.
…be.each; await using; stderr before exitCode

- If the setImmediate callback finds the reader disowned, set
  needsInternalReadRefresh = true so a later ref() restarts reading
  instead of silently no-oping.
- Use describe.each() (repo convention in test/CLAUDE.md) instead of
  test.each() for the signal matrix — one nested describe per signal.
- await using on the Bun.spawn subprocesses: the children spin on
  /dev/zero with no natural exit; if an early assertion throws the
  disposer still kills them instead of leaking a CPU-bound process
  into the rest of the suite.
- Assert stderr before exitCode: on regression the child is killed by
  the default signal disposition (exitCode=null, empty stderr);
  asserting stderr first surfaces the handler-never-fired root cause
  rather than a bare null/exit mismatch.
- Emit READY before attaching the data listener. Without the fix the
  synchronous read loop blocks any writes that come after
  process.stdin.on('data'); waiting on a post-listener READY deadlocks
  the whole suite output (the gate saw 2+ timeouts cascading into a
  test-file truncation).
- Bump the signal/timer test timeouts to 5s. Debug-build subprocess
  startup is ~1s on its own, READY takes another ~0.5s, and 1500ms
  was racy.
- Increase the setInterval settle window to 1s. On /dev/zero with the
  event-loop yield, the 10ms interval still needs room to tick more
  than once under debug build conditions.
The .unref() broke `bun script.js < file` with only a 'data' listener.
For non-pollable fds, `source.updateRef(true)` in own() is a no-op
(PosixBufferedReader.updateRef early-returns when there's no poll
handle), so the native source contributes zero to event-loop
liveness. Unref'd immediates are skipped when the loop is otherwise
idle (runImmediateTask checks isEventLoopAliveExcludingImmediates),
which caused test-stdin-from-file.js, child-process-stdio.test.js,
and spawn-stdin-readable-stream-integration.test.ts to fail in CI
Build #50636.

The immediate is one-shot per _read call and the chain stops
naturally at EOF (Readable won't call _read again after push(null)),
so keeping it ref'd does not leak the process beyond stdin close.

Test tweaks:
- setInterval test now synchronizes on a 'TICKED' marker emitted from
  the first interval tick instead of a 1s Bun.sleep, per the test
  guidelines against wall-clock delays.
- waitForLine() throws on EOF so a child that dies before emitting
  the marker fails with a diagnostic rather than letting callers
  proceed against a corpse.
autofix-ci Bot and others added 19 commits May 4, 2026 10:23
JSC claims SIGUSR2 for its internal signal machinery on Darwin (see
WTF/wtf/threads/Signals.cpp: Signal::Usr maps to SIGUSR2), and
delivering SIGUSR1 to a Bun process on macOS currently crashes the
runtime with 'Bus error at address 0x0'. This is a pre-existing Bun
issue unrelated to this PR's event-loop yield fix — reproduces on
main with or without this change.

Skip the user-signal cases on macOS and keep SIGTERM/SIGINT +
setInterval coverage everywhere. Linux still runs the full 4-signal
matrix.
claude[bot] caught that the 'on regression the child is killed by the
default disposition, exitCode is null, stderr is empty' comment was
inherited from an earlier test ordering. In the current shape, the JS
signal handler is installed BEFORE the wedging data listener, so
Bun's sigaction IS active when the parent sends the signal — the
signal just never makes it to JS because the ring never drains. The
child hangs indefinitely and proc.stderr.text() never resolves;
failure is surfaced as the 5s test timeout + await using disposal.

Also removed the now-contradictory 'timeout is deliberately tight'
comment (timeout was relaxed to 5s in d736595).
…t overrides)

Bun's default per-test timeout is already 5s. claude[bot] flagged the
third argument as a guideline violation; removed it in both the
signal-handler test and the setInterval test. All new tests still
comfortably finish in <2s each on debug builds.
Replaces the setImmediate JS hack in ProcessObjectInternals with a
native threadpool path in PipeReader: when FileReader opens a
non-pollable, non-regular, non-TTY fd (character devices like
/dev/zero, /dev/urandom), PosixBufferedReader.flags.threadpool is
set and each read() is dispatched to jsc.WorkPool via a
heap-allocated ThreadPoolReadTask.

The pool thread runs the blocking read(2) syscall and then calls
enqueueTaskConcurrent to schedule the completion task back on the
JS thread. This makes the read() boundary a natural event-loop
yield point where tickConcurrentWithCount drains posted signals
and timers, fixing #30189.

A per-task Async.KeepAlive refs the event loop while the read is
in flight — the inline path relies on a FilePoll refcount for
that, but non-pollable fds have no poll handle so we track it
explicitly.

The detach-and-close handshake keeps the reader and task
lifetimes independent: if close() lands while a read is on the
pool, ThreadPoolReadTask.detachAndClose clears the task's
back-pointer, hands fd ownership to the task, and returns. The
pool thread finishes its read; the completion task sees
reader == null, closes the fd, and destroys itself.

Reverts the JS-level setImmediate wrapper added in b7a20e9 —
no longer needed now that the yield happens at the C/Zig layer.
CI Windows build failed because:
1. `ReaderThreadPoolReadTask = void` made the TaggedPointerUnion choke.
   Replaced with a named `opaque {}` stub so `@typeName` gives a stable
   distinct identifier. The tag is never constructed on Windows.
2. `WindowsBufferedReader.Flags` has no `threadpool` field. Guarded
   `reader.flags.threadpool = opened.use_threadpool` in FileReader.onStart
   behind `comptime bun.Environment.isPosix`.
3. Added `bun.markPosixOnly()` to the switch-case body to make intent
   explicit (matches the surrounding `ProcessWaiterThreadTask` pattern).

Verified with `bun scripts/build.ts --profile=ci-zig-only --os=windows` for
x64, x64 baseline, and aarch64.
…ion-is-aborted Windows flake, unrelated to this PR [skip size check]
…dows flake (fix attempted in #30217, closed pending root-cause fix) [skip size check]
…d-cpp (GitHub dep fetch transient) [skip size check]
…ws, maintainer wants root-cause not workaround (rejected #30217) [skip size check]
@Jarred-Sumner
Jarred-Sumner force-pushed the farm/949e0656/fix-signals-flowing-stdin-dev-zero branch from e935035 to 874e869 Compare May 4, 2026 10:23
@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: this PR's implementation lives entirely in Zig source files that have since been removed from the tree as part of the Rust migration. The change can no longer merge cleanly and the files it edits no longer exist on main.

If the underlying issue is still present, it will need a fresh fix against the Rust implementation.

@robobun robobun closed this Jun 26, 2026
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.

SIGTERM/SIGINT not delivered when process.stdin has flowing data listener

2 participants