-
Notifications
You must be signed in to change notification settings - Fork 5k
sql: ignore stale on_connect firing after #onClose in pooled Postgres/MySQL #30950
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+165
−0
Closed
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| // (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, | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:spawnSync, terminate all idle backends, then query): 0/25 reproducedspawnSynccalls): 0/20 reproducedThe bug is a microtask-vs-synchronous-callback ordering race:
handleConnectedis queued as a microtask fromReadyForQuery, buthandleClosefires synchronously. It only corrupts the pool whenReadyForQueryand the socket FIN land in the same uSockets poll dispatch, sohandleCloseruns before the queuedhandleConnecteddrains. 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 onesocket.write/end, so the client receivesREADABLE | EPOLLHUPin 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.