From 512ef2f0236730a5843d0dd08cbcb1498261b858 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:06:12 +0000 Subject: [PATCH 01/14] node:net: feed _writev chunks to the socket one at a time instead of concat+copy Socket.prototype._writev concatenated the whole batch into one Buffer and handed it to _write, which on a short write copies the unsent tail into the native buffered_data_for_node_net Vec. A writer that queues past backpressure against a stalled peer paid for three copies of the queue: the Writable buffer's references, the concat, and the native Vec (plus its growth headroom). 200 MiB queued cost ~600 MiB of RSS; node costs ~205 MiB because libuv's uv_write_t holds the caller's buffers by reference. Feed the normalized chunks through socket.$write one at a time instead. On the first short write the remaining chunks are parked on _pendingData as an array and the drain handler resumes from there; the native buffer only ever holds the unsent tail of a single chunk. cork()/uncork() can reach _writev before the handle is live, so the connecting/upgrade deferral mirrors _write. 200 MiB queued now costs ~211 MiB of RSS (debug/ASAN; ~207 MiB in node). --- src/js/node/net.ts | 140 +++++++++++++++++++++++++----- test/js/node/net/node-net.test.ts | 117 +++++++++++++++++++++++++ 2 files changed, 233 insertions(+), 24 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index 03ad37679853..f85c99f37060 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -422,6 +422,13 @@ const SocketHandlers: SocketHandler = { self.connecting = false; if (callback) { const writeChunk = self._pendingData; + if ($isArray(writeChunk)) { + // on_writable only dispatches this drain once the native buffer is + // empty, so resume directly from the next queued chunk. + self._pendingData = self[kwriteCallback] = null; + if (writeChunksUntilFull(self, socket, writeChunk, callback)) callback(null); + return; + } const res = socket.$write(writeChunk || "", self._pendingEncoding || "utf8"); if (res < 0) { // The retried send failed for good (peer gone): $write returned -errno. @@ -1285,6 +1292,16 @@ const SocketHandlers2: SocketHandler { + // A writer that queues past backpressure fills the Writable buffer; when the + // in-flight _write completes, clearBuffer hands the whole batch to _writev. + // Node holds the caller's Buffers by reference in a uv_write_t, so queuing + // N bytes costs ~N bytes of RSS. Concatenating the batch and copying the + // unsent tail into a native Vec on top of the caller's live references costs + // ~2x that at steady state (and ~3x at the transient peak). + // + // cork()/uncork() forces the whole batch through _writev synchronously so the + // sample is deterministic; the `bufs` array keeps the caller's references + // live so the steady-state difference (native copy vs. reference) is what is + // measured, not the GC-raceable transient peak. + it("holds queued _writev chunks by reference instead of copying into the native buffer", async () => { + const CHUNK = 65536; + const N = 1024; // 64 MiB queued + const fixture = ` + const net = require("node:net"); + const CHUNK = ${CHUNK}; + const N = ${N}; + const server = net.createServer({ pauseOnConnect: true }, () => {}); + server.listen(0, "127.0.0.1", () => { + const port = server.address().port; + const c = net.connect(port, "127.0.0.1", () => { + Bun.gc(true); + const rss0 = process.memoryUsage().rss; + const bufs = []; + c.cork(); + for (let n = 0; n < N; n++) { + const b = Buffer.alloc(CHUNK, 0x62); + bufs.push(b); + c.write(b); + } + c.uncork(); + Bun.gc(true); + const rss1 = process.memoryUsage().rss; + process.stdout.write(JSON.stringify({ + writableLength: c.writableLength, + rssDelta: rss1 - rss0, + held: bufs.length, + }) + "\\n"); + c.destroy(); + server.close(); + }); + }); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", fixture], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const { writableLength, rssDelta, held } = JSON.parse(stdout); + const queued = CHUNK * N; + expect(held).toBe(N); + // Most of the 64 MiB is still queued (a few MiB went to the kernel send + // buffer); writableLength reports the queued byte count either way. + expect(writableLength).toBeGreaterThan(queued * 0.75); + // Holding the queue by reference costs ~1.0x on top of the caller's live + // `bufs` (same Buffers). Copying into the native Vec costs another ~1.0x + // (plus growth headroom), i.e. >= 2.0x. The bound sits between the two, + // with headroom for ASAN/debug per-allocation overhead on the reference + // side. + const bound = queued * (isASAN || isDebug ? 1.7 : 1.5); + expect(rssDelta).toBeLessThan(bound); + expect(exitCode).toBe(0); + }); + + // The chunk-by-chunk path must still deliver every byte in order once the + // peer starts reading: this exercises the drain-resume path where + // _pendingData is an array. + it("delivers every queued byte in order once the peer reads", async () => { + const CHUNK = 65536; + const N = 512; // 32 MiB + const server = createServer({ pauseOnConnect: true }, sock => { + setImmediate(() => sock.resume()); + const chunks: Buffer[] = []; + sock.on("data", d => chunks.push(d)); + sock.on("end", () => { + const all = Buffer.concat(chunks); + sock.destroy(); + server.close(); + serverRecv.resolve(all); + }); + sock.on("error", serverRecv.reject); + }); + const serverRecv = Promise.withResolvers(); + await new Promise((resolve, reject) => { + server.on("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const port = (server.address() as import("node:net").AddressInfo).port; + + const expected = Buffer.allocUnsafe(CHUNK * N); + const finished = Promise.withResolvers(); + const c = connect(port, "127.0.0.1", () => { + let sawFalse = false; + for (let n = 0; n < N; n++) { + const b = Buffer.alloc(CHUNK, n & 0xff); + b.copy(expected, n * CHUNK); + if (!c.write(b)) sawFalse = true; + } + // The test only exercises the _writev queue path if backpressure was hit. + expect(sawFalse).toBe(true); + c.end(); + c.on("finish", finished.resolve); + c.on("error", finished.reject); + }); + const got = await serverRecv.promise; + await finished.promise; + expect(got.length).toBe(CHUNK * N); + expect(got.equals(expected)).toBe(true); + expect(c.bytesWritten).toBe(CHUNK * N); + c.destroy(); + }); +}); From d9766f8106b1c04ad8cff4b14d87cc222bae5199 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:24:27 +0000 Subject: [PATCH 02/14] lint: read chunk.chunk / this.connecting into locals (no-duplicate-conditional-property-access) --- src/js/node/net.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index f85c99f37060..ae8c09e52352 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -1865,8 +1865,11 @@ Object.defineProperty(Socket.prototype, "bytesWritten", { for (let i = 0; i < data.length; i++) { const chunk = data[i]; if (data.allBuffers || chunk instanceof Buffer) bytes += chunk.length; - else if (chunk.chunk !== undefined) bytes += Buffer.byteLength(chunk.chunk, chunk.encoding); - else bytes += chunk.length; + else { + const inner = chunk.chunk; + if (inner !== undefined) bytes += Buffer.byteLength(inner, chunk.encoding); + else bytes += chunk.length; + } } } else if (data) { // Writes are either a string or a Buffer. @@ -2800,13 +2803,14 @@ Socket.prototype._writev = function _writev(data, callback) { // connecting / upgrade-in-flight deferral mirrors _write. _pendingData // carries the Buffer[] and the drain handler resumes it once the handle is // open and the native buffer is empty. - if (this.connecting || (!this._handle && this[kupgraded] && !this.destroyed)) { + const connecting = this.connecting; + if (connecting || (!this._handle && this[kupgraded] && !this.destroyed)) { this._pendingData = data; this._pendingEncoding = ""; this[kwriteCallback] = callback; const retry = onWritevHandleReady.bind(this, data, callback); const onClose = onWritevCloseBeforeReady.bind(this, callback); - this.once(this.connecting ? "connect" : kUpgradeAttached, function () { + this.once(connecting ? "connect" : kUpgradeAttached, function () { this.off("close", onClose); retry(); }); From 9de12ed65b57e4a1584003136a0d7974754433d3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:26:21 +0000 Subject: [PATCH 03/14] trim code comments flagged by comment-cop --- src/js/node/net.ts | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index ae8c09e52352..12971215aa63 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -423,8 +423,6 @@ const SocketHandlers: SocketHandler = { if (callback) { const writeChunk = self._pendingData; if ($isArray(writeChunk)) { - // on_writable only dispatches this drain once the native buffer is - // empty, so resume directly from the next queued chunk. self._pendingData = self[kwriteCallback] = null; if (writeChunksUntilFull(self, socket, writeChunk, callback)) callback(null); return; @@ -1293,8 +1291,6 @@ const SocketHandlers2: SocketHandler Date: Sun, 26 Jul 2026 12:27:48 +0000 Subject: [PATCH 04/14] keep the _writev TODO attached to _writev; drop helper doc comment --- src/js/node/net.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index 12971215aa63..eba1c507eb11 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -2754,10 +2754,6 @@ Socket.prototype.destroySoon = function destroySoon() { else this.once("finish", this.destroy); }; -//TODO: migrate to native -// Writes `chunks` (normalized Buffer-likes) one at a time; on the first short -// write parks the remainder on `_pendingData` and arms the drain callback. -// Returns true when every chunk was fully accepted. function writeChunksUntilFull(self, socket, chunks, callback) { const len = chunks.length; for (let i = 0; i < len; i++) { @@ -2780,6 +2776,7 @@ function writeChunksUntilFull(self, socket, chunks, callback) { return true; } +//TODO: migrate to native Socket.prototype._writev = function _writev(data, callback) { const allBuffers = data.allBuffers; for (let i = 0; i < data.length; i++) { From dafc8a83c783f50b6393df09405bd65ce77902d8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:44:34 +0000 Subject: [PATCH 05/14] gate writeChunksUntilFull on empty native buffer; primordial slice; readyState guard; test try/finally writeChunksUntilFull now checks getBufferedAmount(socket) before feeding any chunk. SocketHandlers.open emits 'connect' (which runs the deferred _writev retry) and then calls drain() manually, so the array branch could otherwise re-enter $write with the native buffer still holding the previous chunk's tail. The native on_writable dispatch already guarantees emptiness, but the manual open()/kAttach call sites do not. Also: capture ArrayPrototypeSlice and call it via .$call (matching the file's existing Array primordial pattern); add the readyState < 0 guard to onWritevHandleReady (matching _write and the direct _writev path); and wrap the delivery test's client/server in try/finally with the error listener registered synchronously. --- src/js/node/net.ts | 23 +++++++++++++--- test/js/node/net/node-net.test.ts | 45 ++++++++++++++++--------------- 2 files changed, 43 insertions(+), 25 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index eba1c507eb11..e76783342d77 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -47,6 +47,7 @@ const { kArmHandshakeTimeout, kSecureConnectDone, kVerifyError } = require("inte const ArrayPrototypeIncludes = Array.prototype.includes; const ArrayPrototypeJoin = Array.prototype.join; const ArrayPrototypePush = Array.prototype.push; +const ArrayPrototypeSlice = Array.prototype.slice; const MathMax = Math.max; const MathMin = Math.min; @@ -2754,7 +2755,19 @@ Socket.prototype.destroySoon = function destroySoon() { else this.once("finish", this.destroy); }; +function parkPendingChunks(self, socket, chunks, callback) { + self._pendingData = chunks; + self._pendingEncoding = ""; + self[kwriteCallback] = callback; + if (self[kended] && !self[kUserUnrefed]) socket.ref?.(); +} + function writeChunksUntilFull(self, socket, chunks, callback) { + // Never feed a chunk while the native buffer still holds a tail (open() calls drain() manually). + if (getBufferedAmount(socket) > 0) { + parkPendingChunks(self, socket, chunks, callback); + return false; + } const len = chunks.length; for (let i = 0; i < len; i++) { const res = socket.$write(chunks[i], "buffer"); @@ -2765,10 +2778,7 @@ function writeChunksUntilFull(self, socket, chunks, callback) { } if (!res) { self[kBytesWritten] = socket.bytesWritten; - self._pendingData = i + 1 < len ? chunks.slice(i + 1) : null; - self._pendingEncoding = ""; - self[kwriteCallback] = callback; - if (self[kended] && !self[kUserUnrefed]) socket.ref?.(); + parkPendingChunks(self, socket, i + 1 < len ? ArrayPrototypeSlice.$call(chunks, i + 1) : null, callback); return false; } } @@ -2836,6 +2846,11 @@ function onWritevHandleReady(data, callback) { return; } this._unrefTimer(); + if (socket.readyState < 0) { + const er = new ErrnoException(process.platform === "win32" ? -4047 /* UV_EPIPE */ : -9 /* UV_EBADF */, "write"); + process.nextTick(callback, er); + return; + } if (writeChunksUntilFull(this, socket, data, callback)) { if (this.encrypted) process.nextTick(callback); else callback(); diff --git a/test/js/node/net/node-net.test.ts b/test/js/node/net/node-net.test.ts index c5e4edbabeb8..90b1c9654284 100644 --- a/test/js/node/net/node-net.test.ts +++ b/test/js/node/net/node-net.test.ts @@ -1898,19 +1898,17 @@ describe("net.Socket write buffering behind a stalled peer", () => { it("delivers every queued byte in order once the peer reads", async () => { const CHUNK = 65536; const N = 512; // 32 MiB + const serverRecv = Promise.withResolvers(); const server = createServer({ pauseOnConnect: true }, sock => { setImmediate(() => sock.resume()); const chunks: Buffer[] = []; sock.on("data", d => chunks.push(d)); sock.on("end", () => { - const all = Buffer.concat(chunks); sock.destroy(); - server.close(); - serverRecv.resolve(all); + serverRecv.resolve(Buffer.concat(chunks)); }); sock.on("error", serverRecv.reject); }); - const serverRecv = Promise.withResolvers(); await new Promise((resolve, reject) => { server.on("error", reject); server.listen(0, "127.0.0.1", resolve); @@ -1919,24 +1917,29 @@ describe("net.Socket write buffering behind a stalled peer", () => { const expected = Buffer.allocUnsafe(CHUNK * N); const finished = Promise.withResolvers(); - const c = connect(port, "127.0.0.1", () => { - let sawFalse = false; - for (let n = 0; n < N; n++) { - const b = Buffer.alloc(CHUNK, n & 0xff); - b.copy(expected, n * CHUNK); - if (!c.write(b)) sawFalse = true; - } + let sawFalse = false; + let c: Socket | undefined; + try { + c = connect(port, "127.0.0.1", () => { + for (let n = 0; n < N; n++) { + const b = Buffer.alloc(CHUNK, n & 0xff); + b.copy(expected, n * CHUNK); + if (!c!.write(b)) sawFalse = true; + } + c!.end(); + c!.on("finish", finished.resolve); + }); + c.on("error", finished.reject); + const got = await serverRecv.promise; + await finished.promise; // The test only exercises the _writev queue path if backpressure was hit. expect(sawFalse).toBe(true); - c.end(); - c.on("finish", finished.resolve); - c.on("error", finished.reject); - }); - const got = await serverRecv.promise; - await finished.promise; - expect(got.length).toBe(CHUNK * N); - expect(got.equals(expected)).toBe(true); - expect(c.bytesWritten).toBe(CHUNK * N); - c.destroy(); + expect(got.length).toBe(CHUNK * N); + expect(got.equals(expected)).toBe(true); + expect(c.bytesWritten).toBe(CHUNK * N); + } finally { + c?.destroy(); + server.close(); + } }); }); From 258f8827c5f45c2e2ff68a9b5238a092ea05cbf0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:51:22 +0000 Subject: [PATCH 06/14] test: reject serverRecv from the client error handler too --- test/js/node/net/node-net.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/js/node/net/node-net.test.ts b/test/js/node/net/node-net.test.ts index 90b1c9654284..4256f66a48bb 100644 --- a/test/js/node/net/node-net.test.ts +++ b/test/js/node/net/node-net.test.ts @@ -1929,7 +1929,10 @@ describe("net.Socket write buffering behind a stalled peer", () => { c!.end(); c!.on("finish", finished.resolve); }); - c.on("error", finished.reject); + c.on("error", err => { + finished.reject(err); + serverRecv.reject(err); + }); const got = await serverRecv.promise; await finished.promise; // The test only exercises the _writev queue path if backpressure was hit. From 483a18caaf4a30dfd1f0be348de4aa1c51623c30 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 13:17:46 +0000 Subject: [PATCH 07/14] match _write's error code in the _writev close-before-ready path The kUpgradeAttached branch closed with ERR_SOCKET_CLOSED_BEFORE_CONNECTION; _write's sibling onUpgradeWriteClose uses ERR_SOCKET_CLOSED there (the socket was already connected, it was being wrapped). Branch on the captured connecting flag so the multi-chunk path matches the single-chunk path. --- src/js/node/net.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index e76783342d77..22297bc59b66 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -2805,7 +2805,7 @@ Socket.prototype._writev = function _writev(data, callback) { this._pendingEncoding = ""; this[kwriteCallback] = callback; const retry = onWritevHandleReady.bind(this, data, callback); - const onClose = onWritevCloseBeforeReady.bind(this, callback); + const onClose = onWritevCloseBeforeReady.bind(this, connecting, callback); this.once(connecting ? "connect" : kUpgradeAttached, function () { this.off("close", onClose); retry(); @@ -2857,10 +2857,10 @@ function onWritevHandleReady(data, callback) { } } -function onWritevCloseBeforeReady(callback) { +function onWritevCloseBeforeReady(connecting, callback) { if (this[kwriteCallback] !== callback) return; this[kwriteCallback] = null; - callback($ERR_SOCKET_CLOSED_BEFORE_CONNECTION()); + callback(connecting ? $ERR_SOCKET_CLOSED_BEFORE_CONNECTION() : $ERR_SOCKET_CLOSED()); } Socket.prototype._write = function _write(chunk, encoding, callback) { From 1d39cb4b7f724b7f54799018470dbda6c2b788e6 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 15:25:39 +0000 Subject: [PATCH 08/14] keep the Buffer.concat _writev path on Windows Winsock indicates send completion for a first large send only when it is a single WSASend; usockets' bsd_writev on Windows is a sequential-send loop, so per-chunk $write calls backpressure on the large chunk after the small prefixes. Node's libuv hands the batch to uv_try_write as one iovec, which is why test-http-agent-reuse-drained-socket-only.js asserts writableLength === 0 after a corked 64 MiB batch there. Concat on Windows so that assertion (and any user code relying on the same synchronous-completion observation) keeps holding; the by-reference path stays POSIX-only. process.platform is inlined, so the concat branch is dead-stripped on POSIX builds. The RSS bound test is skipped on Windows accordingly. --- src/js/node/net.ts | 6 ++++++ test/js/node/net/node-net.test.ts | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index 22297bc59b66..3e9897e11d28 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -2797,6 +2797,12 @@ Socket.prototype._writev = function _writev(data, callback) { if (data.length === 1) { return this._write(data[0], "buffer", callback); } + // Winsock completes a first large send synchronously only when it is one + // WSASend; usockets has no vectored send on Windows, so concat to one buffer + // there (test-http-agent-reuse-drained-socket-only.js depends on this). + if (process.platform === "win32") { + return this._write(Buffer.concat(data), "buffer", callback); + } // cork()/uncork() can reach _writev before the handle is live; defer like _write. const connecting = this.connecting; diff --git a/test/js/node/net/node-net.test.ts b/test/js/node/net/node-net.test.ts index 4256f66a48bb..261eca9eef21 100644 --- a/test/js/node/net/node-net.test.ts +++ b/test/js/node/net/node-net.test.ts @@ -1836,7 +1836,11 @@ describe("net.Socket write buffering behind a stalled peer", () => { // sample is deterministic; the `bufs` array keeps the caller's references // live so the steady-state difference (native copy vs. reference) is what is // measured, not the GC-raceable transient peak. - it("holds queued _writev chunks by reference instead of copying into the native buffer", async () => { + // + // Windows keeps the Buffer.concat path (Winsock only completes a first large + // send synchronously when it is a single WSASend, and usockets has no + // vectored send there), so the by-reference bound only applies on POSIX. + it.skipIf(isWindows)("holds queued _writev chunks by reference instead of copying into the native buffer", async () => { const CHUNK = 65536; const N = 1024; // 64 MiB queued const fixture = ` From 6f217407a10a6f7454cab88dd81778acb6d2e644 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sun, 26 Jul 2026 15:27:50 +0000 Subject: [PATCH 09/14] [autofix.ci] apply automated fixes --- test/js/node/net/node-net.test.ts | 55 ++++++++++++++++--------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/test/js/node/net/node-net.test.ts b/test/js/node/net/node-net.test.ts index 261eca9eef21..075d47d8c716 100644 --- a/test/js/node/net/node-net.test.ts +++ b/test/js/node/net/node-net.test.ts @@ -1840,10 +1840,12 @@ describe("net.Socket write buffering behind a stalled peer", () => { // Windows keeps the Buffer.concat path (Winsock only completes a first large // send synchronously when it is a single WSASend, and usockets has no // vectored send there), so the by-reference bound only applies on POSIX. - it.skipIf(isWindows)("holds queued _writev chunks by reference instead of copying into the native buffer", async () => { - const CHUNK = 65536; - const N = 1024; // 64 MiB queued - const fixture = ` + it.skipIf(isWindows)( + "holds queued _writev chunks by reference instead of copying into the native buffer", + async () => { + const CHUNK = 65536; + const N = 1024; // 64 MiB queued + const fixture = ` const net = require("node:net"); const CHUNK = ${CHUNK}; const N = ${N}; @@ -1873,28 +1875,29 @@ describe("net.Socket write buffering behind a stalled peer", () => { }); }); `; - await using proc = Bun.spawn({ - cmd: [bunExe(), "-e", fixture], - env: bunEnv, - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - const { writableLength, rssDelta, held } = JSON.parse(stdout); - const queued = CHUNK * N; - expect(held).toBe(N); - // Most of the 64 MiB is still queued (a few MiB went to the kernel send - // buffer); writableLength reports the queued byte count either way. - expect(writableLength).toBeGreaterThan(queued * 0.75); - // Holding the queue by reference costs ~1.0x on top of the caller's live - // `bufs` (same Buffers). Copying into the native Vec costs another ~1.0x - // (plus growth headroom), i.e. >= 2.0x. The bound sits between the two, - // with headroom for ASAN/debug per-allocation overhead on the reference - // side. - const bound = queued * (isASAN || isDebug ? 1.7 : 1.5); - expect(rssDelta).toBeLessThan(bound); - expect(exitCode).toBe(0); - }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", fixture], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const { writableLength, rssDelta, held } = JSON.parse(stdout); + const queued = CHUNK * N; + expect(held).toBe(N); + // Most of the 64 MiB is still queued (a few MiB went to the kernel send + // buffer); writableLength reports the queued byte count either way. + expect(writableLength).toBeGreaterThan(queued * 0.75); + // Holding the queue by reference costs ~1.0x on top of the caller's live + // `bufs` (same Buffers). Copying into the native Vec costs another ~1.0x + // (plus growth headroom), i.e. >= 2.0x. The bound sits between the two, + // with headroom for ASAN/debug per-allocation overhead on the reference + // side. + const bound = queued * (isASAN || isDebug ? 1.7 : 1.5); + expect(rssDelta).toBeLessThan(bound); + expect(exitCode).toBe(0); + }, + ); // The chunk-by-chunk path must still deliver every byte in order once the // peer starts reading: this exercises the drain-resume path where From aeb327add73ccd2992657b256eae72a34ddd7962 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 15:28:31 +0000 Subject: [PATCH 10/14] shrink Windows concat comment to one line (comment-cop) --- src/js/node/net.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index 3e9897e11d28..fe9db418b89f 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -2797,10 +2797,8 @@ Socket.prototype._writev = function _writev(data, callback) { if (data.length === 1) { return this._write(data[0], "buffer", callback); } - // Winsock completes a first large send synchronously only when it is one - // WSASend; usockets has no vectored send on Windows, so concat to one buffer - // there (test-http-agent-reuse-drained-socket-only.js depends on this). if (process.platform === "win32") { + // Winsock only sync-completes a first large send as one WSASend; no vectored send in usockets here. return this._write(Buffer.concat(data), "buffer", callback); } From 6d547168fa02767fe1ae36eaa62cd06fa0fbc056 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 26 Jul 2026 15:45:59 +0000 Subject: [PATCH 11/14] drop unreachable win32 errno arm in _writev/onWritevHandleReady readyState guards The win32 early-return at the top of _writev makes both guards POSIX-only; process.platform is inlined per target so the ternary always folded to -9. --- src/js/node/net.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index fe9db418b89f..f8a59251c7fa 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -2828,8 +2828,7 @@ Socket.prototype._writev = function _writev(data, callback) { } this._unrefTimer(); if (socket.readyState < 0) { - const er = new ErrnoException(process.platform === "win32" ? -4047 /* UV_EPIPE */ : -9 /* UV_EBADF */, "write"); - process.nextTick(callback, er); + process.nextTick(callback, new ErrnoException(-9 /* UV_EBADF */, "write")); return false; } @@ -2851,8 +2850,7 @@ function onWritevHandleReady(data, callback) { } this._unrefTimer(); if (socket.readyState < 0) { - const er = new ErrnoException(process.platform === "win32" ? -4047 /* UV_EPIPE */ : -9 /* UV_EBADF */, "write"); - process.nextTick(callback, er); + process.nextTick(callback, new ErrnoException(-9 /* UV_EBADF */, "write")); return; } if (writeChunksUntilFull(this, socket, data, callback)) { From 544ff28db23ffbc340d9ee470aea1fff9818032b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 15:31:02 +0000 Subject: [PATCH 12/14] mirror #33974's loop-hold contract in the parked _writev path parkPendingChunks re-takes the hold on kPausedUnref as well as kended, matching _write's short-write branch, and both drain array branches release it through unrefAfterDrain like their single-chunk siblings. Without this a client paused by an unread reply exits with its queued batch unflushed once the first chunk drains (the drain's unrefAfterDrain drops the hold and the batch parked behind it never re-took it). Adds the multi-chunk twin of the #33974 keep-alive test; it prints 'drained false' with the old condition. --- src/js/node/net.ts | 10 +++++--- test/js/node/net/node-net.test.ts | 41 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index 5700a8c2c517..d9d206027275 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -426,7 +426,10 @@ const SocketHandlers: SocketHandler = { const writeChunk = self._pendingData; if ($isArray(writeChunk)) { self._pendingData = self[kwriteCallback] = null; - if (writeChunksUntilFull(self, socket, writeChunk, callback)) callback(null); + if (writeChunksUntilFull(self, socket, writeChunk, callback)) { + unrefAfterDrain(self, socket); + callback(null); + } return; } const res = socket.$write(writeChunk || "", self._pendingEncoding || "utf8"); @@ -1294,7 +1297,7 @@ const SocketHandlers2: SocketHandler { server.close(); } }); + + // Multi-chunk twin of "a write still waiting for drain does keep it alive": + // the unread reply pauses the client (dropping its hold on the loop), the + // first chunk's drain gives the hold up again via unrefAfterDrain, and the + // batch _writev then parks behind it must re-take it the way _write does, + // or the process exits with the queue unflushed. + it.skipIf(isWindows)("a parked _writev batch keeps the process alive until it drains", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const net = require("net"); + let drained = false; + const server = net.createServer(s => { + s.unref(); + s.pause(); + s.write(Buffer.alloc(256 * 1024, 0x61)); + setTimeout(() => { s.on("data", () => {}); s.resume(); }, 100).unref(); + }); + server.unref(); + server.listen(0, () => { + const c = net.connect(server.address().port, () => { + for (let i = 0; i < 127; i++) c.write(Buffer.alloc(64 * 1024, 0x62)); + c.write(Buffer.alloc(64 * 1024, 0x62), () => { drained = true; c.destroy(); }); + }); + }); + process.on("exit", code => console.log("exit", code, "drained", drained)); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode }).toEqual({ + stdout: "exit 0 drained true", + stderr: "", + exitCode: 0, + }); + }); }); // On Windows the connect-error path receives raw WSA codes (WSAECONNRESET, From 53c7991d36b5cbbcaa00804d4a544d229bf8ce84 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 10 Sep 2026 21:53:03 +0000 Subject: [PATCH 13/14] test: use --expose-gc + globalThis.gc() in the RSS fixture so the same fixture runs on node --- test/js/node/net/node-net.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/js/node/net/node-net.test.ts b/test/js/node/net/node-net.test.ts index b1748d28c93a..66699f1c7b37 100644 --- a/test/js/node/net/node-net.test.ts +++ b/test/js/node/net/node-net.test.ts @@ -2262,7 +2262,7 @@ describe("net.Socket write buffering behind a stalled peer", () => { server.listen(0, "127.0.0.1", () => { const port = server.address().port; const c = net.connect(port, "127.0.0.1", () => { - Bun.gc(true); + globalThis.gc(); const rss0 = process.memoryUsage().rss; const bufs = []; c.cork(); @@ -2272,7 +2272,7 @@ describe("net.Socket write buffering behind a stalled peer", () => { c.write(b); } c.uncork(); - Bun.gc(true); + globalThis.gc(); const rss1 = process.memoryUsage().rss; process.stdout.write(JSON.stringify({ writableLength: c.writableLength, @@ -2285,7 +2285,7 @@ describe("net.Socket write buffering behind a stalled peer", () => { }); `; await using proc = Bun.spawn({ - cmd: [bunExe(), "-e", fixture], + cmd: [bunExe(), "--expose-gc", "-e", fixture], env: bunEnv, stderr: "pipe", }); From 47ecee593592a79699e3d5d676ed5ba561e320f9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:39:16 +0000 Subject: [PATCH 14/14] net: share the _writev dispatch body between the direct and deferred paths --- src/js/node/net.ts | 41 ++++++++++++++--------------------------- 1 file changed, 14 insertions(+), 27 deletions(-) diff --git a/src/js/node/net.ts b/src/js/node/net.ts index d9d206027275..a670a4ab6f45 100644 --- a/src/js/node/net.ts +++ b/src/js/node/net.ts @@ -2807,47 +2807,34 @@ Socket.prototype._writev = function _writev(data, callback) { return; } - const socket = this._handle; - this._pendingData = null; - this._pendingEncoding = ""; - this[kwriteCallback] = null; - if (!socket) { - callback($ERR_SOCKET_CLOSED()); - return false; - } - this._unrefTimer(); - if (socket.readyState < 0) { - process.nextTick(callback, new ErrnoException(-9 /* UV_EBADF */, "write")); - return false; - } - - if (writeChunksUntilFull(this, socket, data, callback)) { - if (this.encrypted) process.nextTick(callback); - else callback(); - } + dispatchWritev(this, data, callback); }; -function onWritevHandleReady(data, callback) { - if (this[kwriteCallback] !== callback) return; - const socket = this._handle; - this._pendingData = null; - this._pendingEncoding = ""; - this[kwriteCallback] = null; +function dispatchWritev(self, data, callback) { + const socket = self._handle; + self._pendingData = null; + self._pendingEncoding = ""; + self[kwriteCallback] = null; if (!socket) { callback($ERR_SOCKET_CLOSED()); return; } - this._unrefTimer(); + self._unrefTimer(); if (socket.readyState < 0) { process.nextTick(callback, new ErrnoException(-9 /* UV_EBADF */, "write")); return; } - if (writeChunksUntilFull(this, socket, data, callback)) { - if (this.encrypted) process.nextTick(callback); + if (writeChunksUntilFull(self, socket, data, callback)) { + if (self.encrypted) process.nextTick(callback); else callback(); } } +function onWritevHandleReady(data, callback) { + if (this[kwriteCallback] !== callback) return; + dispatchWritev(this, data, callback); +} + function onWritevCloseBeforeReady(connecting, callback) { if (this[kwriteCallback] !== callback) return; this[kwriteCallback] = null;