Skip to content

Flush FileSink in process.stdout._final before end() callback fires - #28635

Merged
Jarred-Sumner merged 3 commits into
mainfrom
farm/b933f280/fix-stdout-end-truncation
Mar 30, 2026
Merged

Jarred-Sumner merged 3 commits into
mainfrom
farm/b933f280/fix-stdout-end-truncation

Conversation

@robobun

@robobun robobun commented Mar 29, 2026

Copy link
Copy Markdown
Collaborator

Problem

process.stdout.end(callback) fires callback before all data has been flushed through the pipe, causing truncation at power-of-2 boundaries (64KB, 128KB, etc.) when the callback calls process.exit(0).

Repro:

const output = "x".repeat(200000) + "\n";
process.stdout.write(output);
process.stdout.end(() => { process.exit(0); });
$ bun repro.js | wc -c
65536          # expected: 200001

Node.js outputs all 200001 bytes correctly.

Root Cause

process.stdout uses a fast-path writeFast() that bypasses Writable._writableState tracking (never updates pendingcb). When end() is called, finishMaybe() sees pendingcb === 0 and immediately schedules the finish callback — even though the underlying FileSink may still have buffered data waiting to be flushed through the pipe.

Additionally, process.stdout had no _final method defined. The _final hook is specifically designed for this purpose: it runs before the stream transitions to "finished" state, giving an opportunity to flush pending data.

Fix

Add a _final method to process.stdout and process.stderr that calls sink.flush() on the underlying FileSink. If flush() returns a Promise (data still pending in the pipe buffer), the callback waits for it to resolve before the stream finishes.

Closes #25432

Add a _final method to process.stdout and process.stderr that flushes
the underlying FileSink before the Writable stream transitions to the
finished state. Without this, process.stdout.end(cb) fires cb
immediately because writeFast bypasses _writableState tracking, so
the stream doesn't know about pending async writes. The callback
firing early means process.exit(0) can terminate the process before
all data is flushed through the pipe, causing truncation at power-of-2
boundaries (64KB, 128KB).

Closes #25432
@robobun

robobun commented Mar 29, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 9:33 AM PT - Mar 29th, 2026

❌ @robobun, your commit b54bc15 has 3 failures in Build #42646 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 28635

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

bun-28635 --bun

@coderabbitai

coderabbitai Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Install a _final(cb) handler on stdout/stderr write streams that flushes the underlying fast-path sink (kWriteStreamFastPath) during stream finalization, awaiting promise-based flushes and forwarding errors to the final callback. Added regression tests exercising process.stdout.end() with and without a saved/original stdout.write override.

Changes

Cohort / File(s) Summary
Stdout/Stderr Flush Implementation
src/js/builtins/ProcessObjectInternals.ts
Adds a _final(cb) handler for fd 1 and 2 write streams that retrieves this[kFastPath], calls sink.flush() when the sink exists and is not true, awaits promise results, calls cb(null) on success or cb(err) on error, and catches thrown errors to pass to cb(err).
Regression Tests
test/regression/issue/25432.test.ts
Adds two tests spawning fixtures that write ~200KB to stdout and call process.stdout.end(); one test uses a saved/bound original stdout.write after overriding process.stdout.write. Each asserts the child produced the expected byte count and exited with code 0.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding a flush mechanism in process.stdout._final before the end() callback fires.
Description check ✅ Passed The PR description includes both required sections: 'Problem' (explaining the issue), 'Root Cause' (analysis), and 'Fix' (solution). However, 'How did you verify your code works?' section is missing from the template.
Linked Issues check ✅ Passed The PR addresses all core coding requirements from #25432: adds _final method to flush FileSink, handles Promise returns from flush(), and includes regression tests covering the truncation scenario and stdout.write override case.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the issue: ProcessObjectInternals.ts adds the _final handler for stdout/stderr flushing, and regression test file tests the exact scenario from #25432.

✏️ 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 85-97: The _final implementation calls sink.flush() without
catching synchronous throws; wrap the sink.flush() invocation in a try/catch
inside stream._final (use the same kFastPath/sink logic) so that if sink.flush()
throws synchronously you call cb(err) instead of letting the exception escape;
if sink.flush() returns a promise (check via $isPromise(result)) attach then(()
=> cb(null), err => cb(err)) and return to avoid double-calling cb, otherwise
call cb(null) for the synchronous-success path.

