Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres): answer a statement that fails to build in its place in the pipeline (porsager/postgres#1236), so a transaction it was part of aborts instead of committing without it
garrytanef017353c452
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 006170197b..d61e29f6bb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,13 +12,13 @@ identifiers and attribution are available in the pre-removal Git revision## [0.60.150.0] - 2026-10-10-**On Postgres, one statement with an `undefined` parameter could wedge a pooled connection for good: the statement in flight ahead of it got its error, it stayed queued with nothing on the wire, every later reply arrived one statement late, and the backend sat `active / ClientRead` while `/health` answered 200 (#6383, the driver desync behind #6352). The vendored driver now builds a statement before it joins the queue, so only the culprit fails; a connection whose statement waits past `statement_timeout` plus 30 s with nothing coming back is retired and replaced; the pool numbers are live; and `/health?deep=1` probes through the same pool the handlers use.**+**On Postgres, one statement with an `undefined` parameter could wedge a pooled connection for good: the statement in flight ahead of it got its error, it stayed queued with nothing on the wire, every later reply arrived one statement late, and the backend sat `active / ClientRead` while `/health` answered 200 (#6383, the driver desync behind #6352). The vendored driver now answers a statement that fails to build in its place in the pipeline (the approach of porsager/postgres#1236), so only the culprit fails and a transaction it was part of is aborted rather than committed without it; a connection whose statement waits past `statement_timeout` plus 30 s with nothing coming back is retired and replaced; the pool numbers are live; and `/health?deep=1` probes through the same pool the handlers use.**GBRA-76. Reproduced on master against Postgres 16 with `max: 1, prepare: false, shared_types: true`: a head statement, a statement binding `undefined`, and a describe-first follower issued together. Head rejects with `UNDEFINED_VALUE`, the culprit with `null is not an object (evaluating 'query.statement.types')`, the follower and everything after it never settle, and `pg_stat_activity` shows the backend `active / Client:ClientRead` on the follower. With the fix the head and the follower resolve with their own rows, only the culprit rejects, and the backend is idle.### Itemized changes-- **A statement that fails to build never touches its connection** (`vendor/postgres/src/connection.js`, the `cjs` and `cf` copies, `patches/[email protected]`). `execute()` builds and serializes the statement first and enqueues it only once its bytes exist. A build failure (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) rejects that statement alone; a head statement on an idle connection still owns the `Sync` round trip the stock driver wrote, so the reservation and transaction state machines are unchanged. The pool reports each failure through `onbuilderror(code, statement)` with the statement's text and `$n` placeholders, never values; the engine logs it as `[gbrain] warn code=pg_statement_build_failed error=UNDEFINED_VALUE pool=read sql=INSERT_mcp_request_log` (first keyword and table), so the call site that binds `undefined`, which nobody has found yet, names itself the first time it happens.+- **A statement that fails to build is answered in its place** (`vendor/postgres/src/connection.js`, the `cjs` and `cf` copies, `patches/[email protected]`; the approach of upstream PR porsager/postgres#1236, which fixes the same desync as porsager/postgres#1082). A statement joins the connection's queue before it is built, so when `build` throws (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) it already holds a place in the pipeline with nothing on the wire. The driver now sends a query the server is certain to refuse in that place: the culprit gets an answer of its own and rejects with its own error, every later reply stays with its statement, and a transaction the culprit was part of is aborted by the server (the member behind it is refused with `25P02`, a pipelined `commit` lands as `ROLLBACK`) instead of committing without it. The reservation and transaction state machines are unchanged. The pool reports each failure through `onbuilderror(code, statement)` with the statement's text and `$n` placeholders, never values; the engine logs it as `[gbrain] warn code=pg_statement_build_failed error=UNDEFINED_VALUE pool=read sql=INSERT_mcp_request_log` (first keyword and table), so the call site that binds `undefined`, which nobody has found yet, names itself the first time it happens.- **A connection whose statement never answers is retired, not kept** (`connection.js`, `index.js`, `src/core/db.ts`, `connection-manager.ts`, `postgres-engine.ts`, `pool-gauge.ts`). New pool option `inflight_timeout`: a clock on the head statement that starts when it becomes the head, restarts on every byte the server sends and stops at `ReadyForQuery`. Past it the statement and everything queued behind it reject with `CONNECTION_STUCK`, the pool parks the connection out of rotation before its socket closes, `onstuck({ age_ms, queued, statement })` fires once, the socket is ended and destroyed, and the pool reconnects. gbrain sets it to each pool's own `statement_timeout` plus `GBRAIN_PG_STUCK_GRACE_MS` (default 30 000 ms; `0`/`off` disables it; a pool without a statement timeout has no watchdog), so a legitimate statement, which the server ends first, is never retired, while a desynced pipeline, a transaction-mode pooler that swallowed a `CancelRequest`, or a dead peer costs one budget instead of a restart. Each retirement logs `pg_connection_stuck` with the pool, age, queue depth and the statement's keyword and table, and counts in `getPoolDiagnostics().stuckDiscards`.- **The pool numbers are live** (`index.js`, `postgres-engine/pool-stats.ts`, `persistence/consumer-heartbeat.ts`). `sql.pool` (#6317) was defined inside `Object.assign`, which reads a getter once and copies the value, so every reader saw the construction-time snapshot (`checked_out: 0`, `waiters: 0`) for the life of the pool. It is a property getter now and adds `inflight_oldest_ms` (the oldest head statement's age) and `completed` (statements settled). The persistence heartbeat row carries both, so `gbrain sources writer status --json` shows them for the owner process.- **`/health?deep=1`** (`serve-http-metrics.ts`). Plain `/health` is unchanged and still fast. It answered 200 through the whole incident because its `SELECT 1` runs on a reserved connection, and `reserve()` only ever claims an idle one; the wedged connections sat in the busy queue where handler statements are routed. `/health?deep=1` runs `SELECT 1` through that ordinary pooled dispatch with the 3 s budget, returns the pool block (`checked_out`, `max`, `waiters`, `inflight_oldest_ms`, `completed`, `poisoned_discards`, `stuck_discards`, `build_failures`) and answers 503 when the probe times out, when a statement is past the read pool's in-flight budget, or while an earlier deep probe is still pending (one at a time per engine).@@ -26,7 +26,7 @@ GBRA-76. Reproduced on master against Postgres 16 with `max: 1, prepare: false,- `gbrain errors pg_connection_stuck | pg_statement_build_failed | pg_pool_stalled` resolve offline; [docs/ENGINES.md](docs/ENGINES.md#pg-connection-stuck) has the entries and the `/health?deep=1` contract; `docs/mcp/DEPLOY.md` names the deep probe for supervisors.- Not in this release: forwarding an HTTP client's abort into the MCP handler (serve never did; the cancel in the #6383 timeline was coincidental, the retries fed the wedged connection) and a deadline on publication transactions (#6352's second ask).- Tests:- - `test/e2e/postgres-pipelined-build-failure-postgres.test.ts` (5 cases: the pipelined culprit, a culprit as head on an idle and on a reserved connection, a transaction with a bad member, `MAX_PARAMETERS_EXCEEDED`, the CommonJS build). On master 5 of 5 fail: the follower and later statements hang and the backend stays `active`.+ - `test/e2e/postgres-pipelined-build-failure-postgres.test.ts` (6 cases: the pipelined culprit, a culprit as head on an idle and on a reserved connection, a `sql.begin` with a bad member, a pipelined `begin … commit` on a reserved connection with a bad member, `MAX_PARAMETERS_EXCEEDED`, the CommonJS build). On master 6 of 6 fail: the follower and later statements hang and the backend stays `active`. A fix that only drops the culprit from the pipeline fails the two transaction cases: both inserts commit.- `test/e2e/postgres-stuck-connection-postgres.test.ts` (5 cases: live pool numbers, a stuck head and its queued follower, a stuck reserved connection, no false positive within budget and with the watchdog off, the engine's counter and warn line). On master 4 of 5 fail: `busy` reads 0 during `pg_sleep` and the stuck statements hang.- `test/pool-health-6383.test.ts` (18 cases, no database): the budget derivation and its `0`/`off` switch, the three warn lines, the stall watch's two-tick rule and single recovery line, and `/health?deep=1`'s 200, budget-exceeded 503, timeout 503, pending 503 and PGLite paths.diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex ee922d5d5a..02b82fbe60 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -723,8 +723,9 @@ with the operations that preceded them.<a id="pg-statement-build-failed"></a>**`pg_statement_build_failed`** (warn). Astatement could not be built from its parameters (`error=UNDEFINED_VALUE`: aparameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534-parameters) and was rejected before it reached the connection. No other-statement was affected: before #6383 the same failure, when the statement was+parameters). It was answered in its place in the pipeline by a query the server+refuses, so only it failed and a transaction it was part of was aborted rather+than committed without it. No other statement was affected: before #6383 the same failure, when the statement waspipelined behind another on its connection, rejected that other statement withits error, left the culprit queued with nothing on the wire, and delivered everylater reply one statement late until the process restarted (thediff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 147087c235..3b47cfe03d 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1986,7 +1986,7 @@ More: [docs/ENGINES.md#pg-pool-stalled](../../docs/ENGINES.md#pg-pool-stalled)| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was rejected before it reached the connection; no other statement was affected. | This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now rejects only the culprit. | The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined. | host_admin | `gbrain doctor --json` | 1 | no |+| A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was answered in its place in the pipeline by a query the server refuses; only it failed, and a transaction it was part of was aborted rather than committed without it. | This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now answers the culprit in its place (the approach of porsager/postgres#1236), so only it rejects and a transaction it was in aborts. | The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined. | host_admin | `gbrain doctor --json` | 1 | no |More: [docs/ENGINES.md#pg-statement-build-failed](../../docs/ENGINES.md#pg-statement-build-failed)diff --git a/llms-full.txt b/llms-full.txtindex 08089fb99b..32492c59d5 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5786,8 +5786,9 @@ with the operations that preceded them.<a id="pg-statement-build-failed"></a>**`pg_statement_build_failed`** (warn). Astatement could not be built from its parameters (`error=UNDEFINED_VALUE`: aparameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534-parameters) and was rejected before it reached the connection. No other-statement was affected: before #6383 the same failure, when the statement was+parameters). It was answered in its place in the pipeline by a query the server+refuses, so only it failed and a transaction it was part of was aborted rather+than committed without it. No other statement was affected: before #6383 the same failure, when the statement waspipelined behind another on its connection, rejected that other statement withits error, left the culprit queued with nothing on the wire, and delivered everylater reply one statement late until the process restarted (thediff --git a/patches/[email protected] b/patches/[email protected]index ea31f44910..7dba03bd8d 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -1,8 +1,16 @@diff --git a/cjs/src/connection.js b/cjs/src/connection.js-index 07f6716..813790c 100644+index 07f67167..9224858c 100644--- a/cjs/src/connection.js+++ b/cjs/src/connection.js-@@ -49,7 +49,7 @@ const errorFields = {+@@ -20,6 +20,7 @@ const Sync = b().S().end()+ , SSLRequest = b().i32(8).i32(80877103).end(8)+ , ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync])+ , DescribeUnnamed = b().D().str('S').str(b.N).end()++ , Unbuildable = b().Q().str('postgres.js: query could not be built' + b.N).end()+ , noop = () => { /* noop */ }++ const retryRoutines = new Set([+@@ -49,7 +50,7 @@ const errorFields = {82 : 'routine' // R}@@ -11,7 +19,7 @@ index 07f6716..813790c 100644const {sslnegotiation,ssl,-@@ -75,9 +75,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -75,9 +76,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout)@@ -25,7 +33,7 @@ index 07f6716..813790c 100644, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0)-@@ -105,11 +109,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -105,11 +110,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, ended = null, nonce = null, query = null@@ -39,7 +47,7 @@ index 07f6716..813790c 100644connect(query) {initial = queryreconnect()-@@ -143,11 +149,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -143,11 +150,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}async function cancel({ pid, secret }, resolve, reject) {@@ -55,57 +63,34 @@ index 07f6716..813790c 100644} catch (error) {reject(error)}-@@ -163,25 +171,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose- if (q.cancelled)- return--+ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to-+ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an-+ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and-+ // every later reply on the socket was delivered one statement late until the process restarted.-+ let bytes- try {+@@ -167,7 +176,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.state = backend-+ build(q)-+ bytes = toBuffer(q)-+ } catch (error) {-+ if (!query) {-+ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.-+ query = q-+ query.active = true-+ write(Sync)-+ armInflight()-+ }-+ options.onbuilderror && reportBuildError(q, error)-+ queryError(q, error)-+ return true-+ }-+-+ try {query? sent.push(q)- : (query = q, query.active = true)+ : (query = q, query.active = true, armInflight())-- build(q)-- return write(toBuffer(q))-+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)-+ return write(bytes)- && !q.describeFirst- && !q.cursorFn+ build(q)+ return write(toBuffer(q))+@@ -176,12 +185,60 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose&& sent.length < max_pipeline-- && (!q.options.onexecute || q.options.onexecute(connection))-+ && mayPipeline+ && (!q.options.onexecute || q.options.onexecute(connection))} catch (error) {- sent.length === 0 && write(Sync)- errored(error)-+ if (query === q) {-+ sent.length === 0 && write(Sync)-+ errored(error)-+ } else {-+ sent.remove(q)-+ queryError(q, error)-+ }++ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of++ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's++ // current query with q's error and left q waiting, so every later answer went to the wrong query.++ // Send a query the server is sure to refuse in q's place: q gets an answer of its own, every later++ // answer stays with its query, and a transaction q was part of is aborted instead of committing++ // without it. q is then rejected with its own error, as a retried query is (ReadyForQuery). It is no++ // longer described first or a cursor, since either would make the server's error send a Sync of its++ // own and shift the next answer.++ q.retried = error++ q.describeFirst = false++ q.cursorFn = null++ options.onbuilderror && reportBuildError(q, error)++ write(Unbuildable)return true}}@@ -150,7 +135,7 @@ index 07f6716..813790c 100644function toBuffer(q) {if (q.parameters.length >= 65534)throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')-@@ -235,10 +306,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -235,10 +292,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -168,7 +153,7 @@ index 07f6716..813790c 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +371,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +357,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -181,7 +166,7 @@ index 07f6716..813790c 100644if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,6 +456,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,6 +442,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -190,7 +175,7 @@ index 07f6716..813790c 100644if (connection.queue === queues.connecting && options.host[retries + 1])return-@@ -388,6 +467,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -388,6 +453,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function errored(err) {@@ -199,7 +184,7 @@ index 07f6716..813790c 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +519,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,19 +505,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -239,7 +224,7 @@ index 07f6716..813790c 100644closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -533,8 +633,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -533,8 +619,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -253,7 +238,7 @@ index 07f6716..813790c 100644query.retried? errored(query.retried): query.prepared && retryRoutines.has(errorResponse.routine)-@@ -550,6 +655,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -550,6 +641,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()@@ -261,7 +246,7 @@ index 07f6716..813790c 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +670,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +656,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -291,7 +276,7 @@ index 07f6716..813790c 100644: connection.reserved(): ending? terminate()-@@ -630,6 +738,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,6 +724,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -301,7 +286,7 @@ index 07f6716..813790c 100644query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)}-@@ -767,14 +878,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +864,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -332,7 +317,7 @@ index 07f6716..813790c 100644}diff --git a/cjs/src/index.js b/cjs/src/index.js-index f09c61c..abb4a15 100644+index f09c61c7..abb4a158 100644--- a/cjs/src/index.js+++ b/cjs/src/index.js@@ -62,10 +62,34 @@ function Postgres(a, b) {@@ -700,7 +685,7 @@ index f09c61c..abb4a15 100644}}diff --git a/cjs/src/query.js b/cjs/src/query.js-index 45327f2..1d09250 100644+index 45327f2f..1d092504 100644--- a/cjs/src/query.js+++ b/cjs/src/query.js@@ -23,11 +23,12 @@ const Query = module.exports.Query = class Query extends Promise {@@ -744,7 +729,7 @@ index 45327f2..1d09250 100644this.execute()return promisediff --git a/cjs/src/queue.js b/cjs/src/queue.js-index 8438f5d..c444310 100644+index 8438f5da..c444310f 100644--- a/cjs/src/queue.js+++ b/cjs/src/queue.js@@ -15,6 +15,7 @@ function Queue(initial = []) {@@ -756,10 +741,18 @@ index 8438f5d..c444310 100644const out = xs[index++]diff --git a/src/connection.js b/src/connection.js-index 1b1cccd..a2e2deb 100644+index 1b1cccde..c1a9075a 100644--- a/src/connection.js+++ b/src/connection.js-@@ -49,7 +49,7 @@ const errorFields = {+@@ -20,6 +20,7 @@ const Sync = b().S().end()+ , SSLRequest = b().i32(8).i32(80877103).end(8)+ , ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync])+ , DescribeUnnamed = b().D().str('S').str(b.N).end()++ , Unbuildable = b().Q().str('postgres.js: query could not be built' + b.N).end()+ , noop = () => { /* noop */ }++ const retryRoutines = new Set([+@@ -49,7 +50,7 @@ const errorFields = {82 : 'routine' // R}@@ -768,7 +761,7 @@ index 1b1cccd..a2e2deb 100644const {sslnegotiation,ssl,-@@ -75,9 +75,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -75,9 +76,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout)@@ -782,7 +775,7 @@ index 1b1cccd..a2e2deb 100644, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0)-@@ -105,11 +109,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -105,11 +110,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, ended = null, nonce = null, query = null@@ -796,7 +789,7 @@ index 1b1cccd..a2e2deb 100644connect(query) {initial = queryreconnect()-@@ -143,11 +149,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -143,11 +150,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}async function cancel({ pid, secret }, resolve, reject) {@@ -812,57 +805,34 @@ index 1b1cccd..a2e2deb 100644} catch (error) {reject(error)}-@@ -163,25 +171,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose- if (q.cancelled)- return--+ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to-+ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an-+ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and-+ // every later reply on the socket was delivered one statement late until the process restarted.-+ let bytes- try {+@@ -167,7 +176,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.state = backend-+ build(q)-+ bytes = toBuffer(q)-+ } catch (error) {-+ if (!query) {-+ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.-+ query = q-+ query.active = true-+ write(Sync)-+ armInflight()-+ }-+ options.onbuilderror && reportBuildError(q, error)-+ queryError(q, error)-+ return true-+ }-+-+ try {query? sent.push(q)- : (query = q, query.active = true)+ : (query = q, query.active = true, armInflight())-- build(q)-- return write(toBuffer(q))-+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)-+ return write(bytes)- && !q.describeFirst- && !q.cursorFn+ build(q)+ return write(toBuffer(q))+@@ -176,12 +185,60 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose&& sent.length < max_pipeline-- && (!q.options.onexecute || q.options.onexecute(connection))-+ && mayPipeline+ && (!q.options.onexecute || q.options.onexecute(connection))} catch (error) {- sent.length === 0 && write(Sync)- errored(error)-+ if (query === q) {-+ sent.length === 0 && write(Sync)-+ errored(error)-+ } else {-+ sent.remove(q)-+ queryError(q, error)-+ }++ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of++ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's++ // current query with q's error and left q waiting, so every later answer went to the wrong query.++ // Send a query the server is sure to refuse in q's place: q gets an answer of its own, every later++ // answer stays with its query, and a transaction q was part of is aborted instead of committing++ // without it. q is then rejected with its own error, as a retried query is (ReadyForQuery). It is no++ // longer described first or a cursor, since either would make the server's error send a Sync of its++ // own and shift the next answer.++ q.retried = error++ q.describeFirst = false++ q.cursorFn = null++ options.onbuilderror && reportBuildError(q, error)++ write(Unbuildable)return true}}@@ -907,7 +877,7 @@ index 1b1cccd..a2e2deb 100644function toBuffer(q) {if (q.parameters.length >= 65534)throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')-@@ -235,10 +306,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -235,10 +292,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -925,7 +895,7 @@ index 1b1cccd..a2e2deb 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +371,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +357,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -938,7 +908,7 @@ index 1b1cccd..a2e2deb 100644if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,6 +456,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,6 +442,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -947,7 +917,7 @@ index 1b1cccd..a2e2deb 100644if (connection.queue === queues.connecting && options.host[retries + 1])return-@@ -388,6 +467,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -388,6 +453,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function errored(err) {@@ -956,7 +926,7 @@ index 1b1cccd..a2e2deb 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +519,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,19 +505,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -996,7 +966,7 @@ index 1b1cccd..a2e2deb 100644closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -533,8 +633,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -533,8 +619,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -1010,7 +980,7 @@ index 1b1cccd..a2e2deb 100644query.retried? errored(query.retried): query.prepared && retryRoutines.has(errorResponse.routine)-@@ -550,6 +655,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -550,6 +641,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()@@ -1018,7 +988,7 @@ index 1b1cccd..a2e2deb 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +670,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +656,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -1048,7 +1018,7 @@ index 1b1cccd..a2e2deb 100644: connection.reserved(): ending? terminate()-@@ -630,6 +738,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,6 +724,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -1058,7 +1028,7 @@ index 1b1cccd..a2e2deb 100644query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)}-@@ -767,14 +878,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +864,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -1089,7 +1059,7 @@ index 1b1cccd..a2e2deb 100644}diff --git a/src/index.js b/src/index.js-index c7fba3d..32efd8b 100644+index c7fba3da..32efd8bf 100644--- a/src/index.js+++ b/src/index.js@@ -62,10 +62,34 @@ function Postgres(a, b) {@@ -1457,7 +1427,7 @@ index c7fba3d..32efd8b 100644}}diff --git a/src/query.js b/src/query.js-index 0d44a15..9696778 100644+index 0d44a15c..96967780 100644--- a/src/query.js+++ b/src/query.js@@ -23,11 +23,12 @@ export class Query extends Promise {@@ -1501,7 +1471,7 @@ index 0d44a15..9696778 100644this.execute()return promisediff --git a/src/queue.js b/src/queue.js-index c4ef971..8fba891 100644+index c4ef9716..8fba891b 100644--- a/src/queue.js+++ b/src/queue.js@@ -15,6 +15,7 @@ function Queue(initial = []) {@@ -1513,7 +1483,7 @@ index c4ef971..8fba891 100644const out = xs[index++]diff --git a/types/index.d.ts b/types/index.d.ts-index 13c3432..3623312 100644+index 13c3432f..36233121 100644--- a/types/index.d.ts+++ b/types/index.d.ts@@ -119,6 +119,32 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 808f25aa16..f6df2a343f 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -309,7 +309,7 @@ export const CODES = {persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement waited past the pool's statement_timeout plus grace with nothing coming back from the server, so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "A legitimate statement cannot outlive the server-side statement_timeout, so a connection that is still waiting past it is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },- pg_statement_build_failed: { class: 'server', summary: "A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was rejected before it reached the connection; no other statement was affected.", why: "This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now rejects only the culprit.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined.' },+ pg_statement_build_failed: { class: 'server', summary: "A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was answered in its place in the pipeline by a query the server refuses; only it failed, and a transaction it was part of was aborted rather than committed without it.", why: "This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now answers the culprit in its place (the approach of porsager/postgres#1236), so only it rejects and a transaction it was in aborts.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined.' },pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },pglite_vector_index_too_large: { class: 'unavailable', summary: "A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap.", why: "pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans.", docs: 'docs/ENGINES.md#pglite-vector-index-ceiling', suggestion: 'Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json', fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists what moves to Postgres, the blockers and the exact run command.', requires_exclusive: false } },plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },diff --git a/test/e2e/postgres-pipelined-build-failure-postgres.test.ts b/test/e2e/postgres-pipelined-build-failure-postgres.test.tsindex 62f4dd9424..ae8fd30b04 100644--- a/test/e2e/postgres-pipelined-build-failure-postgres.test.ts+++ b/test/e2e/postgres-pipelined-build-failure-postgres.test.ts@@ -1,20 +1,30 @@/*** #6383 (and the driver desync behind #6352): a statement that fails to build- * (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) used to join the connection's- * queue before it was built, so when another statement was already in flight- * the failure rejected that head statement with the wrong error, left the- * culprit queued with nothing on the wire, and every later reply on the socket- * was delivered one statement late. A describe-first statement then never got- * its ParameterDescription, so its Bind/Execute/Sync was never sent and the+ * (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) joins the connection's queue+ * before it is built, and nothing of it reaches the wire. The stock catch+ * rejected the connection's current statement with the culprit's error and+ * left the culprit queued, so every later reply on the socket was delivered+ * one statement late. A describe-first statement then never got its+ * ParameterDescription, so its Bind/Execute/Sync was never sent and the* backend sat `active / ClientRead` until the process restarted.*+ * The vendored fix follows porsager/postgres#1236: a query the server is sure+ * to refuse goes out in the culprit's place, so the culprit gets an answer of+ * its own (and rejects with its own error), every later reply stays with its+ * statement, and a transaction the culprit was part of is aborted by the+ * server instead of committing without it.+ ** Protects: only the culprit rejects, with its own error; the head and every- * later statement resolve with their own rows; the backend returns to idle; a- * transaction with a bad member rolls back cleanly; the pool reports each- * build failure through `onbuilderror` with the statement's text and no- * parameter values. Regression that fails it on master: `next` and `later`- * never settle (the 5 s race below reports `hung`), and the backend stays- * `active`.+ * later statement outside a transaction resolve with their own rows; the+ * backend returns to idle; a `sql.begin` with a bad member rolls back; a+ * pipelined `begin … commit` on a reserved connection with a bad member+ * commits nothing (the member behind it is refused with `25P02` and the+ * `commit` lands as `ROLLBACK`); the pool reports each build failure through+ * `onbuilderror` with the statement's text and no parameter values.+ * Regression that fails it on master: `next` and `later` never settle (the+ * 5 s race below reports `hung`), and the backend stays `active`. A fix that+ * only drops the culprit from the pipeline fails the reserved-transaction+ * case: both inserts commit.*/import { afterEach, describe, expect, test } from 'bun:test';import { createRequire } from 'node:module';@@ -88,17 +98,55 @@ describe.skipIf(!url)('#6383 a statement that fails to build never desyncs its cexpect(builds.map(b => b[0])).toEqual(['UNDEFINED_VALUE', 'UNDEFINED_VALUE']);});- test('a transaction with a bad member rolls back and the backend is idle, not left in the transaction', async () => {+ test('a sql.begin with a bad member rolls back: the member behind it is refused, nothing commits, the backend is idle', async () => {const builds: Array<[string, string]> = [];const { sql, appName } = pool(1, builds);- const tx = await settle(sql.begin(async tx => Promise.allSettled([- tx`SELECT 1 AS a`,- tx`SELECT ${undefined as unknown as string}::text`,- tx`SELECT 2 AS b, ${3}::int AS c`,- ])));- expect(tx).toEqual({ code: 'UNDEFINED_VALUE' });- expect(await settle(sql`SELECT 'after' AS who`)).toEqual({ rows: [{ who: 'after' }] });- expect(await backendStates(appName)).toEqual(['idle']);+ const table = `t6383_${Math.random().toString(36).slice(2)}`;+ await sql.unsafe(`CREATE TABLE ${table} (x int)`);+ try {+ const members: Settled[] = [];+ const tx = await settle(sql.begin(async tx => {+ const settled = await Promise.all([+ settle(tx.unsafe(`INSERT INTO ${table} VALUES (1)`)),+ settle(tx`SELECT ${undefined as unknown as string}::text`),+ settle(tx.unsafe(`INSERT INTO ${table} VALUES (2)`)),+ ]);+ members.push(...settled);+ }));+ expect(tx).toEqual({ code: 'UNDEFINED_VALUE' });+ expect(members).toEqual([{ rows: [] }, { code: 'UNDEFINED_VALUE' }, { code: '25P02' }]);+ expect(await settle(sql.unsafe(`SELECT count(*)::int AS n FROM ${table}`))).toEqual({ rows: [{ n: 0 }] });+ expect(await backendStates(appName)).toEqual(['idle']);+ } finally {+ await sql.unsafe(`DROP TABLE ${table}`);+ }+ });++ test('a pipelined begin … commit on a reserved connection with a bad member commits nothing (the porsager/postgres#1236 case)', async () => {+ const builds: Array<[string, string]> = [];+ const { sql, appName } = pool(1, builds);+ const table = `t6383_${Math.random().toString(36).slice(2)}`;+ await sql.unsafe(`CREATE TABLE ${table} (x int)`);+ try {+ const reserved = await sql.reserve();+ const results = await Promise.all([+ reserved`begin`,+ reserved.unsafe(`INSERT INTO ${table} VALUES (1)`),+ reserved`SELECT ${undefined as unknown as string}::text AS x`,+ reserved.unsafe(`INSERT INTO ${table} VALUES (2)`),+ reserved`commit`,+ ].map(q => Promise.race([+ Promise.resolve(q).then(r => (r as { command?: string }).command ?? 'rows', (e: { code?: string }) => e.code ?? 'error'),+ new Promise<string>(resolve => setTimeout(() => resolve('hung'), 5000)),+ ])));+ reserved.release();+ expect(results).toEqual(['BEGIN', 'INSERT', 'UNDEFINED_VALUE', '25P02', 'ROLLBACK']);+ expect(await settle(sql.unsafe(`SELECT count(*)::int AS n FROM ${table}`))).toEqual({ rows: [{ n: 0 }] });+ expect(await backendStates(appName)).toEqual(['idle']);+ expect(builds).toEqual([['UNDEFINED_VALUE', 'SELECT $1::text AS x']]);+ } finally {+ await sql.unsafe(`DROP TABLE ${table}`);+ }});test('MAX_PARAMETERS_EXCEEDED behind a head statement is rejected alone too', async () => {diff --git a/vendor/README.md b/vendor/README.mdindex 0efeedda69..a6a21b97c0 100644--- a/vendor/README.md+++ b/vendor/README.md@@ -37,12 +37,17 @@ must settle or retire the connection before another query can own it. Thisis necessary for worker admission, query timeout and lease-release safety.See issues #5466 and #5560 and `test/e2e/persistence-chaos.test.ts`.-A statement is built and serialized before it joins a connection's queue-(#6383). Stock postgres.js enqueues first, so a statement that fails to build-(`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) behind an in-flight statement-rejects that head statement with its error, stays queued with nothing on the-wire, and every later reply on the socket is delivered one statement late until-the process restarts; with the patch only the culprit rejects, reported through+A statement that fails to build is answered in its place in the pipeline+(#6383; the approach of upstream PR porsager/postgres#1236, which fixes+porsager/postgres#1082, so this hunk drops when that merges). A statement joins+a connection's queue before it is built, so when `build` throws+(`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) behind an in-flight statement,+stock postgres.js rejects that head statement with its error, leaves the+culprit queued with nothing on the wire, and delivers every later reply on the+socket one statement late until the process restarts. With the patch a query+the server is certain to refuse goes out in the culprit's place: only the+culprit rejects, with its own error, a transaction it was part of is aborted+rather than committed without it, and the pool reports the failure through`onbuilderror(code, statement)` (template text with `$n` placeholders, novalues). The same patch adds the in-flight watchdog: `inflight_timeout`(seconds) bounds how long a head statement may wait with nothing coming back;diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsindex e8ecf9da80..96f2277dad 100644--- a/vendor/postgres/cf/src/connection.js+++ b/vendor/postgres/cf/src/connection.js@@ -22,6 +22,7 @@ const Sync = b().S().end(), SSLRequest = b().i32(8).i32(80877103).end(8), ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync]), DescribeUnnamed = b().D().str('S').str(b.N).end()+ , Unbuildable = b().Q().str('postgres.js: query could not be built' + b.N).end(), noop = () => { /* noop */ }const retryRoutines = new Set([@@ -173,47 +174,32 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return- // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to- // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an- // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and- // every later reply on the socket was delivered one statement late until the process restarted.- let bytestry {q.state = backend- build(q)- bytes = toBuffer(q)- } catch (error) {- if (!query) {- // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.- query = q- query.active = true- write(Sync)- armInflight()- }- options.onbuilderror && reportBuildError(q, error)- queryError(q, error)- return true- }-- try {query? sent.push(q): (query = q, query.active = true, armInflight())- const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)- return write(bytes)+ build(q)+ return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn&& sent.length < max_pipeline- && mayPipeline+ && (!q.options.onexecute || q.options.onexecute(connection))} catch (error) {- if (query === q) {- sent.length === 0 && write(Sync)- errored(error)- } else {- sent.remove(q)- queryError(q, error)- }+ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of+ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's+ // current query with q's error and left q waiting, so every later answer went to the wrong query.+ // Send a query the server is sure to refuse in q's place: q gets an answer of its own, every later+ // answer stays with its query, and a transaction q was part of is aborted instead of committing+ // without it. q is then rejected with its own error, as a retried query is (ReadyForQuery). It is no+ // longer described first or a cursor, since either would make the server's error send a Sync of its+ // own and shift the next answer.+ q.retried = error+ q.describeFirst = false+ q.cursorFn = null+ options.onbuilderror && reportBuildError(q, error)+ write(Unbuildable)return true}}diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsindex 813790ce78..9224858c32 100644--- a/vendor/postgres/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end(), SSLRequest = b().i32(8).i32(80877103).end(8), ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync]), DescribeUnnamed = b().D().str('S').str(b.N).end()+ , Unbuildable = b().Q().str('postgres.js: query could not be built' + b.N).end(), noop = () => { /* noop */ }const retryRoutines = new Set([@@ -171,47 +172,32 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return- // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to- // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an- // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and- // every later reply on the socket was delivered one statement late until the process restarted.- let bytestry {q.state = backend- build(q)- bytes = toBuffer(q)- } catch (error) {- if (!query) {- // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.- query = q- query.active = true- write(Sync)- armInflight()- }- options.onbuilderror && reportBuildError(q, error)- queryError(q, error)- return true- }-- try {query? sent.push(q): (query = q, query.active = true, armInflight())- const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)- return write(bytes)+ build(q)+ return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn&& sent.length < max_pipeline- && mayPipeline+ && (!q.options.onexecute || q.options.onexecute(connection))} catch (error) {- if (query === q) {- sent.length === 0 && write(Sync)- errored(error)- } else {- sent.remove(q)- queryError(q, error)- }+ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of+ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's+ // current query with q's error and left q waiting, so every later answer went to the wrong query.+ // Send a query the server is sure to refuse in q's place: q gets an answer of its own, every later+ // answer stays with its query, and a transaction q was part of is aborted instead of committing+ // without it. q is then rejected with its own error, as a retried query is (ReadyForQuery). It is no+ // longer described first or a cursor, since either would make the server's error send a Sync of its+ // own and shift the next answer.+ q.retried = error+ q.describeFirst = false+ q.cursorFn = null+ options.onbuilderror && reportBuildError(q, error)+ write(Unbuildable)return true}}diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex a2e2deb1a2..c1a9075a4f 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end(), SSLRequest = b().i32(8).i32(80877103).end(8), ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync]), DescribeUnnamed = b().D().str('S').str(b.N).end()+ , Unbuildable = b().Q().str('postgres.js: query could not be built' + b.N).end(), noop = () => { /* noop */ }const retryRoutines = new Set([@@ -171,47 +172,32 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return- // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to- // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an- // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and- // every later reply on the socket was delivered one statement late until the process restarted.- let bytestry {q.state = backend- build(q)- bytes = toBuffer(q)- } catch (error) {- if (!query) {- // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.- query = q- query.active = true- write(Sync)- armInflight()- }- options.onbuilderror && reportBuildError(q, error)- queryError(q, error)- return true- }-- try {query? sent.push(q): (query = q, query.active = true, armInflight())- const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)- return write(bytes)+ build(q)+ return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn&& sent.length < max_pipeline- && mayPipeline+ && (!q.options.onexecute || q.options.onexecute(connection))} catch (error) {- if (query === q) {- sent.length === 0 && write(Sync)- errored(error)- } else {- sent.remove(q)- queryError(q, error)- }+ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of+ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's+ // current query with q's error and left q waiting, so every later answer went to the wrong query.+ // Send a query the server is sure to refuse in q's place: q gets an answer of its own, every later+ // answer stays with its query, and a transaction q was part of is aborted instead of committing+ // without it. q is then rejected with its own error, as a retried query is (ReadyForQuery). It is no+ // longer described first or a cursor, since either would make the server's error send a Sync of its+ // own and shift the next answer.+ q.retried = error+ q.describeFirst = false+ q.cursorFn = null+ options.onbuilderror && reportBuildError(q, error)+ write(Unbuildable)return true}}