Stale FATAL error from a terminated backend rejects the first query after reconnect (3.4.9)
Summary
If a backend is terminated (for example pg_terminate_backend() → 57P01, or a server restart) while a query is in flight, the in-flight query is correctly rejected with CONNECTION_CLOSED. But the next query on the same Connection object, which runs on a brand-new socket after reconnect, is rejected with the old 57P01 error. That query never reaches the server.
Reproduced on 3.4.9 (latest) with PostgreSQL 18.6 and Node 24: 10 out of 10 attempts.
Reproduction
import postgres from 'postgres'
const url = process.env.DATABASE_URL
const admin = postgres(url, { max: 1 })
const sql = postgres(url, { max: 1 })
await sql`select 1`
const [{ pid }] = await sql`select pg_backend_pid() as pid`
const inflight = sql`select pg_sleep(5)`.catch(e => e.code)
await new Promise(r => setTimeout(r, 100)) // query is on the wire
await admin`select pg_terminate_backend(${ pid })`
console.log('in-flight:', await inflight) // CONNECTION_CLOSED (expected)
console.log('next:', await sql`select 1 as x`.then(() => 'ok', e => e.code))
// 57P01 (expected: ok)
await sql.end(); await admin.end()The PostgreSQL log (with log_connections/log_statement=all) shows that the new backend for the "next" query connects and later disconnects cleanly without receiving a single statement.
Cause
src/connection.js:
- When the FATAL
ErrorResponsearrives whilequeryis set, it is parked inerrorResponseuntilReadyForQuery, which never comes because the backend is gone. closed()rejects the in-flight query viaerror(CONNECTION_CLOSED), but it does not reseterrorResponse,queryorresults.- After reconnect, the first
ReadyForQueryof the new socket (the one that ends startup) takes theelse if (errorResponse) errored(errorResponse)branch (or theif (query)branch with the stale query).errored()then rejectsinitial, the query that triggered the reconnect, with the stale57P01, before it is ever sent.
The same state leaks in cjs/src and cf/src.
Proposed fix
Response state belongs to one socket, so reset it in closed() after the in-flight query has been rejected:
async function closed(hadError) {
...
socket.removeAllListeners()
socket = null
- if (initial)
- return reconnect()
-
- !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
+ const reconnecting = !!initial
+ !reconnecting && !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
+
+ // Response state belongs to the socket that just closed.
+ query = results = errorResponse = null
+ result = new Result()
+
+ if (reconnecting)
+ return reconnect()
+
closedTime = performance.now()With this change the reproduction above prints next: ok in 10 out of 10 runs. A regression test is straightforward: terminate the backend of an in-flight pg_sleep and assert that the next query on a max: 1 pool succeeds.
Impact
After any backend loss during a query (restart, failover, admin kill, idle_in_transaction_session_timeout FATAL racing a query), the first query on the reconnected connection fails spuriously. In transactional code that runs as BEGIN failing "before the callback", which looks like an unrelated error.
Related
Possibly the same root cause as #1223 (state from the killed socket is replayed after reconnect), but triggered by an ordinary in-flight query rather than fetch_types during startup.
Source: porsager/postgres