In `@test/regression/issue/25432.test.ts`:
- Around line 17-26: The test currently parses and asserts stdout byte count
from the Bun.spawnSync call (variable result and byteCount) but does not assert
the subprocess exit status; after the existing stdout expectations
(expect(byteCount).toBe(...)) add an explicit assertion that the spawned process
exited successfully, e.g. assert the spawn result's exitCode is 0 (use
expect(result.exitCode).toBe(0)), and apply the same change to the other test
that uses Bun.spawnSync (the second spawned command block that also parses
stdout).
🪄 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: b8c2259e-85a4-47eb-9557-95fa4a40de21

📥 Commits

Reviewing files that changed from the base of the PR and between 1cc8376 and a9385ed.

📒 Files selected for processing (2)
  • src/js/builtins/ProcessObjectInternals.ts
  • test/regression/issue/25432.test.ts

Comment thread test/regression/issue/25432.test.ts Resolved

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

LGTM — clean, targeted fix using the correct hook with proper sync/async handling and a regression test.

Extended reasoning...

Overview

The PR modifies to add a method to and . It also adds a regression test in . The change is 13 lines of logic.

Security Risks

None. This only affects the stdio stream lifecycle and does not touch auth, crypto, permissions, or any external input handling.

Level of Scrutiny

Low. This is a focused bug fix to a well-understood problem. The hook is the canonical Node.js streams mechanism for flushing before finish. The guard correctly handles the sentinel value for . The async path properly chains the callback through promise resolution and rejection.

Other Factors

No bugs were found by the automated system. The fix matches the described root cause exactly. A regression test reproducing the truncation-at-power-of-2-boundaries issue is included and validates the fix end-to-end via a shell pipe.

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

