From da5838c58d606cedc20e5339f3d4fd970072f66e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 12:43:06 +0000 Subject: [PATCH 1/4] test(proxy-stress-protocol): deflake early-reply-during-upload The origin wrote its early reply and then immediately sock.end()'d. The proxy relays that FIN and end()s the client leg while bun is still writing ~1MB of request body; if bun's on_writable/on_close fires before the reply bytes are processed it observes a shut-down socket and fails with ConnectionClosed (surfaced as ECONNRESET, errno 0). Keep the origin socket open after writing the reply; the client closes after reading Connection: close, which tears down the proxy->origin leg. Disposal now destroys any socket still open. --- .../js/bun/http/proxy-stress-protocol.test.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/test/js/bun/http/proxy-stress-protocol.test.ts b/test/js/bun/http/proxy-stress-protocol.test.ts index 588d89f3238f..c291f12cc90b 100644 --- a/test/js/bun/http/proxy-stress-protocol.test.ts +++ b/test/js/bun/http/proxy-stress-protocol.test.ts @@ -52,7 +52,10 @@ afterAll(async () => { describe("early reply during upload", () => { async function makeEarlyReplyOrigin(status: number, after: number, withTls: boolean) { + const sockets = new Set(); const handler = (sock: net.Socket) => { + sockets.add(sock); + sock.on("close", () => sockets.delete(sock)); sock.on("error", () => {}); let got = 0; let replied = false; @@ -61,7 +64,14 @@ describe("early reply during upload", () => { if (!replied && got >= after) { replied = true; const reply = `HTTP/1.1 ${status} Nope\r\nContent-Length: 5\r\nConnection: close\r\n\r\nearly`; - sock.write(reply, () => sock.end()); + // Keep the socket open after replying: the client is still + // mid-upload, and if we end here the proxy relays the FIN and + // closes the client leg while ~1MB of body is still in flight. + // bun's next on_writable then observes a shut-down socket before + // it has read this response and fails with ConnectionClosed + // (ECONNRESET). The client closes after reading Connection: close, + // which tears down the proxy→origin leg. + sock.write(reply); } }); }; @@ -71,11 +81,15 @@ describe("early reply during upload", () => { server.listen(0, "127.0.0.1"); await once(server, "listening"); const port = (server.address() as net.AddressInfo).port; + const close = () => { + server.close(); + for (const s of sockets) s.destroy(); + }; return { url: `${withTls ? "https" : "http"}://localhost:${port}`, port, - close: () => server.close(), - [Symbol.asyncDispose]: async () => server.close(), + close, + [Symbol.asyncDispose]: async () => close(), }; } From 8554a06aed7eac8778b42cace1c88056713bd804 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 29 Jul 2026 13:32:06 +0000 Subject: [PATCH 2/4] http: honor Connection: close on non-2xx responses The response Connection header was only applied when the status code was 2xx. That guard dates from when keep-alive defaulted off and the block only handled "Connection: keep-alive"; once the default flipped to keep-alive on, the guard started meaning "ignore Connection: close on 4xx/5xx", so a 413/500 with Connection: close was pooled. When the server (or a relaying proxy) then closed the socket, a concurrent fetch that picked it from the pool failed with ECONNRESET. Honor "Connection: close" for every status code (RFC 9112 section 9.6); keep the 2xx guard only for the explicit "keep-alive" case. This reverts the previous test-side workaround in proxy-stress-protocol.test.ts; the original sock.end() behavior is realistic and is now handled correctly. --- src/http/lib.rs | 27 +++++---- .../js/bun/http/proxy-stress-protocol.test.ts | 20 +------ test/js/web/fetch/fetch-keepalive.test.ts | 56 +++++++++++++++++++ 3 files changed, 75 insertions(+), 28 deletions(-) diff --git a/src/http/lib.rs b/src/http/lib.rs index 9f813f795f8c..6b29d6500485 100644 --- a/src/http/lib.rs +++ b/src/http/lib.rs @@ -4898,19 +4898,24 @@ impl<'a> HTTPClient<'a> { location = header.value(); } h if h == hash_header_const(b"Connection") => { - if response.status_code >= 200 && response.status_code <= 299 { - // HTTP headers are case-insensitive (RFC 7230) - if bun_core::strings::eql_case_insensitive_ascii_check_length( - header.value(), - b"close", - ) { - self.state.flags.allow_keepalive = false; - } else if bun_core::strings::eql_case_insensitive_ascii_check_length( + // RFC 9112 §9.6: `Connection: close` means the sender will + // close after this response; status code is irrelevant. The + // old 2xx-only guard dates from when keep-alive defaulted + // off and the block only handled `keep-alive`; with the + // default now on, gating `close` on 2xx pools a socket the + // server (or relaying proxy) is closing after a 4xx/5xx. + if bun_core::strings::eql_case_insensitive_ascii_check_length( + header.value(), + b"close", + ) { + self.state.flags.allow_keepalive = false; + } else if (200..=299).contains(&response.status_code) + && bun_core::strings::eql_case_insensitive_ascii_check_length( header.value(), b"keep-alive", - ) { - self.state.flags.allow_keepalive = true; - } + ) + { + self.state.flags.allow_keepalive = true; } } h if h == hash_header_const(b"Last-Modified") => { diff --git a/test/js/bun/http/proxy-stress-protocol.test.ts b/test/js/bun/http/proxy-stress-protocol.test.ts index c291f12cc90b..588d89f3238f 100644 --- a/test/js/bun/http/proxy-stress-protocol.test.ts +++ b/test/js/bun/http/proxy-stress-protocol.test.ts @@ -52,10 +52,7 @@ afterAll(async () => { describe("early reply during upload", () => { async function makeEarlyReplyOrigin(status: number, after: number, withTls: boolean) { - const sockets = new Set(); const handler = (sock: net.Socket) => { - sockets.add(sock); - sock.on("close", () => sockets.delete(sock)); sock.on("error", () => {}); let got = 0; let replied = false; @@ -64,14 +61,7 @@ describe("early reply during upload", () => { if (!replied && got >= after) { replied = true; const reply = `HTTP/1.1 ${status} Nope\r\nContent-Length: 5\r\nConnection: close\r\n\r\nearly`; - // Keep the socket open after replying: the client is still - // mid-upload, and if we end here the proxy relays the FIN and - // closes the client leg while ~1MB of body is still in flight. - // bun's next on_writable then observes a shut-down socket before - // it has read this response and fails with ConnectionClosed - // (ECONNRESET). The client closes after reading Connection: close, - // which tears down the proxy→origin leg. - sock.write(reply); + sock.write(reply, () => sock.end()); } }); }; @@ -81,15 +71,11 @@ describe("early reply during upload", () => { server.listen(0, "127.0.0.1"); await once(server, "listening"); const port = (server.address() as net.AddressInfo).port; - const close = () => { - server.close(); - for (const s of sockets) s.destroy(); - }; return { url: `${withTls ? "https" : "http"}://localhost:${port}`, port, - close, - [Symbol.asyncDispose]: async () => close(), + close: () => server.close(), + [Symbol.asyncDispose]: async () => server.close(), }; } diff --git a/test/js/web/fetch/fetch-keepalive.test.ts b/test/js/web/fetch/fetch-keepalive.test.ts index d949b21df8de..c3948cf522a0 100644 --- a/test/js/web/fetch/fetch-keepalive.test.ts +++ b/test/js/web/fetch/fetch-keepalive.test.ts @@ -73,6 +73,62 @@ test("fetch does not reuse a pooled TLS connection for a request with a differen expect(plain).not.toBe(overrideA); }); +// RFC 9112 §9.6: a server's `Connection: close` applies regardless of status +// code. Previously bun only honored it for 2xx, so a 4xx/5xx with +// `Connection: close` was pooled; a concurrent fetch that picked the pooled +// socket before the server's FIN landed failed with ECONNRESET. Subprocess +// so the pool can't leak into other tests. The server here keeps the socket +// open and answers every request on it, so the connection count is exactly +// how many times bun dialed (pooled reuse => 1, correct => 4). +test.each([200, 400, 413, 500])( + "a %d response with Connection: close is not pooled", + async status => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + import net from "node:net"; + let connections = 0; + const server = net.createServer(sock => { + connections++; + sock.on("error", () => {}); + let buf = ""; + sock.on("data", d => { + buf += d.toString("latin1"); + while (buf.includes("\\r\\n\\r\\n")) { + buf = buf.slice(buf.indexOf("\\r\\n\\r\\n") + 4); + sock.write("HTTP/1.1 ${status} X\\r\\nContent-Length: 2\\r\\nConnection: close\\r\\n\\r\\nok"); + } + }); + }); + server.listen(0, "127.0.0.1"); + await new Promise(r => server.on("listening", r)); + const url = "http://127.0.0.1:" + server.address().port + "/"; + const statuses = []; + for (let i = 0; i < 4; i++) { + const res = await fetch(url, { keepalive: true }); + statuses.push(res.status); + await res.text(); + } + console.log(JSON.stringify({ statuses, connections })); + process.exit(0); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const result = stdout.startsWith("{") ? JSON.parse(stdout.trim()) : { stdout, stderr }; + expect({ result, exitCode }).toEqual({ + result: { statuses: [status, status, status, status], connections: 4 }, + exitCode: 0, + }); + }, +); + // A reused keep-alive connection reset during a streaming PUT must reject with // ECONNRESET, not retry: the stream body is already consumed, and the retry // panicked in send_initial_request_payload. Subprocess: the panic aborts the process. From b28d9a9f84351049b9b4d8f562abb706a627fd1f Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 29 Jul 2026 13:34:20 +0000 Subject: [PATCH 3/4] [autofix.ci] apply automated fixes --- test/js/web/fetch/fetch-keepalive.test.ts | 39 +++++++++++------------ 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/test/js/web/fetch/fetch-keepalive.test.ts b/test/js/web/fetch/fetch-keepalive.test.ts index c3948cf522a0..afcf2efa55e0 100644 --- a/test/js/web/fetch/fetch-keepalive.test.ts +++ b/test/js/web/fetch/fetch-keepalive.test.ts @@ -80,14 +80,12 @@ test("fetch does not reuse a pooled TLS connection for a request with a differen // so the pool can't leak into other tests. The server here keeps the socket // open and answers every request on it, so the connection count is exactly // how many times bun dialed (pooled reuse => 1, correct => 4). -test.each([200, 400, 413, 500])( - "a %d response with Connection: close is not pooled", - async status => { - await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - ` +test.each([200, 400, 413, 500])("a %d response with Connection: close is not pooled", async status => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` import net from "node:net"; let connections = 0; const server = net.createServer(sock => { @@ -114,20 +112,19 @@ test.each([200, 400, 413, 500])( console.log(JSON.stringify({ statuses, connections })); process.exit(0); `, - ], - env: bunEnv, - stdout: "pipe", - stderr: "pipe", - }); + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const result = stdout.startsWith("{") ? JSON.parse(stdout.trim()) : { stdout, stderr }; - expect({ result, exitCode }).toEqual({ - result: { statuses: [status, status, status, status], connections: 4 }, - exitCode: 0, - }); - }, -); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const result = stdout.startsWith("{") ? JSON.parse(stdout.trim()) : { stdout, stderr }; + expect({ result, exitCode }).toEqual({ + result: { statuses: [status, status, status, status], connections: 4 }, + exitCode: 0, + }); +}); // A reused keep-alive connection reset during a streaming PUT must reject with // ECONNRESET, not retry: the stream body is already consumed, and the retry From a47c6c94e7b1108886b60fd8341ba79ed224e807 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 29 Jul 2026 13:40:38 +0000 Subject: [PATCH 4/4] address review: trim comment, test.concurrent.each --- src/http/lib.rs | 8 ++------ test/js/web/fetch/fetch-keepalive.test.ts | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/http/lib.rs b/src/http/lib.rs index 6b29d6500485..91849102ddbf 100644 --- a/src/http/lib.rs +++ b/src/http/lib.rs @@ -4898,12 +4898,8 @@ impl<'a> HTTPClient<'a> { location = header.value(); } h if h == hash_header_const(b"Connection") => { - // RFC 9112 §9.6: `Connection: close` means the sender will - // close after this response; status code is irrelevant. The - // old 2xx-only guard dates from when keep-alive defaulted - // off and the block only handled `keep-alive`; with the - // default now on, gating `close` on 2xx pools a socket the - // server (or relaying proxy) is closing after a 4xx/5xx. + // `close` applies on any status (RFC 9112 §9.6); only an + // explicit `keep-alive` is gated on a 2xx success. if bun_core::strings::eql_case_insensitive_ascii_check_length( header.value(), b"close", diff --git a/test/js/web/fetch/fetch-keepalive.test.ts b/test/js/web/fetch/fetch-keepalive.test.ts index afcf2efa55e0..83440ef8563e 100644 --- a/test/js/web/fetch/fetch-keepalive.test.ts +++ b/test/js/web/fetch/fetch-keepalive.test.ts @@ -80,7 +80,7 @@ test("fetch does not reuse a pooled TLS connection for a request with a differen // so the pool can't leak into other tests. The server here keeps the socket // open and answers every request on it, so the connection count is exactly // how many times bun dialed (pooled reuse => 1, correct => 4). -test.each([200, 400, 413, 500])("a %d response with Connection: close is not pooled", async status => { +test.concurrent.each([200, 400, 413, 500])("a %d response with Connection: close is not pooled", async status => { await using proc = Bun.spawn({ cmd: [ bunExe(),