Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/js/internal/sql/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,19 @@ abstract class BasePooledConnection<ConnectionHandle extends { close(): void; fl
}

protected handleConnected(err: any) {
// The native connection queues this callback as a microtask when the
// handshake completes (e.g. Postgres ReadyForQuery). If the socket is
// closed in the same I/O tick (the server's FIN rides the same read
// buffer, or the pool closes mid-handshake), handleClose runs
// synchronously first and transitions us to `closed`. When this
// microtask then fires, honoring it would resurrect a dead connection
// into readyConnections with `this.connection === null`, which
// dispatches null to the native query's run() and wedges the pool
// permanently (it never retries a slot it thinks is live). Only a slot
// still `pending` is legitimately waiting for this callback.
if (this.state !== PooledConnectionState.pending) {
return;
}
if (err) {
err = this.wrapError(err);
}
Expand Down
152 changes: 152 additions & 0 deletions test/js/sql/postgres-close-during-handshake.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Regression test for https://github.com/oven-sh/bun/issues/30947
//
// Bun.SQL's pool would be permanently corrupted when all pool connections were
// closed server-side (e.g. by a connection pooler's idle reaper or
// `pg_terminate_backend`) while the event loop was blocked. The underlying
// PostgresSQLConnection queues its on_connect callback as a microtask when the
// server's ReadyForQuery arrives; if the socket is closed in the same I/O tick,
// `handleClose` runs synchronously first and transitions the pooled connection
// to `closed`. The pending `handleConnected` microtask then fires and, without
// the guard in `BasePooledConnection.handleConnected`
// (src/js/internal/sql/shared.ts), unconditionally overwrites state to
// `connected` and re-adds the dead connection (with `this.connection ===
// null`) to `readyConnections`. Subsequent queries dispatch `null` to Rust's
// PostgresSQLQuery.run, which throws "connection must be a
// PostgresSQLConnection" — and the pool never recovers because it thinks the
// ghost entry is still live.

import { expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";

// A fake postgres server that sends the full trust-mode handshake response

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we not use a real postgres instance? Both CI and @robobun your container have live running postgres instances. Check other tests to see how testing against real postgres works.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried real Postgres first and went with the fake server because the regression only reproduces under release-speed timing — a debug/ASAN build (what the merge gate and the asan CI lanes run) never hits it.

Measured just now against a debug build with the fix removed, using a real local Postgres + pg_terminate_backend:

  • the issue's exact repro (block the loop via spawnSync, terminate all idle backends, then query): 0/25 reproduced
  • an aggressive variant (max: 30, kill all backends mid-handshake across 3 batched spawnSync calls): 0/20 reproduced
  • the fake-server test in this file, same debug build, fix removed: fails every run

The bug is a microtask-vs-synchronous-callback ordering race: handleConnected is queued as a microtask from ReadyForQuery, but handleClose fires synchronously. It only corrupts the pool when ReadyForQuery and the socket FIN land in the same uSockets poll dispatch, so handleClose runs before the queued handleConnected drains. Real Postgres only produces that window at release speed (the original reporter saw ~30% there); in a debug build the connect microtask always drains before the close is processed, so the bug can't fire — a real-pg test would pass with or without the fix and catch nothing.

The fake server writes the full handshake + admin-shutdown ErrorResponse + FIN in one socket.write/end, so the client receives READABLE | EPOLLHUP in a single poll and the race is deterministic on every lane including debug/ASAN. There's already precedent for a hand-rolled PG wire-protocol server in this dir: test/js/sql/postgres-multi-statement-fields.test.ts.

Happy to also add a docker-gated real-pg smoke test if you'd like the end-to-end path exercised, but it can't be the regression guard — it won't fire in the gate's debug build and would be flaky (~30%) on the release lanes. Let me know if you'd still prefer I switch this one over.

// (AuthenticationOk + many ParameterStatus messages + BackendKeyData +
// ReadyForQuery + an admin-shutdown ErrorResponse) and immediately closes the
// socket. The ParameterStatus stack matches what a real server sends on
// startup so uSockets' recv delivers the whole handshake plus the FIN in one
// poll dispatch; that is what makes on_close land in the same I/O tick as
// ReadyForQuery and fire `handleClose` before the queued `handleConnected`
// microtask drains.
const FIXTURE = /* js */ `
const net = require("node:net");
const { SQL } = require("bun");

function pkt(type, body) {
const h = Buffer.alloc(5);
h.write(type, 0);
h.writeInt32BE(body.length + 4, 1);
return Buffer.concat([h, body]);
}
function int32(n) {
const b = Buffer.alloc(4);
b.writeInt32BE(n, 0);
return b;
}
function cstr(s) {
return Buffer.concat([Buffer.from(s), Buffer.from([0])]);
}
function paramStatus(k, v) {
return pkt("S", Buffer.concat([cstr(k), cstr(v)]));
}

const handshakeResponse = Buffer.concat([
pkt("R", int32(0)), // AuthenticationOk
paramStatus("application_name", ""),
paramStatus("client_encoding", "UTF8"),
paramStatus("server_encoding", "UTF8"),
paramStatus("server_version", "17.0"),
paramStatus("session_authorization", "test"),
paramStatus("standard_conforming_strings", "on"),
paramStatus("TimeZone", "UTC"),
paramStatus("integer_datetimes", "on"),
paramStatus("IntervalStyle", "postgres"),
paramStatus("is_superuser", "off"),
pkt("K", Buffer.concat([int32(12345), int32(67890)])), // BackendKeyData
pkt("Z", Buffer.from("I")), // ReadyForQuery
]);
const adminShutdown = pkt("E", Buffer.concat([
cstr("SERROR"),
cstr("C57P01"),
cstr("Mterminating connection due to administrator command"),
Buffer.from([0]),
]));

const server = net.createServer(socket => {
let handshook = false;
socket.setNoDelay(true);
socket.on("data", () => {
if (handshook) return;
handshook = true;
// Full handshake + admin-shutdown error + FIN — the same close pattern
// pg_terminate_backend produces.
socket.write(handshakeResponse);
socket.write(adminShutdown);
socket.end();
});
socket.on("error", () => {});
});

await new Promise(r => server.listen(0, "127.0.0.1", r));
const port = server.address().port;

const sql = new SQL({
url: \`postgres://u@127.0.0.1:\${port}/db\`,
max: 10,
connectionTimeout: 2,
});

// A broken pool throws "connection must be a PostgresSQLConnection" on every
// subsequent query once a ghost entry has leaked into readyConnections. A
// healthy pool just keeps seeing "Connection closed" (or the admin-shutdown
// error) because our fake server kicks every connection. A handful of
// iterations is enough to trigger the race reliably; bail out on the first
// occurrence so we don't hang against a corrupted pool.
let corrupted = false;
let iterations = 0;
for (let i = 0; i < 20; i++) {
iterations = i + 1;
try {
await sql\`SELECT 1\`;
} catch (err) {
if (/connection must be a PostgresSQLConnection/i.test(err && err.message)) {
corrupted = true;
break;
}
}
}

console.log(JSON.stringify({ corrupted, iterations }));
// A corrupted pool can refuse to close cleanly (sql.close() spins trying to
// flush ghost entries), so just exit immediately — the subprocess dying is
// the tear-down signal for the fake server.
process.exit(0);
`;

test("pool recovers after every connection is closed mid-handshake", async () => {
using dir = tempDir("pg-close-mid-handshake", {
"fixture.js": FIXTURE,
});

await using proc = Bun.spawn({
cmd: [bunExe(), "fixture.js"],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

// Fixture prints a single JSON line on stdout. `corrupted: true` means the
// pool produced the internal "connection must be a PostgresSQLConnection"
// error at least once — always a bug, never expected fallout from the test
// scenario (the fake server just closes every connection).
// Fold stderr into the assertion so a fixture crash surfaces in the diff
// instead of leaving CI with an opaque `corrupted: undefined`.
const line = stdout.trim().split("\n").at(-1) ?? "";
const parsed = line ? JSON.parse(line) : {};
expect({ stderr, corrupted: parsed.corrupted, exitCode }).toEqual({
stderr: "",
corrupted: false,
exitCode: 0,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
});
Loading