🤖 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/regression/issue/25432.test.ts`:
- Around line 17-26: The test is asserting result.exitCode from Bun.spawnSync
which is the shell pipeline’s exit (wc -c), not the Bun child’s exit; update the
spawn to run bash -lc and use ${PIPESTATUS[0]} to capture the left-hand (bun)
exit code alongside the byte count (e.g. have the shell print the byte count and
then print PIPESTATUS[0] separated so you can parse both from result.stdout),
then assert the parsed bun child exit code is 0 in addition to the byteCount
check; references: Bun.spawnSync, bunExe(), result.stdout, result.exitCode.
🪄 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: 146dd0d4-d386-4e97-882b-6d54e85371b4

📥 Commits

Reviewing files that changed from the base of the PR and between a9385ed and b54bc15.

📒 Files selected for processing (2)
  • src/js/builtins/ProcessObjectInternals.ts
  • test/regression/issue/25432.test.ts

Comment on lines +17 to +26
const result = Bun.spawnSync({
cmd: ["sh", "-c", `"${bunExe()}" "${path.join(String(dir), "test.js")}" 2>/dev/null | wc -c`],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const byteCount = parseInt(result.stdout.toString().trim(), 10);
expect(byteCount).toBe(200001);
expect(result.exitCode).toBe(0);

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.

⚠️ Potential issue | 🟡 Minor

result.exitCode here is the pipeline status, not the Bun child’s.

Line 26 and Line 60 only prove that wc -c/the shell exited successfully. In sh -c 'bun ... | wc -c', the pipeline status comes from the last command, so this can still pass if the Bun subprocess exits non-zero after producing output. Capture the left-hand command’s exit code separately and assert that value too.

One way to make the child-exit assertion real (apply the same pattern to both tests)
+    const statusFile = path.join(String(dir), "child-exit-code.txt");
     const result = Bun.spawnSync({
-      cmd: ["sh", "-c", `"${bunExe()}" "${path.join(String(dir), "test.js")}" 2>/dev/null | wc -c`],
+      cmd: [
+        "sh",
+        "-c",
+        '{ "$1" "$2" 2>/dev/null; printf "%s" "$?" > "$3"; } | wc -c',
+        "sh",
+        bunExe(),
+        path.join(String(dir), "test.js"),
+        statusFile,
+      ],
       env: bunEnv,
       stdout: "pipe",
       stderr: "pipe",
     });
@@
     const byteCount = parseInt(result.stdout.toString().trim(), 10);
     expect(byteCount).toBe(200001);
+    expect(await Bun.file(statusFile).text()).toBe("0");
     expect(result.exitCode).toBe(0);

As per coding guidelines: "Always check exit codes and test error scenarios when spawning processes in tests."

Also applies to: 50-60

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

In `@test/regression/issue/25432.test.ts` around lines 17 - 26, The test is
asserting result.exitCode from Bun.spawnSync which is the shell pipeline’s exit
(wc -c), not the Bun child’s exit; update the spawn to run bash -lc and use
${PIPESTATUS[0]} to capture the left-hand (bun) exit code alongside the byte
count (e.g. have the shell print the byte count and then print PIPESTATUS[0]
separated so you can parse both from result.stdout), then assert the parsed bun
child exit code is 0 in addition to the byteCount check; references:
Bun.spawnSync, bunExe(), result.stdout, result.exitCode.

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

LGTM — the _final flush fix is correct and all reviewer feedback has been addressed.

Extended reasoning...

Overview

This PR adds a _final method to process.stdout/process.stderr in ProcessObjectInternals.ts that calls sink.flush() before the stream finishes, fixing truncation at power-of-2 boundaries when end(callback) fires process.exit. A regression test in test/regression/issue/25432.test.ts verifies the fix with two scenarios.

Security risks

None. This is a stream lifecycle change limited to stdout/stderr flush ordering. No auth, crypto, or permissions code is touched.

Level of scrutiny

Low-to-medium. The change is small and targeted: it adds a _final hook (a standard Node.js stream mechanism) and properly handles both synchronous and async flush paths with try/catch. The CodeRabbit feedback about missing try/catch and exit-code assertions was fully addressed in b54bc15.

Other factors

One nit was flagged: the expect(result.exitCode).toBe(0) assertion in each test checks the exit code of wc -c (last pipeline command), not bun itself, due to POSIX pipeline semantics. The byte-count assertions remain the effective regression guard. This is a minor test-quality issue that does not affect correctness of the fix or the test's ability to detect the original truncation bug.


const byteCount = parseInt(result.stdout.toString().trim(), 10);
expect(byteCount).toBe(200001);
expect(result.exitCode).toBe(0);

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 expect(result.exitCode).toBe(0) assertions in both tests check the exit code of wc -c (the last command in the shell pipeline), not bun itself. In POSIX sh, a pipeline exit code is always that of the rightmost command, so wc -c exits 0 regardless of whether bun crashed — the assertion provides false assurance about bun actual exit status. The byte count assertions remain the true regression guard; to also verify bun exit status, either capture bun exit code separately or run bun outside the shell pipeline.

Extended reasoning...

What the bug is

Both tests spawn a shell pipeline via sh -c "<bunExe> <script> 2>/dev/null | wc -c" and then assert expect(result.exitCode).toBe(0). In POSIX sh (and dash, the default /bin/sh on most Linux systems), the exit code of a pipeline A | B is the exit code of the last process in the pipeline — in this case wc -c, not bun.

The specific code path

At test/regression/issue/25432.test.ts line 26 (and its counterpart around line 58), result.exitCode is the exit code returned by Bun.spawnSync for the outer sh -c "..." invocation. The shell process itself exits with the status of the rightmost pipeline command: wc -c. Since wc -c succeeds (exits 0) whenever it reads its stdin to EOF — even if the upstream writer (bun) has already crashed — the shell exits 0 unconditionally.

Why existing code does not prevent it

The PR author added these assertions in commit b54bc15 in direct response to CodeRabbit request to "verify bun exited successfully". The intent was correct, but the implementation does not accomplish it. There is no set -o pipefail or PIPESTATUS check anywhere in the shell command, so bun individual exit code is silently discarded by the pipeline semantics.

Step-by-step proof

  1. Bun starts, writes some bytes, then crashes with SIGSEGV (exit code 139).
  2. wc -c receives EOF on its stdin (pipe closed because bun died).
  3. wc -c prints the byte count it saw and exits 0.
  4. sh -c "..." exits with the last pipeline stage code: 0.
  5. Bun.spawnSync returns exitCode: 0.
  6. expect(result.exitCode).toBe(0) passes — even though bun crashed.

A quick shell verification: sh -c "false | wc -c" exits 0 on any POSIX shell without pipefail.

Impact

The assertion was explicitly added to guard against bun process failures. It does not do what it claims. If bun were to regress and crash, the exit-code check would still pass. The byte-count check (expect(byteCount).toBe(200001)) is the real regression guard and correctly catches truncation — but the exit-code line is misleading.

How to fix

To actually test bun exit status within a shell pipeline, one approach uses bash PIPESTATUS: sh -c "... | wc -c; exit \${PIPESTATUS[0]}". Alternatively, run bun outside the shell pipe and assert byteCount and exitCode on separate Bun.spawnSync calls.

@Jarred-Sumner
Jarred-Sumner merged commit 9a27ef7 into main Mar 30, 2026
58 of 64 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/b933f280/fix-stdout-end-truncation branch March 30, 2026 07:45
structwafel pushed a commit to structwafel/bun that referenced this pull request Apr 25, 2026
…ven-sh#28635)

## Problem

`process.stdout.end(callback)` fires `callback` before all data has been
flushed through the pipe, causing truncation at power-of-2 boundaries
(64KB, 128KB, etc.) when the callback calls `process.exit(0)`.

**Repro:**
```js
const output = "x".repeat(200000) + "\n";
process.stdout.write(output);
process.stdout.end(() => { process.exit(0); });
```
```
$ bun repro.js | wc -c
65536          # expected: 200001
```

Node.js outputs all 200001 bytes correctly.

## Root Cause

`process.stdout` uses a fast-path `writeFast()` that bypasses
`Writable._writableState` tracking (never updates `pendingcb`). When
`end()` is called, `finishMaybe()` sees `pendingcb === 0` and
immediately schedules the finish callback — even though the underlying
`FileSink` may still have buffered data waiting to be flushed through
the pipe.

Additionally, `process.stdout` had no `_final` method defined. The
`_final` hook is specifically designed for this purpose: it runs before
the stream transitions to "finished" state, giving an opportunity to
flush pending data.

## Fix

Add a `_final` method to `process.stdout` and `process.stderr` that
calls `sink.flush()` on the underlying `FileSink`. If `flush()` returns
a Promise (data still pending in the pipe buffer), the callback waits
for it to resolve before the stream finishes.

Closes oven-sh#25432

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
xhjkl pushed a commit to xhjkl/bun that referenced this pull request May 14, 2026
…ven-sh#28635)

## Problem

`process.stdout.end(callback)` fires `callback` before all data has been
flushed through the pipe, causing truncation at power-of-2 boundaries
(64KB, 128KB, etc.) when the callback calls `process.exit(0)`.

**Repro:**
```js
const output = "x".repeat(200000) + "\n";
process.stdout.write(output);
process.stdout.end(() => { process.exit(0); });
```
```
$ bun repro.js | wc -c
65536          # expected: 200001
```

Node.js outputs all 200001 bytes correctly.

## Root Cause

`process.stdout` uses a fast-path `writeFast()` that bypasses
`Writable._writableState` tracking (never updates `pendingcb`). When
`end()` is called, `finishMaybe()` sees `pendingcb === 0` and
immediately schedules the finish callback — even though the underlying
`FileSink` may still have buffered data waiting to be flushed through
the pipe.

Additionally, `process.stdout` had no `_final` method defined. The
`_final` hook is specifically designed for this purpose: it runs before
the stream transitions to "finished" state, giving an opportunity to
flush pending data.

## Fix

Add a `_final` method to `process.stdout` and `process.stderr` that
calls `sink.flush()` on the underlying `FileSink`. If `flush()` returns
a Promise (data still pending in the pipe buffer), the callback waits
for it to resolve before the stream finishes.

Closes oven-sh#25432

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Jarred-Sumner pushed a commit that referenced this pull request Sep 25, 2026
…#43879)

Fixes #43875

### Problem
- `child.stdin.end(cb)` with no data fires `cb` and `'finish'` on the
next tick while earlier writes still wait behind pipe backpressure. Node
waits for the drain. A parent that exits in `cb` truncates the child's
input.
- `child.stdin` is a fast-path `fs.WriteStream`
(`src/js/internal/fs/streams.ts:474`). `writeFast` hands chunks to the
native `FileSink` and never updates `_writableState`, so `end()` sees
nothing pending. #28635 fixed this for `process.stdout` only, with a
per-instance `_final`.

### Fix
- Install `finalFast` as `_final` where the constructor installs the
fast path. It awaits `fileSink.flush()`, which returns the backlog's
promise when writes are pending.
- Delete the copy in `getStdioWriteStream`. `process.stdout` and
`process.stderr` now get it from the constructor.
- Suppress `'drain'` from the fast-path sites once the stream is ending
or destroyed, as `Writable`'s `afterWrite` does. The stream now stays
alive while the backlog drains, which made that late `'drain'` visible.
- Verified: `test/js/node/child_process/child_process.test.ts` and
`test/js/node/tty.test.ts` (one new case each, both fail on 1.4.3). Also
`test/regression/issue/25432.test.ts`, the `process` and `child_process`
suites, and the stdio cases in `test/js/node/test/parallel`.
- Self-reviewed: 1 concern raised, 1 addressed (the tty test held the
backlog with a `sleep`. It now gates the read on an IPC message).

### Background
- The fast path (`$fastPath: true`) has three callers: `child.stdin`,
`process.stdout`/`stderr`, and `tty.WriteStream`. It replaces `write`
with `writeFast`, which skips the `Writable` bookkeeping. `Writable`
emits `'finish'` when `_final(cb)` calls back, or at once when there is
no `_final`.
- Considered a `_final` on `child.stdin` alone: it repeats #28635 and
leaves `tty.WriteStream` broken. Considered routing `writeFast` through
`Writable.prototype.write`: it adds bookkeeping to every
`process.stdout.write`.

### Downsides
- `child.stdin` and `tty.WriteStream` gain one own property: 16 to 17
and 15 to 16 own keys (`Object.getOwnPropertyNames`, 1.4.3 vs this
build).
- Each `end()` on those streams makes one `flush()` host call. On an
empty buffer that is 0 syscalls (`IOWriter::flush` returns `Wrote(0)`,
`src/io/PipeWriter.rs:969`). `strace` is not installed here, so the
count is from the code.
- Code that relied on `'finish'` from `child.stdin` firing before the
pipe drained now sees it later.
- On Windows a single in-flight `uv_write` is not reported by `flush()`
(`src/io/PipeWriter.rs:2099`), so one unsent chunk can still be lost
when `cb` exits. This PR fixes the multi-chunk backlog. The single-chunk
case is pre-existing and needs a change in `FileSink`.

<details><summary>Notes</summary>

Ordering on the repro (3 untracked writes, `write(chunk, cb)`,
`'finish'` listener, `end(cb)`):

```
bun 1.4.3: end(cb) 1ms, 'finish' 1ms, write(cb) 243ms
this PR:   write(cb), end(cb), 'finish'  (same order as node)
```

`FileSink.flush()` (`src/runtime/webcore/FileSink.rs:983`) returns the
pending write promise when one exists, and a number when the buffer is
empty.

Open PR #36316 makes `child.stdin` a `net.Socket` subclass whose
`_write` goes through `Duplex`, which would also fix this for
`child.stdin`. It is a larger parity change and leaves `tty.WriteStream`
on the fast path. This PR does not depend on it.

Related issues with the same shape in other layers: #43155
(`http.ServerResponse`, fix in #41822) and #43874 (`TLSSocket` over a
`Duplex`).

`bun x tsc --noEmit -p src/js/tsconfig.json` reports the same 385
pre-existing errors with and without this change.

Two tests in the `child_process` suite fail on main in this container
without the change: "should allow us to spawn in the default shell" and
"extra stdio pipes are not double-closed on GC".

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 1 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/node/tty.test.ts,
test/js/node/child_process/child_process.test.ts

<!-- robobun:evidence:end -->
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.

stdout truncated at 64KB/128KB/256KB boundary when using saved process.stdout.write after override

2 participants