Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughDefers synchronous stdin reads for non‑TTY file fds by introducing ChangesSignal delivery with flowing stdin
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/js/builtins/ProcessObjectInternals.tstest/js/node/process/process-stdin.test.ts
There was a problem hiding this comment.
♻️ Duplicate comments (1)
test/js/node/process/process-stdin.test.ts (1)
182-220: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winUse
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 requireddescribe.each()shape fortest/**/*.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
📒 Files selected for processing (2)
src/js/builtins/ProcessObjectInternals.tstest/js/node/process/process-stdin.test.ts
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
test/js/node/process/process-stdin.test.ts
Jarred-Sumner
left a comment
There was a problem hiding this comment.
This is a bad hack. We should instead fix the code path for reading from character-devices so it is threadpool'd.
|
Pushed the requested threadpool refactor in a6409aa.
A per-task Dropped the Verified on release: without the fix, SIGTERM/INT/USR1/USR2 all hang the process on |
| 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 = .{}, | ||
|
|
There was a problem hiding this comment.
🟡 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
lockso 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():
detachAndClose(line 189) — doc'd as "Called on the JS thread when the reader is being torn down". Its only call sites areclose()andcloseWithoutReporting(), both reached viaFileReaderon the JS thread.runFromJSThread(line 210) — dispatched fromtickQueueWithCountinTask.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:
- JS thread:
schedule()allocates the task, setsreader.threadpool_task = self, and submits toWorkPool. No lock taken. - Pool thread:
runOnPoolThreadrunsbun.sys.read(self.fd, self.buf), writesself.result, callsenqueueTaskConcurrent. No lock taken,self.readernever read. - JS thread: either (a)
tickQueueWithCountdequeues the concurrent task →runFromJSThreadtakes the lock, readsself.reader, releases; or (b) the reader is closed first →detachAndClosetakes the lock, nullsself.reader, releases. - 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_flightso we can't race withdetachAndClose.
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.Mutexfield and the fourlock()/unlock()calls indetachAndCloseandrunFromJSThread. - Reword the
readerdoc comment to: "Cleared bydetachAndClose(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 inrunFromJSThread— there is no cross-thread race; both run on the JS thread, ordered by the event loop.
| /// 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 { |
There was a problem hiding this comment.
🟡 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: whenprocess.stdin's fdType isfileand not a TTY (i.e. non-pollable), route the nextinternalRead()throughsetImmediateinstead of calling it inline from_read.setImmediateenqueues anImmediateObjecttask which is drained inautoTick()...
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
- PR description's ## Fix section names exactly one source file:
src/js/builtins/ProcessObjectInternals.ts. git diff main...HEAD --name-onlyfor 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.tsdoes not appear.- The mechanism described ("
setImmediateenqueues anImmediateObjecttask ... forcingtick()to return between reads") is not how the merged code works. The actual mechanism:FileReader.onStartsetsreader.flags.threadpool = truefor blocking non-regular non-TTY fds (FileReader.zig:154-166);PosixBufferedReader.read()then dispatches each read tojsc.WorkPoolviaThreadPoolReadTask.schedule(PipeReader.zig:585-588), and the completion hops back throughenqueueTaskConcurrent→tickQueueWithCount(Task.zig:265-268), which is the yield point that lets signals/timers drain. - 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), setreader.flags.threadpool = true.src/io/PipeReader.zig: when that flag is set,read()dispatches a heap-allocatedThreadPoolReadTasktojsc.WorkPoolinstead of callingread(2)inline; the pool thread runs the blocking syscall and the completion hops back viaenqueueTaskConcurrent, which is drained bytickConcurrentWithCount— the same hop that drains the signal ring. A per-taskAsync.KeepAliveholds 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.
| /// 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, |
There was a problem hiding this comment.
🟡 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
detachAndClosereturns.
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 inrunFromJSThread".close()(lines 364-374) andcloseWithoutReporting()(lines 379-388): whenflags.threadpool_in_flightis set, both calldetachAndClose(this)and thenthis.handle = .{ .closed = {} }— they forget the fd without issuing a close syscall.runFromJSThread()(lines 226-230): whenreader == null(i.e. the reader detached), it doesself.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:
- JS thread:
schedule()cachesfd = reader.getFd()into the task and submits toWorkPool. Reader'shandlestill holds the fd. - Pool thread:
runOnPoolThreadcallsbun.sys.read(self.fd, self.buf)(blocking). - JS thread: user code closes the stream →
PosixBufferedReader.close()seesflags.threadpool_in_flight→ callsThreadPoolReadTask.detachAndClose(this)→self.reader = null. Thenthis.handle = .{ .closed = {} }. No close syscall issued by the reader. The fd is still open; the task holds the only reference to it inself.fd. - Pool thread: read returns →
enqueueTaskConcurrent. - JS thread:
runFromJSThreadruns, seesreader == null, executesself.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 caserunFromJSThreadcloses it after the pool read returns.
| if (r.flags.is_done or r.flags.closed_without_reporting or r.flags.is_paused) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
🔴 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:
stream.pause()→ emits'pause'→ handler atProcessObjectInternals.ts:274-281schedulesprocess.nextTick(... disown()).disown()(line 145) callssource?.setFlowing?.(false)unconditionally, before attemptingreader.releaseLock().FileReader.setFlowing(false)(FileReader.zig:672-673) →this.reader.pause().PosixBufferedReader.pause()setsflags.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):
.on('data', ...)→own()→ firstinternalRead→reader.read()→onPull→PosixBufferedReader.read()→flags.threadpool✓ →ThreadPoolReadTask.schedule(r).threadpool_in_flight = true; pool thread startsbun.sys.read(fd, buf).- JS thread is free. A timer fires → user calls
process.stdin.pause(). 'pause'handler →nextTick→disown()→source.setFlowing(false)→reader.pause()→r.flags.is_paused = true. (The subsequentreleaseLock()throws because a read request is pending;shouldDisown = trueis set, butis_pausedis already true regardless.)- Pool thread's
read(2)returns 64 KB of input events intoself.buf;runOnPoolThreadwritesself.result = .{ .result = 65536 }and callsenqueueTaskConcurrent. tickQueueWithCountrunsrunFromJSThread:reader != null, clearsthreadpool_in_flight, hitsr.flags.is_paused→ returns.deferfreesself.buf. The 64 KB of events are gone; the kernel's read position has advanced past them.- 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;
}| 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); | ||
| } |
There was a problem hiding this comment.
🟡 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
schedule()setsreader.flags.threadpool_in_flight = trueand submits the task to the work pool.- While the pool thread is in
bun.sys.read, the JS thread closes the stream →PosixBufferedReader.close()seesflags.threadpool_in_flight→ callsThreadPoolReadTask.detachAndClose(this). detachAndClosenullsreader.threadpool_taskandself.reader, unrefs the keep-alive.reader.flags.threadpool_in_flightis not touched.close()continues:this.handle = .{ .closed = {} }; if (!this.flags.is_done) this.done();→is_done = true.- Pool read returns →
runOnPoolThreadenqueues the concurrent task →runFromJSThreadruns, seesreader == null, closesself.fd, and thedeferblock destroys the task. Ther.flags.threadpool_in_flight = falseline is in thereader != nullbranch, so it never runs. - The
PosixBufferedReadernow hasis_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 inFileReader.zigare guarded byisDone()first.onPullchecksif (this.reader.isDone()) return .donebefore reachinghasPendingRead();setFlowingchecks!this.reader.isDone() and !hasPendingRead()so the short-circuit applies. After step 4,isDone()is true (is_doneset viadone()→finish()in theclose()path;closed_without_reportingset in thecloseWithoutReporting()path), sohasPendingRead()is unreachable.drain()calls it without anisDone()guard but only to choose between two ways of returning an empty buffer — functionally identical.- Second
close()/deinit()→closeWithoutReporting(): re-enters theflags.threadpool_in_flightbranch, butdetachAndCloseearly-returns (reader.threadpool_task orelse return),handleis already.closed, andis_done/closed_without_reportingare already set → all no-ops.deinit()'scloseWithoutReporting()is additionally gated bygetFd() != invalid_fd, which is false afterhandle = .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).
|
@Jarred-Sumner — this PR has been stuck in an infra-flake retry loop. Last 7 CI runs:
All unrelated to the PR (stdin/signal code). The |
|
Stopping retriggers (7 same-flake failures on Happy to re-kick CI once infrastructure settles. |
…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.
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.
…e, unrelated to this PR [skip size check]
…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]
…dows flake, hitting every PR [skip size check]
…t tty.zig this time) [skip size check]
…d-cpp (GitHub dep fetch transient) [skip size check]
…(reopened #30217 for the workaround) [skip size check]
…ws, maintainer wants root-cause not workaround (rejected #30217) [skip size check]
… available [skip size check]
e935035 to
874e869
Compare
|
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 If the underlying issue is still present, it will need a fresh fix against the Rust implementation. |
Fixes #30189.
Repro
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
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`:
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.