Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres-driver): no server cancel for a cancelled query while statements are pipelined behind it
time-attackda40fa5db009
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e563ebbcb0..c19aa7df17 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,7 @@ identifiers and attribution are available in the pre-removal Git revision### Itemized changes-- `vendor/postgres` (ESM, CommonJS, workerd) and `patches/[email protected]`: a query cancelled after it was written keeps its place in the answer order and rejects with `57014`; a cancelled prepared query is not retried. The 3.4.9 upstream release and upstream master carry the same code.+- `vendor/postgres` (ESM, CommonJS, workerd) and `patches/[email protected]`: a query cancelled after it was written keeps its place in the answer order and rejects with `57014`, and no server cancel is sent for it while other statements are pipelined behind it, so the cancel can't land on one of them; a cancelled prepared query is not retried. The 3.4.9 upstream release and upstream master carry the same code.- The driver's `ondesync` option reports a desynced connection; `PoolIncidentCounter` logs it once per trip and counts it as `getPoolDiagnostics().desyncDiscards` (`desync_discards` in `/health?deep=1`).- `test/e2e/postgres-driver-cancel-pipeline.test.ts` (direct and PgBouncer transaction mode, prepared and unprepared) and `test/e2e/postgres-driver-desync-tripwire.test.ts` fail on the old driver and pass on this one.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 0f8be418da..26752eaeec 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server. A query cancelled after it was written stays current until its own ReadyForQuery, so its answer is never read for the next query, and rejects `57014` (pinned by `test/e2e/postgres-driver-cancel-pipeline.test.ts`, direct and PgBouncer). A statement answer that arrives with no current query retires the connection with `CONNECTION_DESYNC` and calls `ondesync({ message, connection, statement })`; `PoolIncidentCounter` logs `pg_connection_desync` (pinned by `test/e2e/postgres-driver-desync-tripwire.test.ts`).+- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server. A query cancelled after it was written stays current until its own ReadyForQuery, so its answer is never read for the next query, and rejects `57014`; no server cancel is sent for it while statements are pipelined behind it, because a CancelRequest stops whatever the backend is running (pinned by `test/e2e/postgres-driver-cancel-pipeline.test.ts`, direct and PgBouncer). A statement answer that arrives with no current query retires the connection with `CONNECTION_DESYNC` and calls `ondesync({ message, connection, statement })`; `PoolIncidentCounter` logs `pg_connection_desync` (pinned by `test/e2e/postgres-driver-desync-tripwire.test.ts`).- `src/core/pg-type-cache.ts` — the store `shared_types` uses: one `SharedParameterTypes` Map per database target in this process (`sharedParameterTypes(url)`), keyed by SHA-256 digests of the driver's (types, SQL) key, and saved under `<gbrain home>/cache/pg-types/` (0600) for the next process. `db.checkPoolAndLoadSharedTypes` reads its scope (`server_version_num`, `config.version`, and the database as the server names it, so a proxy and a direct URL share a file) in each new pool's connection check and loads it; a different scope is ignored and replaced, a migration's `clearSharedTypes` deletes the file. `GBRAIN_PG_TYPE_CACHE_PERSIST=0` keeps it in-process. Pinned by `test/pg-type-cache.test.ts` and the new-process case in `test/e2e/postgres-shared-types.test.ts`.- `src/core/engine-sql/` — one SQL implementation per migrated storage domain (the domains are the `migrated` rows of `scripts/engine-sql-baseline.tsv`), run by both engines through one executor contract:diff --git a/patches/[email protected] b/patches/[email protected]index 60b33005bc..7d5dbabcdf 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -1,5 +1,5 @@diff --git a/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js-index 07f67167..f4afd61d 100644+index 07f67167..1d6ea0a5 100644--- a/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -324,7 +324,7 @@ index 07f67167..f4afd61d 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +703,33 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +703,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -343,10 +343,13 @@ index 07f67167..f4afd61d 100644+ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.++ // A server cancel targets the backend, not a statement, so it is only sent when nothing is pipelined behind.+ if (sent.length) {+ query = sent.shift()+ query.active = true-+ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ query.cancelled && (sent.length++ ? query.cancelled.resolve()++ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))+ }++ flushRetries()@@ -364,7 +367,7 @@ index 07f67167..f4afd61d 100644: connection.reserved(): ending? terminate()-@@ -630,7 +779,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +782,11 @@ 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)@@ -376,7 +379,7 @@ index 07f67167..f4afd61d 100644}function RowDescription(x) {-@@ -767,14 +920,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +923,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -406,7 +409,7 @@ index 07f67167..f4afd61d 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +981,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +984,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -859,7 +862,7 @@ index 8438f5da..c444310f 100644const out = xs[index++]diff --git a/src/connection.js b/vendor/postgres/src/connection.js-index 1b1cccde..814037bc 100644+index 1b1cccde..37824bf4 100644--- a/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -1184,7 +1187,7 @@ index 1b1cccde..814037bc 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +703,33 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +703,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -1203,10 +1206,13 @@ index 1b1cccde..814037bc 100644+ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.++ // A server cancel targets the backend, not a statement, so it is only sent when nothing is pipelined behind.+ if (sent.length) {+ query = sent.shift()+ query.active = true-+ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ query.cancelled && (sent.length++ ? query.cancelled.resolve()++ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))+ }++ flushRetries()@@ -1224,7 +1230,7 @@ index 1b1cccde..814037bc 100644: connection.reserved(): ending? terminate()-@@ -630,7 +779,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +782,11 @@ 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)@@ -1236,7 +1242,7 @@ index 1b1cccde..814037bc 100644}function RowDescription(x) {-@@ -767,14 +920,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +923,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -1266,7 +1272,7 @@ index 1b1cccde..814037bc 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +981,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +984,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = errordiff --git a/test/e2e/postgres-driver-cancel-pipeline.test.ts b/test/e2e/postgres-driver-cancel-pipeline.test.tsindex 21629ccd57..15fa754d46 100644--- a/test/e2e/postgres-driver-cancel-pipeline.test.ts+++ b/test/e2e/postgres-driver-cancel-pipeline.test.ts@@ -3,7 +3,8 @@* had already been written to the server. The stock ReadyForQuery loop skipped it, so the answer the server still* sent for it was read for the next query: the next query resolved with the cancelled statement's rows (a bare* count resolved to []) and the cancelled query never settled. The cancelled query now stays current, absorbs its- * own answer and rejects as cancelled (57014); every later query reads its own rows. Runs direct and, when+ * own answer and rejects as cancelled (57014); every later query reads its own rows. q3 sleeps, so a server cancel+ * sent for q2 while q3 is pipelined behind it would land on q3; none is sent. Runs direct and, when* the CI PgBouncer fixture is configured (GBRAIN_PGBOUNCER_URL + GBRAIN_PGBOUNCER_DIRECT_URL), through PgBouncer* in transaction mode against a database of its own.*/@@ -49,7 +50,7 @@ describe.skipIf(targets.length === 0)('vendored driver: a query cancelled whileconst run = async (q: Pick<postgres.Sql, 'unsafe'>): Promise<Record<string, Outcome>> => {const q1 = q.unsafe('SELECT pg_sleep(0.2) AS slept').execute();const q2 = q.unsafe(second).execute();- const q3 = q.unsafe(`SELECT count(*)::int AS n FROM ${table}`).execute();+ const q3 = q.unsafe(`SELECT count(*)::int AS n FROM ${table}, pg_sleep(0.15)`).execute();await new Promise(resolve => setTimeout(resolve, 50));expect((q2 as unknown as { active: boolean }).active).toBe(false);const cancelled = q2.cancel();diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsindex 2473a23172..acca266e93 100644--- a/vendor/postgres/cf/src/connection.js+++ b/vendor/postgres/cf/src/connection.js@@ -716,10 +716,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the// server still sent for it was read for the next query (the next query resolved with another statement's// rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.+ // A server cancel targets the backend, not a statement, so it is only sent when nothing is pipelined behind.if (sent.length) {query = sent.shift()query.active = true- query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ query.cancelled && (sent.length+ ? query.cancelled.resolve()+ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))}flushRetries()diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsindex f4afd61d48..1d6ea0a50f 100644--- a/vendor/postgres/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -714,10 +714,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the// server still sent for it was read for the next query (the next query resolved with another statement's// rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.+ // A server cancel targets the backend, not a statement, so it is only sent when nothing is pipelined behind.if (sent.length) {query = sent.shift()query.active = true- query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ query.cancelled && (sent.length+ ? query.cancelled.resolve()+ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))}flushRetries()diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex 814037bc66..37824bf4cd 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -714,10 +714,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the// server still sent for it was read for the next query (the next query resolved with another statement's// rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.+ // A server cancel targets the backend, not a statement, so it is only sent when nothing is pipelined behind.if (sent.length) {query = sent.shift()query.active = true- query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ query.cancelled && (sent.length+ ? query.cancelled.resolve()+ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))}flushRetries()