From 21d43c89bf499e367123e359ae73465b8f4693dc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 02:36:21 +0000 Subject: [PATCH 1/6] node:http: release the request body ref when upgrade() hands the socket to a WebSocket An Upgrade request that declares a body makes NodeHTTPResponse take body_read_ref, which keeps the event loop alive until the body arrives. upgrade() moves the socket to the WebSocket context. uWS frees the HTTP response data there, so the body callback can never run. upgrade() released poll_ref but kept body_read_ref. For an upgrade inside the 'upgrade' event, the dispatch tail then marks the request complete. The socket close path returns early for a completed request, so nothing released the ref. With every socket and server closed the event loop stayed alive with nothing to wait for and spun at 100% CPU. A debug build failed `assertion failed: !self.body_read_ref.get().has` when the GC finalized the response. upgrade() now releases body_read_ref for a body that is still pending and moves body_read_state to Done, next to the poll_ref release. A reader of the request that starts after the upgrade gets 'end' on every path. Before, it got 'end' or waited forever, depending on when it started. --- src/runtime/server/NodeHTTPResponse.rs | 8 ++ test/js/node/http/node-http-with-ws.test.ts | 99 +++++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index 15977391c7e4..7b38abb894be 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -593,6 +593,14 @@ impl NodeHTTPResponse { // and will have its own lifecycle management let vm = self.server.global_this().bun_vm().as_mut(); self.poll_ref.with_mut(|r| r.unref(vm)); + // uWS frees the HTTP response data, and its body callback, when it + // adopts the socket: a pending body never arrives, so nothing later + // releases its ref. A ref that is held while the body is `Done` is + // inside the last `ondata` call, and `on_data_or_aborted` releases it. + if self.body_read_state.get() == BodyReadState::Pending { + self.body_read_ref.with_mut(|r| r.unref(vm)); + self.body_read_state.set(BodyReadState::Done); + } // S008: `WebSocketUpgradeContext` is an `opaque_ffi!` ZST — safe deref // (`upgrade_ctx` checked non-null above). let ctx = bun_opaque::opaque_deref_mut(upgrade_ctx); diff --git a/test/js/node/http/node-http-with-ws.test.ts b/test/js/node/http/node-http-with-ws.test.ts index 0ab97a4b1d26..85c94a01d41e 100644 --- a/test/js/node/http/node-http-with-ws.test.ts +++ b/test/js/node/http/node-http-with-ws.test.ts @@ -162,3 +162,102 @@ describe.concurrent("request handlers run to completion before the callbacks the expect(order).toEqual(["rest of handler", "nextTick", "microtask"]); }); }); + +// An Upgrade request can declare a body. The upgrade hands the socket to the WebSocket, so a body +// that has not arrived never does, and a keep-alive ref that waits for it never lets the process exit. +// Not concurrent: a debug build needs most of the default timeout to start this child, and more beside another. +test("WebSocket upgrade should unref body_read_ref from response", async () => { + const script = /* js */ ` + const http = require("http"); + const net = require("net"); + const { once } = require("events"); + const { WebSocketServer } = require("ws"); + const { getEventLoopStats } = require("bun:internal-for-testing"); + + async function upgradeRequestThatDeclaresABody(upgradeInLaterTask, sendBody) { + const tasksBefore = getEventLoopStats().activeTasks; + let requestEnded = false; + // A request that is not taken for an upgrade gets an answer too, so the client never waits. + const server = http.createServer((req, res) => res.writeHead(426).end()); + const wsServer = new WebSocketServer({ noServer: true }); + server.on("upgrade", (req, socket, head) => { + const upgrade = () => { + wsServer.handleUpgrade(req, socket, head, () => {}); + req.on("end", () => (requestEnded = true)).resume(); + }; + if (upgradeInLaterTask) setImmediate(upgrade); + else upgrade(); + }); + await once(server.listen(0, "127.0.0.1"), "listening"); + + const body = '{"hello":"world"}'; + const client = net.connect(server.address().port, "127.0.0.1"); + client.write( + [ + "GET / HTTP/1.1", + "Host: localhost", + "Connection: Upgrade", + "Upgrade: websocket", + "Sec-WebSocket-Version: 13", + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==", + "Content-Length: " + body.length, + "", + sendBody ? body : "", + ].join("\\r\\n"), + ); + const { promise, resolve, reject } = Promise.withResolvers(); + let received = ""; + client.on("data", chunk => { + received += chunk; + if (!received.includes("\\r\\n\\r\\n")) return; + // The response is in, so the upgrade and the callbacks it queued are over. + const leakedTasks = getEventLoopStats().activeTasks - tasksBefore; + resolve({ status: received.split("\\r\\n")[0], leakedTasks, requestEnded }); + }); + client.on("error", reject); + client.on("close", () => reject(new Error("closed before the response: " + JSON.stringify(received)))); + const result = await promise; + + client.destroy(); + wsServer.close(); + await once(server.close(), "close"); + return result; + } + + const results = { + "in a later task, body not sent": await upgradeRequestThatDeclaresABody(true, false), + "in the 'upgrade' event, body sent": await upgradeRequestThatDeclaresABody(false, true), + "in the 'upgrade' event, body not sent": await upgradeRequestThatDeclaresABody(false, false), + }; + console.log(JSON.stringify(results)); + // A leaked task keeps the event loop alive forever. Exit, so that the test fails fast. + if (Object.values(results).some(result => result.leakedTasks !== 0)) process.exit(1); + `; + + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + const upgraded = { status: "HTTP/1.1 101 Switching Protocols", leakedTasks: 0, requestEnded: true }; + expect({ + results: stdout.startsWith("{") ? JSON.parse(stdout) : stdout, + stderr, + exitCode, + signalCode: proc.signalCode, + }).toEqual({ + results: { + "in a later task, body not sent": upgraded, + "in the 'upgrade' event, body sent": upgraded, + "in the 'upgrade' event, body not sent": upgraded, + }, + stderr: "", + // The script calls process.exit() only for a leak: the process has to exit by itself. + exitCode: 0, + signalCode: null, + }); +}); From 6be58fb21ee725d40a84d31938f752fe8dc8101b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 10:05:23 +0000 Subject: [PATCH 2/6] test: cover a later-task upgrade after the request body arrived The body is complete before upgrade() runs, so body_read_state is not Pending and upgrade() has nothing to release. This case passes without the fix. It guards the other side of the new condition. --- test/js/node/http/node-http-with-ws.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/js/node/http/node-http-with-ws.test.ts b/test/js/node/http/node-http-with-ws.test.ts index 85c94a01d41e..bd16e984b7da 100644 --- a/test/js/node/http/node-http-with-ws.test.ts +++ b/test/js/node/http/node-http-with-ws.test.ts @@ -226,6 +226,8 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { const results = { "in a later task, body not sent": await upgradeRequestThatDeclaresABody(true, false), + // The body is complete before the upgrade: there is nothing left for the upgrade to release. + "in a later task, body sent": await upgradeRequestThatDeclaresABody(true, true), "in the 'upgrade' event, body sent": await upgradeRequestThatDeclaresABody(false, true), "in the 'upgrade' event, body not sent": await upgradeRequestThatDeclaresABody(false, false), }; @@ -252,6 +254,7 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { }).toEqual({ results: { "in a later task, body not sent": upgraded, + "in a later task, body sent": upgraded, "in the 'upgrade' event, body sent": upgraded, "in the 'upgrade' event, body not sent": upgraded, }, From 51453793bcd92f703a9f53a7b5f27f4580804433 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 10:33:16 +0000 Subject: [PATCH 3/6] node:http: shorten the comment on the body ref release in upgrade() --- src/runtime/server/NodeHTTPResponse.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index 7b38abb894be..e4e0679a0625 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -593,10 +593,8 @@ impl NodeHTTPResponse { // and will have its own lifecycle management let vm = self.server.global_this().bun_vm().as_mut(); self.poll_ref.with_mut(|r| r.unref(vm)); - // uWS frees the HTTP response data, and its body callback, when it - // adopts the socket: a pending body never arrives, so nothing later - // releases its ref. A ref that is held while the body is `Done` is - // inside the last `ondata` call, and `on_data_or_aborted` releases it. + // uWS drops the HTTP body callback when it adopts the socket, so a + // body that is still pending never arrives. if self.body_read_state.get() == BodyReadState::Pending { self.body_read_ref.with_mut(|r| r.unref(vm)); self.body_read_state.set(BodyReadState::Done); From 3d52ded85bb0cb80a153425bcf01ad52d895af2c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 10:42:17 +0000 Subject: [PATCH 4/6] node:http: make the comment on the body ref release one line --- src/runtime/server/NodeHTTPResponse.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index e4e0679a0625..21e6bf513c68 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -593,8 +593,7 @@ impl NodeHTTPResponse { // and will have its own lifecycle management let vm = self.server.global_this().bun_vm().as_mut(); self.poll_ref.with_mut(|r| r.unref(vm)); - // uWS drops the HTTP body callback when it adopts the socket, so a - // body that is still pending never arrives. + // Once uWS adopts the socket, a body that is still pending never arrives. if self.body_read_state.get() == BodyReadState::Pending { self.body_read_ref.with_mut(|r| r.unref(vm)); self.body_read_state.set(BodyReadState::Done); From a0ca944648236d3c575d323220c2f06abc6635f0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 11:06:18 +0000 Subject: [PATCH 5/6] ci: retrigger From 6fe97086e8328797d874eebe22c347eedecb5c57 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 20:32:07 +0000 Subject: [PATCH 6/6] node:http: keep the request open when upgrade() releases the body ref On Node v26.3.0 a request whose declared body never arrives stays open after ws.handleUpgrade(): req.complete is false and req does not end. upgrade() moved body_read_state to Done, so a reader of the request that started after the upgrade got 'end' with req.complete === true. upgrade() now only releases body_read_ref. body_read_state stays Pending, as on main, and the request stays open. The test asserts that for the cases where the body is not sent. --- src/runtime/server/NodeHTTPResponse.rs | 3 +-- test/js/node/http/node-http-with-ws.test.ts | 14 +++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index 21e6bf513c68..e15c36b4abd5 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -596,7 +596,6 @@ impl NodeHTTPResponse { // Once uWS adopts the socket, a body that is still pending never arrives. if self.body_read_state.get() == BodyReadState::Pending { self.body_read_ref.with_mut(|r| r.unref(vm)); - self.body_read_state.set(BodyReadState::Done); } // S008: `WebSocketUpgradeContext` is an `opaque_ffi!` ZST — safe deref // (`upgrade_ctx` checked non-null above). @@ -2289,7 +2288,7 @@ impl NodeHTTPResponse { self.update_flags(|f| f.remove(Flags::IS_DATA_BUFFERED_DURING_PAUSE)); // Every site that unrefs `body_read_ref` also transitions `body_read_state` out of `.pending` - // or sets `is_data_buffered_during_pause_last`, both of which are rejected by the guard above. + // or sets `is_data_buffered_during_pause_last` or `upgraded`, all of which are rejected by the guard above. // So reaching here, `body_read_ref` is still held from create(). Do not re-acquire it or // `this.ref()` — there would be no balancing release (PR #18564 removed the paired derefs). debug_assert!(self.body_read_ref.get().has); diff --git a/test/js/node/http/node-http-with-ws.test.ts b/test/js/node/http/node-http-with-ws.test.ts index bd16e984b7da..691435642078 100644 --- a/test/js/node/http/node-http-with-ws.test.ts +++ b/test/js/node/http/node-http-with-ws.test.ts @@ -176,6 +176,7 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { async function upgradeRequestThatDeclaresABody(upgradeInLaterTask, sendBody) { const tasksBefore = getEventLoopStats().activeTasks; + let request; let requestEnded = false; // A request that is not taken for an upgrade gets an answer too, so the client never waits. const server = http.createServer((req, res) => res.writeHead(426).end()); @@ -183,7 +184,7 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { server.on("upgrade", (req, socket, head) => { const upgrade = () => { wsServer.handleUpgrade(req, socket, head, () => {}); - req.on("end", () => (requestEnded = true)).resume(); + request = req.on("end", () => (requestEnded = true)).resume(); }; if (upgradeInLaterTask) setImmediate(upgrade); else upgrade(); @@ -212,7 +213,10 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { if (!received.includes("\\r\\n\\r\\n")) return; // The response is in, so the upgrade and the callbacks it queued are over. const leakedTasks = getEventLoopStats().activeTasks - tasksBefore; - resolve({ status: received.split("\\r\\n")[0], leakedTasks, requestEnded }); + const observed = { status: received.split("\\r\\n")[0], leakedTasks }; + // As in Node, a request whose body never arrives stays open. The upgrade does not end it. + if (!sendBody) observed.requestOpen = !requestEnded && !request.complete; + resolve(observed); }); client.on("error", reject); client.on("close", () => reject(new Error("closed before the response: " + JSON.stringify(received)))); @@ -245,7 +249,7 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const upgraded = { status: "HTTP/1.1 101 Switching Protocols", leakedTasks: 0, requestEnded: true }; + const upgraded = { status: "HTTP/1.1 101 Switching Protocols", leakedTasks: 0 }; expect({ results: stdout.startsWith("{") ? JSON.parse(stdout) : stdout, stderr, @@ -253,10 +257,10 @@ test("WebSocket upgrade should unref body_read_ref from response", async () => { signalCode: proc.signalCode, }).toEqual({ results: { - "in a later task, body not sent": upgraded, + "in a later task, body not sent": { ...upgraded, requestOpen: true }, "in a later task, body sent": upgraded, "in the 'upgrade' event, body sent": upgraded, - "in the 'upgrade' event, body not sent": upgraded, + "in the 'upgrade' event, body not sent": { ...upgraded, requestOpen: true }, }, stderr: "", // The script calls process.exit() only for a leak: the process has to exit by itself.