From e743d5c88a2c3dabe63baeb0053bffd7a3ab7697 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 05:21:22 +0000 Subject: [PATCH 1/7] fs: wait for the FileSink backlog in the WriteStream fast-path _final The fast path hands data to the FileSink without updating _writableState, so Writable's finish logic sees no pending writes. process.stdout got a per-instance _final that awaits sink.flush() in #28635. child.stdin and tty.WriteStream never did, so end(cb) and 'finish' fired at once. Install that _final where the fast path is installed, for every fast-path WriteStream, and delete the copy in ProcessObjectInternals. --- src/js/builtins/ProcessObjectInternals.ts | 20 ---------- src/js/internal/fs/streams.ts | 24 +++++++++++ .../node/child_process/child_process.test.ts | 40 +++++++++++++++++++ test/js/node/tty.test.ts | 39 ++++++++++++++++++ 4 files changed, 103 insertions(+), 20 deletions(-) diff --git a/src/js/builtins/ProcessObjectInternals.ts b/src/js/builtins/ProcessObjectInternals.ts index 781025562a29..8ea675755e15 100644 --- a/src/js/builtins/ProcessObjectInternals.ts +++ b/src/js/builtins/ProcessObjectInternals.ts @@ -85,26 +85,6 @@ export function getStdioWriteStream( }); } }; - - const kFastPath = require("internal/fs/streams").kWriteStreamFastPath; - stream._final = function (cb) { - try { - const sink = this[kFastPath]; - if (sink && sink !== true) { - const result = sink.flush(); - if ($isPromise(result)) { - result.then( - () => cb(null), - err => cb(err), - ); - return; - } - } - cb(null); - } catch (err) { - cb(err); - } - }; } stream._isStdio = true; diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 9fd151b947ac..fc266f6dbb4b 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -476,6 +476,7 @@ function WriteStream(this: FSStream, path: string | null | undefined, options?: this._write = underscoreWriteFast; this._writev = undefined; this.write = writeFast as any; + this._final = finalFast; if (fd != null) { // Already-open fd (stdio): skip the async _construct round-trip so the // stream is born constructed, like node's stdio streams (net.Socket / @@ -631,6 +632,29 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) } } +// writeFast hands data to the FileSink without touching _writableState, so +// Writable's finish logic sees no pending writes. The sink's flush() returns +// the promise of the backlog still queued behind backpressure; 'finish' and +// the end() callback wait for it, as node waits for its write callbacks. +function finalFast(this: FSStream, cb: (err?: any) => void) { + const fileSink = this[kWriteStreamFastPath]; + if (!fileSink || fileSink === true) { + cb(null); + return; + } + try { + const maybePromise = fileSink.flush(); + if ($isPromise(maybePromise)) { + maybePromise.then(() => cb(null), cb); + return; + } + } catch (err) { + cb(err); + return; + } + cb(null); +} + // This function implementation is not correct. const writablePrototypeWrite = Writable.prototype.write; const kWriteMonkeyPatchDefense = Symbol("!"); diff --git a/test/js/node/child_process/child_process.test.ts b/test/js/node/child_process/child_process.test.ts index fe7f6ec07465..d105c423a29e 100644 --- a/test/js/node/child_process/child_process.test.ts +++ b/test/js/node/child_process/child_process.test.ts @@ -389,6 +389,46 @@ describe("spawn()", () => { expect(result.trim()).toBe("hello"); }); + // The child does not read stdin until the parent tells it to over IPC, so + // every write past the pipe buffer sits in the parent's sink when end() runs. + it("stdin.end(cb) and 'finish' wait for the backlog to drain", async () => { + const child = spawn( + bunExe(), + [ + "-e", + `let n = 0; + process.on("message", () => { + process.stdin.on("data", d => { n += d.length; }); + process.stdin.on("end", () => { process.stdout.write(String(n)); process.disconnect(); }); + });`, + ], + { env: bunEnv, stdio: ["pipe", "pipe", "pipe", "ipc"] }, + ); + const stdout = new Promise(resolve => { + let out = ""; + child.stdout!.on("data", d => (out += d)); + child.stdout!.on("end", () => resolve(out)); + }); + const exited = new Promise(resolve => child.on("exit", resolve)); + + const order: string[] = []; + const chunk = Buffer.alloc(256 * 1024, 1); + for (let i = 0; i < 3; i++) child.stdin!.write(chunk); + child.stdin!.write(chunk, () => order.push("write")); + child.stdin!.on("finish", () => order.push("finish")); + const { promise: ended, resolve: onEnd } = Promise.withResolvers(); + child.stdin!.end(() => { + order.push("end"); + onEnd(); + }); + child.send("go"); + + await ended; + expect(await stdout).toBe(String(4 * chunk.length)); + expect(order).toEqual(["write", "end", "finish"]); + expect(await exited).toBe(0); + }); + it("should allow us to timeout hanging processes", async () => { const child = spawn(shellExe(), ["-c", "sleep", "2"], { timeout: 3 }); const start = performance.now(); diff --git a/test/js/node/tty.test.ts b/test/js/node/tty.test.ts index 3eca2321a0fa..c18eae7662f8 100644 --- a/test/js/node/tty.test.ts +++ b/test/js/node/tty.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, test } from "bun:test"; import { bunEnv, bunExe, isWindows } from "harness"; +import { spawn } from "node:child_process"; import { WriteStream } from "node:tty"; describe("ReadStream.prototype.setRawMode", () => { @@ -192,6 +193,44 @@ describe("ReadStream.prototype.setRawMode", () => { }); }); +describe("WriteStream end()", () => { + // The parent does not read the child's stdout until the child says it is + // about to call end(), so most of the 1 MiB sits in the stream's sink when + // end() runs. The callback must wait for it, or process.exit truncates it. + it.skipIf(isWindows)("fires the callback after the backlog is flushed", async () => { + const child = spawn( + bunExe(), + [ + "-e", + `const { WriteStream } = require("node:tty"); + const out = new WriteStream(1); + const chunk = Buffer.alloc(256 * 1024, 120); + for (let i = 0; i < 4; i++) out.write(chunk); + process.send("ending"); + out.end(() => process.exit(0));`, + ], + { env: bunEnv, stdio: ["ignore", "pipe", "pipe", "ipc"] }, + ); + let received = 0; + const read = () => child.stdout!.on("data", d => (received += d.length)); + child.on("message", read); + child.on("exit", read); + const stderr = new Promise(resolve => { + let err = ""; + child.stderr!.on("data", d => (err += d)); + child.stderr!.on("end", () => resolve(err)); + }); + const { promise: ended, resolve: onEnd } = Promise.withResolvers(); + child.stdout!.on("end", onEnd); + const exited = new Promise(resolve => child.on("exit", resolve)); + + await ended; + expect(await stderr).toBe(""); + expect(received).toBe(4 * 256 * 1024); + expect(await exited).toBe(0); + }); +}); + describe("WriteStream.prototype.getColorDepth", () => { const getColorDepth = (env: Record) => WriteStream.prototype.getColorDepth.call(undefined, env); From 9c0edf0575618d820673031f6681fe83d5fa1342 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 06:52:23 +0000 Subject: [PATCH 2/7] test: attach the stdout reader once in the tty WriteStream end() test --- test/js/node/tty.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/js/node/tty.test.ts b/test/js/node/tty.test.ts index c18eae7662f8..c0361a156473 100644 --- a/test/js/node/tty.test.ts +++ b/test/js/node/tty.test.ts @@ -212,7 +212,13 @@ describe("WriteStream end()", () => { { env: bunEnv, stdio: ["ignore", "pipe", "pipe", "ipc"] }, ); let received = 0; - const read = () => child.stdout!.on("data", d => (received += d.length)); + let reading = false; + // 'exit' is the fallback for a child that dies before it sends "ending". + const read = () => { + if (reading) return; + reading = true; + child.stdout!.on("data", d => (received += d.length)); + }; child.on("message", read); child.on("exit", read); const stderr = new Promise(resolve => { From bd839eab15acc75e45f30fdcc881d49a157e1a32 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 06:53:14 +0000 Subject: [PATCH 3/7] fs: shorten the finalFast comment --- src/js/internal/fs/streams.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index fc266f6dbb4b..4071ad77f617 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -632,10 +632,8 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) } } -// writeFast hands data to the FileSink without touching _writableState, so -// Writable's finish logic sees no pending writes. The sink's flush() returns -// the promise of the backlog still queued behind backpressure; 'finish' and -// the end() callback wait for it, as node waits for its write callbacks. +// writeFast bypasses _writableState, so 'finish' must wait on the sink's own +// backlog: flush() returns its promise while writes are pending. function finalFast(this: FSStream, cb: (err?: any) => void) { const fileSink = this[kWriteStreamFastPath]; if (!fileSink || fileSink === true) { From 7256aec586223f849086609e6aedfe92284a392b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 06:54:05 +0000 Subject: [PATCH 4/7] fs: drop the finalFast comment --- src/js/internal/fs/streams.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 4071ad77f617..ba944f086931 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -632,8 +632,6 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) } } -// writeFast bypasses _writableState, so 'finish' must wait on the sink's own -// backlog: flush() returns its promise while writes are pending. function finalFast(this: FSStream, cb: (err?: any) => void) { const fileSink = this[kWriteStreamFastPath]; if (!fileSink || fileSink === true) { From f18d81a96269cc1265f630f6864dc638862bd5c2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 07:02:24 +0000 Subject: [PATCH 5/7] test: send the IPC signal after end() in the tty WriteStream test --- test/js/node/tty.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/js/node/tty.test.ts b/test/js/node/tty.test.ts index c0361a156473..99d9849ac4db 100644 --- a/test/js/node/tty.test.ts +++ b/test/js/node/tty.test.ts @@ -194,9 +194,9 @@ describe("ReadStream.prototype.setRawMode", () => { }); describe("WriteStream end()", () => { - // The parent does not read the child's stdout until the child says it is - // about to call end(), so most of the 1 MiB sits in the stream's sink when - // end() runs. The callback must wait for it, or process.exit truncates it. + // The parent does not read the child's stdout until the child has called + // end(), so most of the 1 MiB sits in the stream's sink at that point. The + // callback must wait for it, or process.exit truncates the output. it.skipIf(isWindows)("fires the callback after the backlog is flushed", async () => { const child = spawn( bunExe(), @@ -206,8 +206,8 @@ describe("WriteStream end()", () => { const out = new WriteStream(1); const chunk = Buffer.alloc(256 * 1024, 120); for (let i = 0; i < 4; i++) out.write(chunk); - process.send("ending"); - out.end(() => process.exit(0));`, + out.end(() => process.exit(0)); + process.send("ending");`, ], { env: bunEnv, stdio: ["ignore", "pipe", "pipe", "ipc"] }, ); From d9a01fd2305d7b65e9c4e53ba92489a7f9bc9590 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 07:32:13 +0000 Subject: [PATCH 6/7] fs: no 'drain' from the fast path once the stream is ending or destroyed Writable's afterWrite suppresses 'drain' when ending or destroyed. The fast-path sites emitted it whenever the sink's pending promise resolved, so a backlogged stream now emitted 'drain' between end() and 'finish'. The child_process test also asserts no 'drain' after end(), drains the child's stderr, and fails fast if the child exits early. The tty test now runs on Windows too. --- src/js/internal/fs/streams.ts | 16 ++++++++++++---- .../node/child_process/child_process.test.ts | 19 +++++++++++++------ test/js/node/tty.test.ts | 2 +- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index ba944f086931..8547718d143b 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -559,6 +559,14 @@ function writevAll(chunks, size, pos, cb, retries = 0) { }); } +// Like Writable's afterWrite: no 'drain' once the stream is ending or destroyed. +function emitDrain(stream: FSStream) { + const state = stream._writableState; + if (state === undefined || !(state.ending || state.destroyed)) { + stream.emit("drain"); + } +} + function _write(data, encoding, cb) { const fileSink = this[kWriteStreamFastPath]; @@ -567,7 +575,7 @@ function _write(data, encoding, cb) { if ($isPromise(maybePromise)) { maybePromise .then(() => { - this.emit("drain"); // Emit drain event + emitDrain(this); cb(null); }) .catch(cb); @@ -613,7 +621,7 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) maybePromise.then( () => { if (cb) cb(null); - this.emit("drain"); + emitDrain(this); }, err => { if (cb) cb(err); @@ -680,7 +688,7 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { // mistaken for a write failure. maybePromise.then( () => { - this.emit("drain"); // Emit drain event + emitDrain(this); cb(null); }, err => { @@ -723,7 +731,7 @@ writeStreamPrototype._writev = function (data, cb) { if ($isPromise(maybePromise)) { maybePromise .then(() => { - this.emit("drain"); + emitDrain(this); cb(null); }) .catch(cb); diff --git a/test/js/node/child_process/child_process.test.ts b/test/js/node/child_process/child_process.test.ts index d105c423a29e..333f055e9514 100644 --- a/test/js/node/child_process/child_process.test.ts +++ b/test/js/node/child_process/child_process.test.ts @@ -404,26 +404,33 @@ describe("spawn()", () => { ], { env: bunEnv, stdio: ["pipe", "pipe", "pipe", "ipc"] }, ); - const stdout = new Promise(resolve => { - let out = ""; - child.stdout!.on("data", d => (out += d)); - child.stdout!.on("end", () => resolve(out)); - }); + const collect = (stream: NodeJS.ReadableStream) => + new Promise(resolve => { + let out = ""; + stream.on("data", d => (out += d)); + stream.on("end", () => resolve(out)); + }); + const stdout = collect(child.stdout!); + const stderr = collect(child.stderr!); const exited = new Promise(resolve => child.on("exit", resolve)); + // Node emits no 'drain' once end() has been called. const order: string[] = []; const chunk = Buffer.alloc(256 * 1024, 1); for (let i = 0; i < 3; i++) child.stdin!.write(chunk); child.stdin!.write(chunk, () => order.push("write")); + child.stdin!.on("drain", () => order.push("drain")); child.stdin!.on("finish", () => order.push("finish")); - const { promise: ended, resolve: onEnd } = Promise.withResolvers(); + const { promise: ended, resolve: onEnd, reject } = Promise.withResolvers(); child.stdin!.end(() => { order.push("end"); onEnd(); }); + child.on("exit", code => reject(new Error(`child exited with ${code} before end(cb) ran`))); child.send("go"); await ended; + expect(await stderr).toBe(""); expect(await stdout).toBe(String(4 * chunk.length)); expect(order).toEqual(["write", "end", "finish"]); expect(await exited).toBe(0); diff --git a/test/js/node/tty.test.ts b/test/js/node/tty.test.ts index 99d9849ac4db..cf98aa5a2659 100644 --- a/test/js/node/tty.test.ts +++ b/test/js/node/tty.test.ts @@ -197,7 +197,7 @@ describe("WriteStream end()", () => { // The parent does not read the child's stdout until the child has called // end(), so most of the 1 MiB sits in the stream's sink at that point. The // callback must wait for it, or process.exit truncates the output. - it.skipIf(isWindows)("fires the callback after the backlog is flushed", async () => { + it("fires the callback after the backlog is flushed", async () => { const child = spawn( bunExe(), [ From 9be4d19e1bf3eed345ae6bc34463ef64ebac98f2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 07:59:07 +0000 Subject: [PATCH 7/7] test: skip the tty WriteStream end() test on Windows, where stdout pipe writes block --- test/js/node/tty.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/js/node/tty.test.ts b/test/js/node/tty.test.ts index cf98aa5a2659..74b28d2e09f2 100644 --- a/test/js/node/tty.test.ts +++ b/test/js/node/tty.test.ts @@ -197,7 +197,11 @@ describe("WriteStream end()", () => { // The parent does not read the child's stdout until the child has called // end(), so most of the 1 MiB sits in the stream's sink at that point. The // callback must wait for it, or process.exit truncates the output. - it("fires the callback after the backlog is flushed", async () => { + // + // Windows: a write to an inherited stdout pipe blocks until the reader + // drains it (every write() returns true), so the child never reaches end() + // while the parent waits, and there is no backlog to flush. + it.skipIf(isWindows)("fires the callback after the backlog is flushed", async () => { const child = spawn( bunExe(), [