Skip to content

FileReader: leave every read for a Node stream to the poll callback - #48918

Closed
robobun wants to merge 4 commits into
robobun/eba3bc94/pull-waits-after-short-readfrom
robobun/e18f67cd/node-stream-poll-only
Closed

robobun wants to merge 4 commits into
robobun/eba3bc94/pull-waits-after-short-readfrom
robobun/e18f67cd/node-stream-poll-only

Conversation

@robobun

@robobun robobun commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

This PR moves into #48782 (merge it into that branch). Related to #48514.

Problem

Fix

  • constructNativeReadable sets POLL_ONLY: request_read leaves every read to the poll callback, as Node's _read() does. One wakeup delivers at most 2 MiB, as in libuv.
  • The read loop stops for a reader that such a stream paused. Subprocess::on_process_exit reads the pipe of a waiting pull before it reports the exit. A throwing 'data' listener of child stdio is an uncaughtException.
  • Verified: child-process-stdio.test.js (16 new, 9 fail on FileReader: a Node stream takes each chunk from the poll callback #48782), 162 of 163 scripted checks. Self-reviewed: 22 concerns raised, 13 addressed (rest: Notes).

Background

Downsides

Notes

Where this comes from. An automated report, not a GitHub issue: a loop of await once(child.stdout, "data") over 2,000,000 bytes from /bin/cat ends short with exit code 0 on Bun 1.4.0 to main. #48514 is the same mechanism seen through 'readable', and #48782 handles that form. #48782's status comment names this loop as its open case. All numbers are from Linux x64. The release builds are f336318 ("main"), that commit with #48782's PipeReader.rs and FileReader.rs ("#48782"), and that commit with #48782's source and this PR ("this PR"). The #48782 build also has the bool return of Bun__reportUnhandledError, which nothing reads there.

Why one PR with #48782. #48782 alone is worse than main in these cases, and this diff repairs each of them:

  • A stream that stopped at a full buffer has 65,540 of 98,308 bytes at 'exit' (stdout:late, web:late). main: all.
  • A reader of the web stream of Bun.spawn() that stopped sees exited settle with 131,076 of 163,844 bytes (reader:late). main: all.
  • A 'data' listener that throws at the second chunk ends the process with status 1 although an 'uncaughtException' listener is installed (stdout:throw:second). main: status 0, all bytes.
  • 5 of the 163 scripted checks pass on main and fail on FileReader: a Node stream takes each chunk from the poll callback #48782.

The mechanism. A chunk that the native pull returns inside _read() is pushed inside _read(). Readable holds such a chunk, and flow() emits it in the same tick as the chunk before. The nextTicks and promise jobs of the listeners of the chunk before have not run then, so a listener that they attach misses the chunk. #48782 lets the pull wait after a read that came up short. After a read that did not find the pipe empty (128 KiB or more in one go, or 64 KiB of a blocking pipe), its pull still reads. #38886 added that read (read_into), and this PR turns it off for Node streams on the sources that #48782 calls poll-driven. Bun 1.3.13, Node, and Bun on Windows deliver every chunk from the loop callback.

The reported loop (complete runs):

Node 26.3 Bun 1.3.13 main #48782 this PR
await once(child.stdout, "data"), 2,000,000 bytes from cat, 10 runs 10 10 0 5 10
the same through Readable.fromWeb(Bun.spawn().stdout) 10 0 6 10
with a process.nextTick between the once() calls, 16 MiB (bench/child_process/stdio.mjs once), 5 runs 5 5 0 0 5

What changed, site by site.

  • PosixBufferedReader::request_read: one more flag in the test that makes a request wait (SHORT_READ | POLL_ONLY).
  • read_loop, for a POLL_ONLY consumer only:
    • It stops when the consumer paused the reader inside the delivery, also at a hang-up. Before, it read on, and the next _read() got those bytes at once.
    • It returns after 2 MiB (MAX_BYTES_PER_WAKEUP) when the consumer's request inside a delivery armed the poll. libuv stops after 32 reads of 64 KiB (stream.c).
    • For a blocking pipe it does not arm the poll a second time after such a request.
  • constructNativeReadable calls setPollOnly() on every source. Only the file source has it, and it has an effect only where FileReader: a Node stream takes each chunk from the poll callback #48782's is_poll_driven() holds. Its third parameter is spelled as in child_process: keep 'close' of stdout and stderr when their 'error' emit throws #44849 ("libuv-handle" | "webstream"), and the hunks of the two callers are the same as there.
  • Subprocess::on_process_exit calls FileReader::read_before_exit for the stdout and stderr stream that JS took. It reads when a pull waits on a poll-driven source. That covers a web reader too.
  • pushAndCheck catches what a 'data' listener of child stdio throws and reports it with reportUncaughtException, which now returns whether a handler took it. The stream reads on only then. The five hunks of that return value are byte for byte those of child_process: keep 'close' of stdout and stderr when their 'error' emit throws #44849.

Why the exit needs a read. A stream that stopped its reader arms its poll again at the next _read(). When the child has exited by then, its pidfd is ahead of the pipe in epoll's list, and the exit came before the last bytes. libuv reports a child's exit after the I/O of the same poll (linux.c). An earlier build of this work held child exits back in the poll dispatch. A self-review found a use-after-free in it (a nested loop tick reports the same level-triggered pidfd twice). It is not in this PR.

The bound. With every read of a Node stream in the poll callback, a child that stays ahead of a slow listener kept the loop in one wakeup. Probe: yes as the child, a 'data' listener that is busy 6 ms for each chunk, a 10 ms interval, 3 s, 6 runs each.

Node 26.3 main #48782 this PR
interval fires, of 300 239 to 244 0 23 to 161 43 to 44
longest gap between two fires, ms 14 to 31 3,001 and more 29 to 2,559 78 to 89
largest number of 'data' events in one loop turn 2 to 5 480 and more 3 to 415 11

The read before the exit has the same bound. Without it the exit of sh -c 'yes & exit 0' was not reported while yes stayed ahead.

Tests. All in test/js/node/child_process/child-process-stdio.test.js, beside #48782's, in the block "a stdio stream read one event at a time" (16 tests).

  • Release builds: this PR 36 pass of 36 in 6 runs. FileReader: a Node stream takes each chunk from the poll callback #48782 fails 9 of the 16: the loops after a full read, the loops over a shell pipe, the later forms (a 5 s stall), three counts of pushes inside _read(), the bound per turn, the exit forms, and the listener throw. main fails 17 of the 36 in the file.
  • Debug build with ASAN of this branch: 36 pass. Also process-stdin.test.ts 24, node-stream.test.js 123, spawn-pipe-start-error.test.ts 24, shell-pipe-read-fault.test.ts 11, spawn-stdio-syscall-error.test.ts 17, child_process-node.test.js 30, the AOT rows test 114 (one new case holds the bool of reportUncaughtException). child_process.test.ts: 83 pass and 3 fail, and the same 3 fail on main here (10,240 open fds against the debug build's JS files, a 5 s GC wait, and a uid test that depends on PATH).
  • The fixture child-process-stdio-once-data-fixture.js has five kinds of stream: stdout and stderr of a child, web (Readable.fromWeb(Bun.spawn().stdout)), stdin (Readable.fromWeb(Bun.stdin.stream()) behind a shell pipe, the one blocking pipe in the mode) and reader (a reader of the web stream). Under Node it prints the same object for stdout and stderr, but for the length of the first chunk.
  • "child.stdout pull nested in a 'data' event" in child_process.test.ts no longer reaches the read nested in the read loop on Linux with pidfd and on macOS: that pull waits now. The waiter-thread test here reaches it (stdout:exit:full) and asserts the chunk lengths 65,536 and 32,768 that only a nested read gives. child_process.test.ts is not touched.
  • A debug build of this base does not compile BunPlugin.cpp (Include wtf/Scope.h in BunPlugin.cpp #48812, open). My local debug builds carry that one include. This PR does not.
  • cargo check for x86_64-pc-windows-msvc and aarch64-apple-darwin. No test ran on macOS or Windows before CI. The exit forms and the bound tests need /proc and run on Linux only. The state "more than 256 KiB queued at a hang-up for a stopped stream" needs macOS's 512 KiB sockets and has no test.

The 163 scripted checks. They are scripts from the findings of the reviews of this work, each judged against Node, main or Bun 1.3.13. They are not in the tree. main 150 pass. #48782 149: it fails 5 that main passes and leaves 7 loop checks failing. This PR 162 in one full run of the final build. The one failure is a Duplex.from over a Blob, which fails on every Bun build.

Costs (this PR against #48782, same commit and toolchain, main in brackets).

  • Release binary: text +5,725 bytes, file +8,192 bytes. One host function (setPollOnly).
  • A pull on a source that is not a file source: 390.4 instructions (390.0) [390.1].
  • Promises per chunk of child.stdout, 64 MiB, 'data' listener: 2.00 (1.63 to 1.77) [0.49 to 1.28].
  • System calls of the main thread for 64 MiB of child.stdout (recvfrom + epoll_ctl + epoll_pwait2), 3 runs: 550 to 778 (506 to 678) [748 to 1,403]. A child that answers 16 bytes per round: 2.00 recvfrom and 2.00 epoll_ctl per round (the same) [3.00 and 3.00].
  • User instructions for 64 MiB with the consumer busy 200 µs per chunk, in units of 100,000, 3 runs: 'data' 1,213 to 1,214 (1,255 to 1,266), 'readable' 1,236 to 1,238 (1,242 to 1,245), for await 1,311 to 1,331 (1,315 to 1,331), pipe() 1,287 to 1,290 (1,329 to 1,333). process.stdin on a shell pipe, which this PR does not touch, as the control: 1,350 to 1,360 (1,345 to 1,376).
  • One child that exits (/bin/true, stdout piped): 560,277 instructions (557,883) [558,696]. The three are inside the noise of this measurement.
  • Readable.fromWeb(Bun.stdin.stream()) on a shell pipe, 64 MiB in 1,024 chunks: read 1,060, epoll_ctl 1,028, epoll_pwait2 1,024, poll 1,026, together 4,138 (4,284 to 4,326) [5,970 to 5,995]. One chunk for each loop turn.
  • 1 GiB through child.stdout with a 'data' listener, 7 interleaved runs, median ms (range): 670 (494 to 1,037), FileReader: a Node stream takes each chunk from the poll callback #48782 982 (812 to 1,439), main 1,041 (701 to 1,653), Bun 1.3.13 711 (511 to 1,036), Node 490 (334 to 564). The ranges overlap. 'readable', for await, pipe() and the web stream at 1 GiB: no median is outside the range of main.

Downsides, with the numbers.

Not changed.

Self-review. 22 concerns, 13 addressed: the bound, the stop for a paused reader (gated to the flag, and at a hang-up), the exit read for web readers, the helper that skipped the second arm (removed, one skip stays for a blocking pipe and is measured above), the guard in readAfterListenerThrow (removed: four probe forms give the same events without it), the stdin kind, the web exit forms, the rethrow for Readable.fromWeb(), the nested read under the waiter thread, the parameter spelling of #44849, and the texts.
Not done:

Questions for a maintainer.

Related open PRs. #48782 (the base of this branch). #44849 (the same bool return and the same parameter, identical hunks). #37171 (the listener throw for child stdio, which reads on also with no handler, and so turns exit status 1 into 0). #43790 (orders the events of child stdio in native-readable.ts). #48553 (the order of the pull buffer, not needed here). #48551 and #48652 (native-readable.ts for sources that answer at once). #48879 (pipe fds in net, the route of #36316). #48812 (the include that the debug build needs).


no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/child_process/child-process-stdio.test.js, test/aot/builtins/rows-of-the-host-are-held-by-calls-written-by-hand.test.ts

A pull on a polled fd read the fd again inside the delivery of the chunk
before it, also right after a read that had found the fd empty. Bytes
that a child wrote while a 'data' listener ran arrived in the same turn
of the event loop. A listener detached until the next setImmediate
missed them, execFile() lost its callback when the decoder held such a
chunk back, and 'readable' stalled.

request_read() replaces read_into(). After a short read it arms the poll
and the poll callback delivers the next bytes in a later turn, as libuv
does. After a read that filled its buffer the pull still reads straight
into the pull buffer. resume_reading() does the same for a resumed
stream.

The read loop arms the poll before it delivers a short read to a
consumer that waits for it, so a child's 'exit' stays behind the bytes
the child wrote first.
Without a pidfd a thread waits for child processes and reports an exit
as a task. Tasks run before the poll, so the bytes that a child wrote
before it exited would arrive after its exit. A pull keeps its read in
that mode.

A read of a blocking pipe that fills its buffer is not a short read,
whatever the size of that buffer. A nested read loop reads into a
smaller buffer than the scratch.

The exit order fixture treats a child that a thread already reaped as
exited. The tests of this behaviour are skipped when Bun has no pidfd.
A Node stream over a native source (child.stdout, Readable.fromWeb(proc.stdout)) sets PosixFlags::POLL_ONLY on its reader. request_read then waits for the poll callback after every read, not only after a short one, so the stream pushes no chunk inside _read() after its first read. Readable emits a chunk pushed inside _read() before the nextTicks and promise jobs of the chunk before, and a loop of `await once(stream, "data")` lost it.

The read loop stops for such a consumer when it paused the reader inside a delivery, and after 2 MiB in one wakeup. Subprocess::on_process_exit reads the pipe of a stream whose pull waits before it reports the exit. What a 'data' listener of child stdio throws is an uncaughtException, and the stream reads on when a handler took it: reportUncaughtException returns whether one did.
@robobun

robobun commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:30 AM PT - Nov 14th, 2026

❌ @robobun, your commit d3f542e has 1 failures in Build #141448 (All Failures):

  • step failed outside runner - exit 1 on ⚙️

🧪   To try this PR locally:

bunx bun-pr 48918

That installs a local version of the PR into your bun-48918 executable, so you can run:

bun-48918 --bun

@robobun

robobun commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

Status

How I reproduced it (Linux x64, release builds of f336318):

This PR targets the branch of #48782 and moves into it. It is a draft until the macOS lanes have run.

@robobun

robobun commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

#48955 targets this branch. It makes process.stdin a POLL_ONLY consumer while it holds the reader, which is the case that the body here lists as still lossy. I think this branch and #48782 should not merge without it.

Measured on Linux x64, release builds. A loop of await once(process.stdin, "data") over 2 MB, runs that lost bytes:

process.stdin main #48782 this PR with #48955
socket, stdin paused for a setImmediate, of 30 0 30 30 0
shell pipe, stdin paused for a setImmediate, of 30 30 30 30 0
shell pipe, one nextTick between two chunks, of 50 42 43 47 0

The first row is a loss that main does not have.

#48955 changes two things of this PR:

  • setPollOnly() takes the state, and constructNativeReadable passes true. disown() of process.stdin clears the flag. With the flag left set, the stop for a paused consumer kept the next reader of Bun.stdin.stream() from its end: printf 'y\n' | bun with one 'data', pause(), and then for await (const line of console) did not reach the end of that loop.
  • bench/child_process/stdio.mjs gets a stdin source.

One finding that #48955 does not change: a fill of a socket reports the EOF with the last bytes. With Readable.fromWeb(Bun.stdin.stream()) over a socket that holds 270,000 bytes and the EOF, a loop with two nextTicks hears 'end' before it is done with the last 7,856 bytes (5 of 5 runs on this branch). A fix that leaves the EOF for the next read must not apply to a terminal: a read returns the Ctrl-D of a terminal once.

@robobun
robobun force-pushed the robobun/eba3bc94/pull-waits-after-short-read branch from f7101f8 to d0efd5f Compare November 15, 2026 06:55
@robobun

robobun commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

#48782 now carries this work in its own form, on a fresh base:

  • The consumer flag (setPollOnly(), set by constructNativeReadable): a pull and a restart of a Node stream only arm the poll.
  • The read before the exit report (Subprocess::on_process_exit calls FileReader::read_before_exit). It is taken from here. It now delivers one chunk per pass, stops at 2 MiB per stream, and also covers a host without pidfd.
  • The third parameter of constructNativeReadable ("libuv-handle" | "webstream") and the listener throw of child stdio: reportUncaughtException returns whether a handler took the error, and the stream reads on when one did.

Not taken: the bound of 2 MiB per wakeup of the read loop and the stop of the read loop at a hang-up. The read loop in #48782 is main's code.

#48955 targets this branch. It needs a rebase onto #48782: process.stdin behaves there as on main, and setPollOnly() takes no argument.

Closing in favor of #48782.

@robobun robobun closed this Nov 15, 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.

2 participants