From 6c8356f3aa96ee865841cf94fc7bae61752ab3fb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 04:57:15 +0000 Subject: [PATCH 1/4] node:process: track bytesWritten on stdio fast-path writes process.stdout and process.stderr route writes through a FileSink fast path that bypasses writeAll/writevAll, so this.bytesWritten was never incremented and stayed at 0. Node (net.Socket / tty.WriteStream) reports the encoded byte count synchronously after write(). Count bytes at each fast-path fileSink.write() site. Strings are measured with Buffer.byteLength so multi-byte UTF-8 is counted correctly. Fixes #23061. Co-authored-by: Steven Zimmerman <15812269+EffortlessSteven@users.noreply.github.com> --- src/js/internal/fs/streams.ts | 15 +++++++- test/js/node/process/process-stdio.test.ts | 42 +++++++++++++++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 44e8d040fd7b..cfc34b184173 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -606,6 +606,13 @@ function _write(data, encoding, cb) { } writeStreamPrototype._write = _write; +// Encoded byte count for a fast-path write. `writeFast` is the public +// `.write()`, so strings reach the sink undecoded and must be measured with +// Buffer.byteLength (not .length, which is UTF-16 code units). +function bytesForWrite(data: any, encoding?: BufferEncoding): number { + return typeof data === "string" ? Buffer.byteLength(data, encoding) : (data?.byteLength ?? data?.length ?? 0); +} + function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) { let fileSink = this[kWriteStreamFastPath]; if (!fileSink) { @@ -620,7 +627,9 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) this.fd = fileSink._getFd(); } + const bytes = bytesForWrite(data, encoding); const maybePromise = fileSink.write(data); + this.bytesWritten += bytes; if ($isPromise(maybePromise)) { maybePromise.then( () => { @@ -667,7 +676,9 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { + const bytes = bytesForWrite(data, encoding); const maybePromise = fileSink.write(data); + this.bytesWritten += bytes; if ($isPromise(maybePromise)) { // Two-arg then(): a throw from the fulfillment handler must not be // mistaken for a write failure. @@ -712,7 +723,9 @@ writeStreamPrototype._writev = function (data, cb) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { - const maybePromise = fileSink.write(Buffer.concat(chunks)); + const buffer = Buffer.concat(chunks); + const maybePromise = fileSink.write(buffer); + this.bytesWritten += buffer.length; if ($isPromise(maybePromise)) { maybePromise .then(() => { diff --git a/test/js/node/process/process-stdio.test.ts b/test/js/node/process/process-stdio.test.ts index ba35bc4f0484..6722d64f7aac 100644 --- a/test/js/node/process/process-stdio.test.ts +++ b/test/js/node/process/process-stdio.test.ts @@ -1,6 +1,7 @@ import { spawn, spawnSync } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe } from "harness"; +import { bunEnv, bunExe, tempDir } from "harness"; +import { readFileSync } from "node:fs"; import path from "path"; import { isatty } from "tty"; describe.concurrent("process-stdio", () => { @@ -158,4 +159,43 @@ describe.concurrent("process-stdio", () => { `hello worldhello again|😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌`.repeat(9999), ); }); + + // #23061: the FileSink fast path used for stdio handed chunks straight to the + // sink without touching this.bytesWritten, so the counter stayed at 0. Node + // (net.Socket/tty.WriteStream) reports the encoded byte count synchronously. + test("process.stdout/stderr.bytesWritten tracks fast-path writes", async () => { + using dir = tempDir("stdio-bytes-written", {}); + const reportPath = path.join(String(dir), "report.json"); + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const fs = require("node:fs"); + const before = { stdout: process.stdout.bytesWritten, stderr: process.stderr.bytesWritten }; + process.stdout.write("out-🚀"); // 8 UTF-8 bytes (4 + 4) + process.stdout.write(Buffer.from([65, 66])); // 2 bytes -> stdout total 10 + process.stderr.write("err-⚡"); // 7 UTF-8 bytes (4 + 3) + fs.writeFileSync(${JSON.stringify(reportPath)}, JSON.stringify({ + before, + stdout: process.stdout.bytesWritten, + stderr: process.stderr.bytesWritten, + })); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect(stdout).toBe("out-🚀AB"); + expect(stderr).toBe("err-⚡"); + expect(JSON.parse(readFileSync(reportPath, "utf8"))).toEqual({ + before: { stdout: 0, stderr: 0 }, + stdout: 10, + stderr: 7, + }); + expect(exitCode).toBe(0); + }); }); From 467f7857359b29b63d8243549e3d3c18465bc5da Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 05:13:50 +0000 Subject: [PATCH 2/4] Count bytes as UTF-8 and cover all four fileSink.write sites FileSink.write(string) has no encoding parameter and always emits UTF-8, so measure strings as UTF-8 regardless of the caller's encoding argument. Also add the increment to the prototype _write fast-path branch so all four fileSink.write sites are consistent. --- src/js/internal/fs/streams.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index cfc34b184173..fc432baf651b 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -571,11 +571,20 @@ function writevAll(chunks, size, pos, cb, retries = 0) { }); } +// Bytes handed to the FileSink for a fast-path write. FileSink.write(string) +// always encodes UTF-8 (it has no encoding parameter), so strings are measured +// as UTF-8 regardless of the caller's `encoding` argument, keeping the counter +// in lockstep with what actually reaches the fd. +function bytesForWrite(data: any): number { + return typeof data === "string" ? Buffer.byteLength(data) : (data?.byteLength ?? data?.length ?? 0); +} + function _write(data, encoding, cb) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { const maybePromise = fileSink.write(data); + this.bytesWritten += bytesForWrite(data); if ($isPromise(maybePromise)) { maybePromise .then(() => { @@ -606,13 +615,6 @@ function _write(data, encoding, cb) { } writeStreamPrototype._write = _write; -// Encoded byte count for a fast-path write. `writeFast` is the public -// `.write()`, so strings reach the sink undecoded and must be measured with -// Buffer.byteLength (not .length, which is UTF-16 code units). -function bytesForWrite(data: any, encoding?: BufferEncoding): number { - return typeof data === "string" ? Buffer.byteLength(data, encoding) : (data?.byteLength ?? data?.length ?? 0); -} - function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) { let fileSink = this[kWriteStreamFastPath]; if (!fileSink) { @@ -627,7 +629,7 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) this.fd = fileSink._getFd(); } - const bytes = bytesForWrite(data, encoding); + const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); this.bytesWritten += bytes; if ($isPromise(maybePromise)) { @@ -676,7 +678,7 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { - const bytes = bytesForWrite(data, encoding); + const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); this.bytesWritten += bytes; if ($isPromise(maybePromise)) { From f338d81be86daa60161dc6a95a61c5dbc7f9d5c0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 05:15:56 +0000 Subject: [PATCH 3/4] Trim bytesForWrite comment --- src/js/internal/fs/streams.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index fc432baf651b..8123ca9b5bb0 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -571,10 +571,7 @@ function writevAll(chunks, size, pos, cb, retries = 0) { }); } -// Bytes handed to the FileSink for a fast-path write. FileSink.write(string) -// always encodes UTF-8 (it has no encoding parameter), so strings are measured -// as UTF-8 regardless of the caller's `encoding` argument, keeping the counter -// in lockstep with what actually reaches the fd. +// FileSink.write(string) always emits UTF-8, so count that (not the caller's encoding). function bytesForWrite(data: any): number { return typeof data === "string" ? Buffer.byteLength(data) : (data?.byteLength ?? data?.length ?? 0); } From 14a770cf15ea9d2492e9930f3e8fde87bc73e593 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 05:45:10 +0000 Subject: [PATCH 4/4] Only count bytes the sink accepted; drop .length fallback A FileSink write that fails (EPIPE) returns a rejected promise; counting before the promise settles over-reports bytesWritten relative to Node, whose net.Socket only adds to _bytesDispatched after a successful low-level write. Move the increment into the synchronous-success branch and the promise fulfillment handler so a rejected write is not counted. Also drop the ?? data?.length fallback from bytesForWrite: every input without a numeric byteLength either already took the string branch or is rejected by FileSink.write before the increment runs. --- src/js/internal/fs/streams.ts | 15 ++++-- test/js/node/process/process-stdio.test.ts | 53 +++++++++++++++++++++- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 8123ca9b5bb0..5190767ccc08 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -573,24 +573,26 @@ function writevAll(chunks, size, pos, cb, retries = 0) { // FileSink.write(string) always emits UTF-8, so count that (not the caller's encoding). function bytesForWrite(data: any): number { - return typeof data === "string" ? Buffer.byteLength(data) : (data?.byteLength ?? data?.length ?? 0); + return typeof data === "string" ? Buffer.byteLength(data) : (data?.byteLength ?? 0); } function _write(data, encoding, cb) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { + const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); - this.bytesWritten += bytesForWrite(data); if ($isPromise(maybePromise)) { maybePromise .then(() => { + this.bytesWritten += bytes; this.emit("drain"); // Emit drain event cb(null); }) .catch(cb); return false; // Indicate backpressure } else { + this.bytesWritten += bytes; cb(null); return true; // No backpressure } @@ -628,10 +630,10 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); - this.bytesWritten += bytes; if ($isPromise(maybePromise)) { maybePromise.then( () => { + this.bytesWritten += bytes; if (cb) cb(null); this.emit("drain"); }, @@ -642,6 +644,7 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) ); return false; } else { + this.bytesWritten += bytes; if (cb) process.nextTick(cb, null); return true; } @@ -677,12 +680,12 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { if (fileSink && fileSink !== true) { const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); - this.bytesWritten += bytes; if ($isPromise(maybePromise)) { // Two-arg then(): a throw from the fulfillment handler must not be // mistaken for a write failure. maybePromise.then( () => { + this.bytesWritten += bytes; this.emit("drain"); // Emit drain event cb(null); }, @@ -695,6 +698,7 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { ); return false; // Indicate backpressure } else { + this.bytesWritten += bytes; cb(null); return true; // No backpressure } @@ -724,16 +728,17 @@ writeStreamPrototype._writev = function (data, cb) { if (fileSink && fileSink !== true) { const buffer = Buffer.concat(chunks); const maybePromise = fileSink.write(buffer); - this.bytesWritten += buffer.length; if ($isPromise(maybePromise)) { maybePromise .then(() => { + this.bytesWritten += buffer.length; this.emit("drain"); cb(null); }) .catch(cb); return false; } else { + this.bytesWritten += buffer.length; cb(null); return true; } diff --git a/test/js/node/process/process-stdio.test.ts b/test/js/node/process/process-stdio.test.ts index 6722d64f7aac..6642272a12ae 100644 --- a/test/js/node/process/process-stdio.test.ts +++ b/test/js/node/process/process-stdio.test.ts @@ -1,6 +1,6 @@ import { spawn, spawnSync } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, tempDir } from "harness"; +import { bunEnv, bunExe, isWindows, tempDir } from "harness"; import { readFileSync } from "node:fs"; import path from "path"; import { isatty } from "tty"; @@ -198,4 +198,55 @@ describe.concurrent("process-stdio", () => { }); expect(exitCode).toBe(0); }); + + // A write that the sink rejects (EPIPE) must not bump the counter. Node's + // net.Socket only adds to _bytesDispatched after a successful low-level + // write, so bytesWritten stays at whatever the last successful write left it. + test.skipIf(isWindows)("process.stdout.bytesWritten does not count a rejected write", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + process.stdout.on("error", () => {}); + process.stdout.write("abc"); + process.stderr.write("after-ok:" + process.stdout.bytesWritten + "\\n"); + process.stdin.once("data", () => { + process.stdout.write("xxxxxxxxxxxx", err => { + process.stderr.write(JSON.stringify({ + errored: err != null, + bytesWritten: process.stdout.bytesWritten, + }) + "\\n"); + process.exit(0); + }); + }); + process.stdin.resume(); + `, + ], + env: bunEnv, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + }); + + // Drain the child's first write so "abc" is out of the pipe buffer, then + // close the read end so the child's next stdout write fails with EPIPE. + const reader = proc.stdout.getReader(); + let seen = 0; + while (seen < 3) { + const { value, done } = await reader.read(); + if (done) break; + seen += value!.length; + } + await reader.cancel(); + + proc.stdin.write("go\n"); + proc.stdin.flush(); + + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + const lines = stderr.trim().split("\n"); + expect(lines[0]).toBe("after-ok:3"); + expect(JSON.parse(lines[1])).toEqual({ errored: true, bytesWritten: 3 }); + expect(exitCode).toBe(0); + }); });