From 2f4bc55f0eb9b5d67862269cbbe4b1899b72a63e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 07:32:40 +0000 Subject: [PATCH 1/4] net: fail the write when the flush that ends the open dispatch hits a fatal send error A write from inside the 'connection' or 'connect' listener runs under the native open dispatch. When its send is short, on_open flushes the rest of buffered_data_for_node_net once the listener returns. It discarded the errno that internal_flush reports for a fatal send (EPIPE, ECONNRESET). It then saw the buffer empty, because the fatal path drops the bytes, and dispatched the drain callback. node:net completed the write as delivered: the callback succeeded and 'finish' fired for bytes that were never sent. on_writable already fails the write in this case on POSIX. Move that delivery into fail_fatal_flush and call it from the tail of on_open too. Windows keeps the legacy contract in both places. write_or_end also queued the bytes of a write whose first send was fatal, although JS fails that write. The same flush then sent them again. Do not queue them. --- src/runtime/socket/socket_body.rs | 84 +++++++++++------ test/js/node/net/net-syscall-fault.test.ts | 105 +++++++++++++++++++++ test/js/node/net/node-net-server.test.ts | 75 ++++++++++++++- 3 files changed, 232 insertions(+), 32 deletions(-) diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 78c1cf81c11d..9a32e89f7100 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -903,6 +903,39 @@ impl NewSocket { called } + /// `internal_flush` reported a fatal send errno under an event-loop + /// dispatch. On POSIX that signal is trustworthy: + /// us_socket_write_check_error only reports an errno that is either known + /// peer-gone or persisted across its bounded unclassified-errno retry + /// window. internal_flush already dropped the undeliverable buffer and the + /// writable poll is no longer re-armed, so the dispatch is the last place + /// the errno is visible - swallowing it acknowledged the bytes to JS, and + /// the peer saw a stream with those bytes missing. Deliver it like a failed + /// write (syscall "write", same shape as net.ts failWrite) and close the + /// socket so 'error' is followed by 'close'. The caller holds the handlers + /// scope. + #[cfg(not(windows))] + fn fail_fatal_flush( + &self, + handlers: &Handlers, + this_value: JSValue, + fatal_send_errno: i32, + ) -> JsResult<()> { + let global = handlers.global_object; + let err_value = ::to_js( + &sys::Error::from_code_int(fatal_send_errno, sys::Tag::write), + &global, + ); + handlers.call_error_handler(this_value, &[this_value, err_value])?; + // The error handler can destroy the socket itself; only close a + // still-attached socket. Close without detaching so on_close runs + // and JS observes 'close' (mirrors h2's dead-transport close). + if !self.socket.get().is_detached() { + self.socket.get().close(uws::CloseCode::Normal); + } + Ok(()) + } + /// Takes `ThisPtr`, not `&mut self`: `callback.call(...)` re-enters /// JS which can call `socket.write()`/`end()`/`reload()` on this same /// wrapper via the JS object's `m_ptr`, re-deriving a borrow and mutating @@ -946,35 +979,14 @@ impl NewSocket { // Windows, keep the legacy contract there (the close path still fails // the pending write callback when the socket is torn down). let fatal_send_errno = this.internal_flush(); - // On POSIX the fatal signal is trustworthy: us_socket_write_check_error - // only reports an errno that is either known peer-gone or persisted - // across its bounded unclassified-errno retry window. internal_flush - // already dropped the undeliverable buffer and the writable poll is no - // longer re-armed, so this dispatch is the last place the errno is - // visible - swallowing it here acknowledged the bytes to JS, sent a - // clean FIN, and the peer saw a silently truncated stream. Deliver it - // like a failed write (syscall "write", same shape as net.ts - // failWrite) and close the socket so 'error' is followed by 'close'. #[cfg(not(windows))] if fatal_send_errno != 0 { - let global = handlers.global_object; let _scope = ScopeExit { socket: this, scope: Some(handlers.enter()), }; - let this_value = this.get_this_value(&global); - let err_value = ::to_js( - &sys::Error::from_code_int(fatal_send_errno, sys::Tag::write), - &global, - ); - handlers.call_error_handler(this_value, &[this_value, err_value])?; - // The error handler can destroy the socket itself; only close a - // still-attached socket. Close without detaching so on_close runs - // and JS observes 'close' (mirrors h2's dead-transport close). - if !this.socket.get().is_detached() { - this.socket.get().close(uws::CloseCode::Normal); - } - return Ok(()); + let this_value = this.get_this_value(&handlers.global_object); + return this.fail_fatal_flush(&handlers, this_value, fatal_send_errno); } #[cfg(windows)] let _ = fatal_send_errno; @@ -1620,7 +1632,16 @@ impl NewSocket { // pending JS write the same way on_writable's tail does, otherwise // the do_socket_write backpressure arms the normal writable // subscription. - let _ = this.internal_flush(); + let fatal_send_errno = this.internal_flush(); + // A fatal flush also leaves the buffer empty (it drops the bytes), + // so the drain below would complete that write as delivered. + // Windows keeps the legacy contract, as in on_writable. + #[cfg(not(windows))] + if fatal_send_errno != 0 { + return this.fail_fatal_flush(&handlers, this_value, fatal_send_errno); + } + #[cfg(windows)] + let _ = fatal_send_errno; if this.buffered_data_for_node_net.get().len() == 0 { let drain_callback = handlers.on_writable(); if !drain_callback.is_empty() { @@ -2146,7 +2167,7 @@ impl NewSocket { } // Reached by a nested dispatch (a close from on_open's error branch, - // on_writable's fatal close, a rejected handshake) while the handler + // fail_fatal_flush's close, a rejected handshake) while the handler // above is unwinding with a termination pending: it belongs to that // frame, so this dispatch neither enters JS over it nor claims it. if handlers.global_object.has_exception() { @@ -2980,7 +3001,9 @@ impl NewSocket { log!("writeOrEnd {}", bytes.len()); let wrote = self.write_maybe_corked(bytes); let uwrote: usize = usize::try_from(wrote.max(0)).expect("int cast"); - if buffer_unwritten_data { + // `wrote < -1` is a fatal send: JS fails that write, so its bytes must + // not stay queued for a later flush to retry. + if buffer_unwritten_data && wrote >= -1 { let remaining = &bytes[uwrote..]; if !remaining.is_empty() { let _ = self @@ -3020,10 +3043,11 @@ impl NewSocket { /// Flushes the node:net buffered tail. Returns 0, or the positive errno of /// a fatal send error (buffer dropped, writable not re-armed). - /// On POSIX, `on_writable` consumes the errno: it dispatches the error - /// handler and closes the socket. On Windows the errno is still ignored - /// (the drain callback is dispatched regardless) - skipping the drain on - /// fatal made Windows servers reset FIN-terminated responses (see + /// On POSIX, the event-loop callers (`on_writable` and the tail of + /// `on_open`) consume the errno through `fail_fatal_flush`: it dispatches + /// the error handler and closes the socket. On Windows the errno is still + /// ignored (the drain callback is dispatched regardless) - skipping the + /// drain on fatal made Windows servers reset FIN-terminated responses (see /// a5e7ba5905) - until the Windows fatal-write detection is verified. fn internal_flush(&self) -> i32 { // A TLS socket whose handshake was rejected has no usable transport: diff --git a/test/js/node/net/net-syscall-fault.test.ts b/test/js/node/net/net-syscall-fault.test.ts index 0d7975d07ac4..0baa744e491e 100644 --- a/test/js/node/net/net-syscall-fault.test.ts +++ b/test/js/node/net/net-syscall-fault.test.ts @@ -165,6 +165,111 @@ describe.skipIf(skip)("node:net under injected syscall faults", () => { ); } + // Calls `write` on one side from inside its 'connection' (server) or + // 'connect' (client) listener, so under the native open dispatch. Resolves + // once both sockets are closed. + async function writeInsideOpenDispatch( + side: "client" | "server", + write: (s: net.Socket, fd: number, headWritten: (err?: Error | null) => void) => void, + ) { + let headError: NodeJS.ErrnoException | null | undefined; + let socketError: NodeJS.ErrnoException | undefined; + let received = Buffer.alloc(0); + const sockets: net.Socket[] = []; + const closed: Promise[] = []; + function track(s: net.Socket) { + sockets.push(s); + closed.push(new Promise(resolve => s.once("close", () => resolve()))); + } + function writer(s: net.Socket) { + s.on("error", err => (socketError = err)); + const fd = (s as any)._handle.fd as number; + // An fd-less rule would match every socket in the process. + expect(fd).toBeGreaterThanOrEqual(0); + write(s, fd, err => (headError = err ?? null)); + } + function reader(s: net.Socket) { + s.on("error", () => {}); + s.on("data", c => (received = Buffer.concat([received, c]))); + } + + const server = net.createServer(s => { + track(s); + if (side === "server") writer(s); + else reader(s); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const client = net.connect({ port: (server.address() as net.AddressInfo).port, host: "127.0.0.1" }); + track(client); + if (side === "client") client.once("connect", () => writer(client)); + else reader(client); + + try { + await Promise.all([once(client, "connect"), once(server, "connection")]); + await Promise.all(closed); + } finally { + for (const s of sockets) s.destroy(); + server.close(); + } + + const shape = (err: NodeJS.ErrnoException | null | undefined) => err && { code: err.code, syscall: err.syscall }; + return { headError: shape(headError), socketError: shape(socketError), received }; + } + + for (const side of ["client", "server"] as const) { + // The remainder of a short send made under the open dispatch is flushed + // when that dispatch ends, not by a writable event. A fatal errno from + // that flush must fail the write and destroy the socket. Reporting it as + // drained let the next write go out on the same connection with the + // dropped bytes missing from the middle of the stream. + test.each(["EPIPE", "ECONNRESET"] as const)( + `send → %s on the flush that ends the open dispatch fails the write (${side} writer)`, + async errno => { + const head = Buffer.from(Array.from({ length: 200 }, (_, i) => i & 0xff)); + const body = Buffer.alloc(4096, 0xee); + const { received, ...errors } = await writeInsideOpenDispatch(side, (s, fd, headWritten) => { + // send #0: 1 byte accepted, the other 199 stay in + // buffered_data_for_node_net. + fault.set({ syscall: "send", action: "short", bytes: 1, repeat: 1, fd }); + s.write(head, headWritten); + // send #1: the flush of that remainder once the listener returns. + fault.set({ syscall: "send", action: "errno", errno, repeat: 1, fd }); + s.write(body); + s.end(); + }); + + // The peer may only see bytes from before the failed send: head[0]. + const stream = Buffer.concat([head, body]); + expect({ + ...errors, + received: { length: received.length, isPrefixOfStream: received.equals(stream.subarray(0, received.length)) }, + }).toEqual({ + headError: { code: errno, syscall: "write" }, + socketError: { code: errno, syscall: "write" }, + received: { length: 1, isPrefixOfStream: true }, + }); + }, + ); + + // A send the kernel rejects outright fails the write in JS. Its bytes must + // not stay queued: that flush sent them again, so the peer could receive + // a write that JS had been told failed. + test(`send → ECONNRESET on a write under the open dispatch is not sent again (${side} writer)`, async () => { + const { received, ...errors } = await writeInsideOpenDispatch(side, (s, fd, headWritten) => { + // One shot: a second send of the same bytes would succeed. + fault.set({ syscall: "send", action: "errno", errno: "ECONNRESET", repeat: 1, fd }); + s.write(Buffer.alloc(200, "h"), headWritten); + }); + + expect({ ...errors, received: received.length }).toEqual({ + headError: { code: "ECONNRESET", syscall: "write" }, + socketError: { code: "ECONNRESET", syscall: "write" }, + received: 0, + }); + }); + } + // us_socket_write_check_error gives send() errnos that are neither // would-block/transient nor known peer-gone (EPROTOTYPE: macOS returns it // racily from send() on healthy sockets) a bounded retry through the diff --git a/test/js/node/net/node-net-server.test.ts b/test/js/node/net/node-net-server.test.ts index ae1f30074051..f4bb9b48652f 100644 --- a/test/js/node/net/node-net-server.test.ts +++ b/test/js/node/net/node-net-server.test.ts @@ -1,5 +1,5 @@ -import { realpathSync } from "fs"; -import { bunEnv, bunExe, tempDir } from "harness"; +import { existsSync, realpathSync } from "fs"; +import { bunEnv, bunExe, isWindows, tempDir } from "harness"; import { AddressInfo, createServer, Server, Socket } from "net"; import { createTest } from "node-harness"; import { once } from "node:events"; @@ -577,6 +577,77 @@ describe("net.createServer events", () => { }); }); + // The 'connection' listener runs under the native open dispatch. A short send + // made there is flushed when that dispatch ends. When the peer reset the + // connection in between, that flush gets ECONNRESET/EPIPE from send() and the + // write must fail. It was reported as drained instead: the write callback + // succeeded and 'finish' fired for a response the peer never received. + // Windows keeps the legacy drain contract for fatal flushes (see on_writable). + it.skipIf(isWindows)( + "fails a write whose flush at the end of the 'connection' listener hits a peer reset", + async () => { + using dir = tempDir("net-open-flush-reset", { + "client.js": ` + const net = require("node:net"); + const fs = require("node:fs"); + const s = net.connect(Number(process.env.RESET_PORT), "127.0.0.1"); + s.on("error", () => {}); + s.once("data", () => { + // The server's first send happened and its listener is still running. + s.resetAndDestroy(); + fs.writeFileSync(process.env.RESET_MARKER, ""); + }); + `, + }); + const marker = join(String(dir), "reset"); + + let sawReset = false; + let writeFailed: boolean | undefined; + let finished = false; + const socketErrors: NodeJS.ErrnoException[] = []; + const closed = Promise.withResolvers(); + const server = createServer(c => { + c.on("error", err => socketErrors.push(err)); + c.on("finish", () => (finished = true)); + c.on("close", hadError => closed.resolve(hadError)); + // More than the socket send buffer takes: a real short send. + c.write(Buffer.alloc(16 * 1024 * 1024, "x"), err => (writeFailed = err != null)); + c.end(); + // Stay in the listener until the peer has reset the connection. + const deadline = performance.now() + 10_000; + while (!(sawReset = existsSync(marker)) && performance.now() < deadline) {} + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + + try { + await using client = Bun.spawn({ + cmd: [bunExe(), join(String(dir), "client.js")], + env: { ...bunEnv, RESET_PORT: String((server.address() as AddressInfo).port), RESET_MARKER: marker }, + stdio: ["ignore", "inherit", "inherit"], + }); + + expect({ + closeHadError: await closed.promise, + sawReset, + writeFailed, + finished, + errors: socketErrors.length, + }).toEqual({ + closeHadError: true, + sawReset: true, + writeFailed: true, + finished: false, + errors: 1, + }); + expect(["ECONNRESET", "EPIPE"]).toContain(socketErrors[0].code); + expect(await client.exited).toBe(0); + } finally { + server.close(); + } + }, + ); + it("#8374", async () => { const server = createServer(); const socketPath = join(tmpdir(), "test-unix-socket"); From 6853159b4a244d86727f0a5ce13c9b9312f65235 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 09:01:38 +0000 Subject: [PATCH 2/4] ci: retrigger From 7960eb954715dd46995adc6ddb60c83e3b2dab66 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 09:05:33 +0000 Subject: [PATCH 3/4] socket: shorten the comments on the fatal-flush path --- src/runtime/socket/socket_body.rs | 38 ++++++++++--------------------- 1 file changed, 12 insertions(+), 26 deletions(-) diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 9a32e89f7100..9ddaa73adef0 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -903,17 +903,9 @@ impl NewSocket { called } - /// `internal_flush` reported a fatal send errno under an event-loop - /// dispatch. On POSIX that signal is trustworthy: - /// us_socket_write_check_error only reports an errno that is either known - /// peer-gone or persisted across its bounded unclassified-errno retry - /// window. internal_flush already dropped the undeliverable buffer and the - /// writable poll is no longer re-armed, so the dispatch is the last place - /// the errno is visible - swallowing it acknowledged the bytes to JS, and - /// the peer saw a stream with those bytes missing. Deliver it like a failed - /// write (syscall "write", same shape as net.ts failWrite) and close the - /// socket so 'error' is followed by 'close'. The caller holds the handlers - /// scope. + /// Reports the fatal send errno that `internal_flush` returned as a failed + /// write, then closes. The buffer is already dropped, so this dispatch is + /// the only place JS can learn of it. The caller holds the handlers scope. #[cfg(not(windows))] fn fail_fatal_flush( &self, @@ -927,9 +919,8 @@ impl NewSocket { &global, ); handlers.call_error_handler(this_value, &[this_value, err_value])?; - // The error handler can destroy the socket itself; only close a - // still-attached socket. Close without detaching so on_close runs - // and JS observes 'close' (mirrors h2's dead-transport close). + // The error handler can detach the socket. Close without detaching, so + // on_close runs and JS observes 'close'. if !self.socket.get().is_detached() { self.socket.get().close(uws::CloseCode::Normal); } @@ -1633,9 +1624,8 @@ impl NewSocket { // the do_socket_write backpressure arms the normal writable // subscription. let fatal_send_errno = this.internal_flush(); - // A fatal flush also leaves the buffer empty (it drops the bytes), - // so the drain below would complete that write as delivered. - // Windows keeps the legacy contract, as in on_writable. + // A fatal flush empties the buffer too: the drain below would + // complete that write as delivered. #[cfg(not(windows))] if fatal_send_errno != 0 { return this.fail_fatal_flush(&handlers, this_value, fatal_send_errno); @@ -3001,8 +2991,7 @@ impl NewSocket { log!("writeOrEnd {}", bytes.len()); let wrote = self.write_maybe_corked(bytes); let uwrote: usize = usize::try_from(wrote.max(0)).expect("int cast"); - // `wrote < -1` is a fatal send: JS fails that write, so its bytes must - // not stay queued for a later flush to retry. + // JS fails a fatal send (`wrote < -1`): do not queue its bytes. if buffer_unwritten_data && wrote >= -1 { let remaining = &bytes[uwrote..]; if !remaining.is_empty() { @@ -3042,13 +3031,10 @@ impl NewSocket { } /// Flushes the node:net buffered tail. Returns 0, or the positive errno of - /// a fatal send error (buffer dropped, writable not re-armed). - /// On POSIX, the event-loop callers (`on_writable` and the tail of - /// `on_open`) consume the errno through `fail_fatal_flush`: it dispatches - /// the error handler and closes the socket. On Windows the errno is still - /// ignored (the drain callback is dispatched regardless) - skipping the - /// drain on fatal made Windows servers reset FIN-terminated responses (see - /// a5e7ba5905) - until the Windows fatal-write detection is verified. + /// a fatal send error (buffer dropped, writable not re-armed). On POSIX the + /// event-loop callers report it through `fail_fatal_flush`. Windows still + /// ignores it: skipping the drain on fatal made Windows servers reset + /// FIN-terminated responses (a5e7ba5905). fn internal_flush(&self) -> i32 { // A TLS socket whose handshake was rejected has no usable transport: // never push the buffered tail at it, and report no error (the From aecd9e37a5c4f469cfd914edcb95ac46ae4b9be8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 09:10:40 +0000 Subject: [PATCH 4/4] socket: keep the new comments on the fatal-flush path to one line each --- src/runtime/socket/socket_body.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/runtime/socket/socket_body.rs b/src/runtime/socket/socket_body.rs index 9ddaa73adef0..5e2dbbf2a625 100644 --- a/src/runtime/socket/socket_body.rs +++ b/src/runtime/socket/socket_body.rs @@ -903,9 +903,7 @@ impl NewSocket { called } - /// Reports the fatal send errno that `internal_flush` returned as a failed - /// write, then closes. The buffer is already dropped, so this dispatch is - /// the only place JS can learn of it. The caller holds the handlers scope. + /// Fails the write with `internal_flush`'s fatal errno, then closes. Caller holds the scope. #[cfg(not(windows))] fn fail_fatal_flush( &self, @@ -919,8 +917,7 @@ impl NewSocket { &global, ); handlers.call_error_handler(this_value, &[this_value, err_value])?; - // The error handler can detach the socket. Close without detaching, so - // on_close runs and JS observes 'close'. + // Close unless the error handler already detached; on_close then reports 'close' to JS. if !self.socket.get().is_detached() { self.socket.get().close(uws::CloseCode::Normal); } @@ -1624,8 +1621,7 @@ impl NewSocket { // the do_socket_write backpressure arms the normal writable // subscription. let fatal_send_errno = this.internal_flush(); - // A fatal flush empties the buffer too: the drain below would - // complete that write as delivered. + // A fatal flush empties the buffer too, so the drain below would report success. #[cfg(not(windows))] if fatal_send_errno != 0 { return this.fail_fatal_flush(&handlers, this_value, fatal_send_errno); @@ -3031,10 +3027,12 @@ impl NewSocket { } /// Flushes the node:net buffered tail. Returns 0, or the positive errno of - /// a fatal send error (buffer dropped, writable not re-armed). On POSIX the - /// event-loop callers report it through `fail_fatal_flush`. Windows still - /// ignores it: skipping the drain on fatal made Windows servers reset - /// FIN-terminated responses (a5e7ba5905). + /// a fatal send error (buffer dropped, writable not re-armed). + /// On POSIX, `fail_fatal_flush` consumes the errno: it dispatches the error + /// handler and closes the socket. On Windows the errno is still ignored + /// (the drain callback is dispatched regardless) - skipping the drain on + /// fatal made Windows servers reset FIN-terminated responses (see + /// a5e7ba5905) - until the Windows fatal-write detection is verified. fn internal_flush(&self) -> i32 { // A TLS socket whose handshake was rejected has no usable transport: // never push the buffered tail at it, and report no error (the