Repository navigation
Description
A query that throws while it is built or serialized (too many parameters, a value that fails to serialize, a throwing debug callback) is handled as if it failed on the server. When another query is already running on the connection, the wrong query gets the error and later queries receive each other's responses. This is porsager#1082 and porsager#729, and it returns wrong results, not only a hang.
Reproduction
PostgreSQL 17, main at 032ea2b:
const sql = postgres({ ...opts, max: 1 })
await sql`select 1`
const a = sql`select pg_sleep(0.2) as a`.execute()
const b = sql.unsafe('select 1', Array(70000).fill(1)).execute()
await new Promise(r => setTimeout(r, 500))
const c = sql`select 2 as c`.execute()arejects withMAX_PARAMETERS_EXCEEDED, which isb's error.bhangs. It was never written to the server.cresolves with[]instead of[{ c: 2 }], because it received the response meant for another query. Only then doesbfail, withERR_OUT_OF_RANGE.
Cause
submit() in src/connection.js registers the query as active (query) or pipelined (sent) before build() and toBuffer() run. When either throws, the catch:
- calls
errored(error), which rejects the active query rather than the one that failed; - writes a
Synconly when nothing is pipelined, so a failing query insenthas no messages on the wire, yet it still waits for a response. Every later response is then matched to the query before it.
On an idle connection, the same path happens to work: the failing query is the active one, and the Sync gives it the ReadyForQuery it waits for.
Fix
Keep the failing query as a placeholder in the pipeline, always write a Sync for it, and reject that query, not the active one. Each placeholder then consumes exactly one ReadyForQuery, so responses stay matched in order. The placeholder also returns an idle connection to the pool, as it does today.
Tests
- The reproduction above:
aandcget their own results, andbrejects withMAX_PARAMETERS_EXCEEDED. - A failing query in the middle of several pipelined queries.
- A
debugcallback that throws once: that query rejects with the callback's error, and the next query on the same connection succeeds. This is thedebugrow of [FIXED in 4.4.0] A throwing user callback breaks connection state #13. [FIXED in 4.4.0] A throwing user callback breaks connection state #13's microtask rethrow is still needed for the other callbacks. sql.stats()back to idle after the failure.
First item in the correctness batch on #5, independent of #18.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsShipped
Activity
chore: release 4.3.0
[-]A query that fails to serialize gets another query's error and response[/-][+][FIXED in 4.3.0] A query that fails to serialize gets another query's error and response[/+]