Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Bound stale-plan retries, and start a plan generation only for a cached statement

garrytan7895e261b034
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e4e290b37..4be5ec6db8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,7 +18,7 @@ identifiers and attribution are available in the pre-removal Git revision
- `vendor/postgres` (`patches/[email protected]`): the first `RevalidateCachedQuery` error starts a process-wide plan generation; each connection drops its prepared statements before it builds its next query.
- `src/core/retry-matcher.ts`: `isStalePlanError` (SQLSTATE 0A000 with routine `RevalidateCachedQuery`, never the code alone) and `retryOnStalePlan`, one more run for a transaction that does only database work.
-- `src/core/persistence/admission-retry.ts`, `src/core/persistence/coordinator.ts`: write admission retries a stale plan within its existing budget, and publication and effects release a claim it aborted, as they do for contention.
+- `src/core/persistence/admission-retry.ts`, `src/core/persistence/coordinator.ts`: write admission re-runs a stale plan up to three times within its existing budget and then rethrows it unchanged, and publication and effects release a claim it aborted, as they do for contention.
- `src/core/oauth-grants.ts`, `src/core/minions/queue.ts`: the client-locked OAuth grant transaction and `completeJob` / `failJob` run once more after a stale plan.
- Tests: `test/stale-plan-heal.test.ts` (Postgres; listed in `test/postgres-unit-arms.txt`).
diff --git a/patches/[email protected] b/patches/[email protected]
index 13960369bf..b3ae640b62 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 07f6716..222249b 100644
+index 07f6716..1c709f4 100644
--- a/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -20,6 +20,7 @@
@@ -10,7 +10,7 @@ index 07f6716..222249b 100644
, noop = () => { /* noop */ }
const retryRoutines = new Set([
-@@ -28,6 +29,13 @@
+@@ -28,6 +29,15 @@
'transformAssignedExpr'
])
@@ -18,13 +18,15 @@ index 07f6716..222249b 100644
+// table it reads with SELECT * or RETURNING *) fails on every connection that prepared it. Stock postgres.js forgets it
+// only on the connection that failed, so each pooled connection failed once, and inside a transaction the caller saw
+// the failure. The first one in the process starts a new plan generation: each connection drops its prepared
-+// statements before it builds its next query, and prepares them again.
++// statements before it builds its next query, and prepares them again. Only a statement this connection had cached
++// starts one: a fresh statement that fails this way (a pooler mapping it onto an older server-side statement) is not
++// healed by preparing again.
+let planGeneration = 0
+
const errorFields = {
83 : 'severity_local', // S
86 : 'severity', // V
-@@ -49,7 +57,7 @@
+@@ -49,7 +59,7 @@
82 : 'routine' // R
}
@@ -33,7 +35,7 @@ index 07f6716..222249b 100644
const {
sslnegotiation,
ssl,
-@@ -64,6 +72,7 @@
+@@ -64,6 +74,7 @@
onnotify,
onparameter,
max_pipeline,
@@ -41,7 +43,7 @@ index 07f6716..222249b 100644
keep_alive,
backoff,
target_session_attrs
-@@ -75,9 +84,14 @@
+@@ -75,9 +86,14 @@
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
@@ -56,7 +58,7 @@ index 07f6716..222249b 100644
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
-@@ -86,6 +100,7 @@
+@@ -86,6 +102,7 @@
, statements = {}
, statementId = Math.random().toString(36).slice(2)
, statementCount = 1
@@ -64,7 +66,7 @@ index 07f6716..222249b 100644
, closedTime = 0
, remaining = 0
, hostIndex = 0
-@@ -95,6 +110,9 @@
+@@ -95,6 +112,9 @@
, rows = 0
, serverSignature = null
, nextWriteTimer = null
@@ -74,7 +76,7 @@ index 07f6716..222249b 100644
, terminated = false
, incomings = null
, results = null
-@@ -105,11 +123,19 @@
+@@ -105,11 +125,19 @@
, ended = null
, nonce = null
, query = null
@@ -94,7 +96,7 @@ index 07f6716..222249b 100644
connect(query) {
initial = query
reconnect()
-@@ -143,11 +169,13 @@
+@@ -143,11 +171,13 @@
}
async function cancel({ pid, secret }, resolve, reject) {
@@ -110,7 +112,7 @@ index 07f6716..222249b 100644
} catch (error) {
reject(error)
}
-@@ -163,22 +191,174 @@
+@@ -163,22 +193,174 @@
if (q.cancelled)
return
@@ -291,7 +293,7 @@ index 07f6716..222249b 100644
}
}
-@@ -232,13 +412,19 @@
+@@ -232,13 +414,19 @@
q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)
q.string = string
q.signature = q.prepare && types + string
@@ -313,7 +315,7 @@ index 07f6716..222249b 100644
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
-@@ -295,10 +481,11 @@
+@@ -295,10 +483,11 @@
/* c8 ignore next 3 */
function drain() {
@@ -326,7 +328,7 @@ index 07f6716..222249b 100644
if (incomings) {
incomings.push(x)
remaining -= x.length
-@@ -330,6 +517,9 @@
+@@ -330,6 +519,9 @@
remaining = 0
incomings = null
}
@@ -336,7 +338,7 @@ index 07f6716..222249b 100644
}
async function connect() {
-@@ -366,6 +556,7 @@
+@@ -366,6 +558,7 @@
try {
statements = {}
needsTypes = options.fetch_types
@@ -344,7 +346,7 @@ index 07f6716..222249b 100644
statementId = Math.random().toString(36).slice(2)
statementCount = 1
lifeTimer.start()
-@@ -379,20 +570,35 @@
+@@ -379,20 +572,35 @@
}
function error(err) {
@@ -380,7 +382,7 @@ index 07f6716..222249b 100644
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
-@@ -437,20 +643,53 @@
+@@ -437,20 +645,53 @@
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
@@ -436,7 +438,7 @@ index 07f6716..222249b 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -459,6 +698,10 @@
+@@ -459,6 +700,10 @@
/* Handlers */
function handle(xs, x = xs[0]) {
@@ -447,7 +449,7 @@ index 07f6716..222249b 100644
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
-@@ -489,6 +732,39 @@
+@@ -489,6 +734,39 @@
)(xs)
}
@@ -487,7 +489,7 @@ index 07f6716..222249b 100644
function DataRow(x) {
let index = 7
let length
-@@ -533,13 +809,26 @@
+@@ -533,13 +811,26 @@
}
function ReadyForQuery(x) {
@@ -501,7 +503,7 @@ index 07f6716..222249b 100644
if (errorResponse) {
+ // GBrain: a failed statement describes again next time instead of trusting shared parameter types.
+ query.sharedTypes && options.shared_types.delete(query.typesKey)
-+ errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
++ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
- : query.prepared && retryRoutines.has(errorResponse.routine)
@@ -515,7 +517,7 @@ index 07f6716..222249b 100644
} else {
query.resolve(results || result)
}
-@@ -547,9 +836,16 @@
+@@ -547,9 +838,16 @@
errored(errorResponse)
}
@@ -532,7 +534,7 @@ index 07f6716..222249b 100644
if (initial) {
if (target_session_attrs) {
-@@ -559,28 +855,54 @@
+@@ -559,28 +857,54 @@
return terminate()
}
@@ -593,7 +595,7 @@ index 07f6716..222249b 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,7 +952,11 @@
+@@ -630,7 +954,11 @@
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
@@ -605,7 +607,7 @@ index 07f6716..222249b 100644
}
function RowDescription(x) {
-@@ -767,15 +1093,23 @@
+@@ -767,15 +1095,23 @@
async function fetchArrayTypes() {
needsTypes = false
@@ -637,7 +639,7 @@ index 07f6716..222249b 100644
}
function addArrayType(oid, typarray) {
-@@ -821,7 +1155,16 @@
+@@ -821,7 +1157,16 @@
function retry(q, error) {
delete statements[q.signature]
q.retried = error
@@ -655,7 +657,7 @@ index 07f6716..222249b 100644
}
function NotificationResponse(x) {
-@@ -1039,6 +1382,59 @@
+@@ -1039,6 +1384,59 @@
return buffer
}
@@ -1293,7 +1295,7 @@ index 0578284..e80a868 100644
return '$' + (types.push(
diff --git a/src/connection.js b/vendor/postgres/src/connection.js
-index 1b1cccd..084ac14 100644
+index 1b1cccd..c5130e8 100644
--- a/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -20,6 +20,7 @@
@@ -1304,7 +1306,7 @@ index 1b1cccd..084ac14 100644
, noop = () => { /* noop */ }
const retryRoutines = new Set([
-@@ -28,6 +29,13 @@
+@@ -28,6 +29,15 @@
'transformAssignedExpr'
])
@@ -1312,13 +1314,15 @@ index 1b1cccd..084ac14 100644
+// table it reads with SELECT * or RETURNING *) fails on every connection that prepared it. Stock postgres.js forgets it
+// only on the connection that failed, so each pooled connection failed once, and inside a transaction the caller saw
+// the failure. The first one in the process starts a new plan generation: each connection drops its prepared
-+// statements before it builds its next query, and prepares them again.
++// statements before it builds its next query, and prepares them again. Only a statement this connection had cached
++// starts one: a fresh statement that fails this way (a pooler mapping it onto an older server-side statement) is not
++// healed by preparing again.
+let planGeneration = 0
+
const errorFields = {
83 : 'severity_local', // S
86 : 'severity', // V
-@@ -49,7 +57,7 @@
+@@ -49,7 +59,7 @@
82 : 'routine' // R
}
@@ -1327,7 +1331,7 @@ index 1b1cccd..084ac14 100644
const {
sslnegotiation,
ssl,
-@@ -64,6 +72,7 @@
+@@ -64,6 +74,7 @@
onnotify,
onparameter,
max_pipeline,
@@ -1335,7 +1339,7 @@ index 1b1cccd..084ac14 100644
keep_alive,
backoff,
target_session_attrs
-@@ -75,9 +84,14 @@
+@@ -75,9 +86,14 @@
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
@@ -1350,7 +1354,7 @@ index 1b1cccd..084ac14 100644
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
-@@ -86,6 +100,7 @@
+@@ -86,6 +102,7 @@
, statements = {}
, statementId = Math.random().toString(36).slice(2)
, statementCount = 1
@@ -1358,7 +1362,7 @@ index 1b1cccd..084ac14 100644
, closedTime = 0
, remaining = 0
, hostIndex = 0
-@@ -95,6 +110,9 @@
+@@ -95,6 +112,9 @@
, rows = 0
, serverSignature = null
, nextWriteTimer = null
@@ -1368,7 +1372,7 @@ index 1b1cccd..084ac14 100644
, terminated = false
, incomings = null
, results = null
-@@ -105,11 +123,19 @@
+@@ -105,11 +125,19 @@
, ended = null
, nonce = null
, query = null
@@ -1388,7 +1392,7 @@ index 1b1cccd..084ac14 100644
connect(query) {
initial = query
reconnect()
-@@ -143,11 +169,13 @@
+@@ -143,11 +171,13 @@
}
async function cancel({ pid, secret }, resolve, reject) {
@@ -1404,7 +1408,7 @@ index 1b1cccd..084ac14 100644
} catch (error) {
reject(error)
}
-@@ -163,22 +191,174 @@
+@@ -163,22 +193,174 @@
if (q.cancelled)
return
@@ -1585,7 +1589,7 @@ index 1b1cccd..084ac14 100644
}
}
-@@ -232,13 +412,19 @@
+@@ -232,13 +414,19 @@
q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)
q.string = string
q.signature = q.prepare && types + string
@@ -1607,7 +1611,7 @@ index 1b1cccd..084ac14 100644
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
-@@ -295,10 +481,11 @@
+@@ -295,10 +483,11 @@
/* c8 ignore next 3 */
function drain() {
@@ -1620,7 +1624,7 @@ index 1b1cccd..084ac14 100644
if (incomings) {
incomings.push(x)
remaining -= x.length
-@@ -330,6 +517,9 @@
+@@ -330,6 +519,9 @@
remaining = 0
incomings = null
}
@@ -1630,7 +1634,7 @@ index 1b1cccd..084ac14 100644
}
async function connect() {
-@@ -366,6 +556,7 @@
+@@ -366,6 +558,7 @@
try {
statements = {}
needsTypes = options.fetch_types
@@ -1638,7 +1642,7 @@ index 1b1cccd..084ac14 100644
statementId = Math.random().toString(36).slice(2)
statementCount = 1
lifeTimer.start()
-@@ -379,20 +570,35 @@
+@@ -379,20 +572,35 @@
}
function error(err) {
@@ -1674,7 +1678,7 @@ index 1b1cccd..084ac14 100644
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
-@@ -437,20 +643,53 @@
+@@ -437,20 +645,53 @@
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
@@ -1730,7 +1734,7 @@ index 1b1cccd..084ac14 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -459,6 +698,10 @@
+@@ -459,6 +700,10 @@
/* Handlers */
function handle(xs, x = xs[0]) {
@@ -1741,7 +1745,7 @@ index 1b1cccd..084ac14 100644
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
-@@ -489,6 +732,39 @@
+@@ -489,6 +734,39 @@
)(xs)
}
@@ -1781,7 +1785,7 @@ index 1b1cccd..084ac14 100644
function DataRow(x) {
let index = 7
let length
-@@ -533,13 +809,26 @@
+@@ -533,13 +811,26 @@
}
function ReadyForQuery(x) {
@@ -1795,7 +1799,7 @@ index 1b1cccd..084ac14 100644
if (errorResponse) {
+ // GBrain: a failed statement describes again next time instead of trusting shared parameter types.
+ query.sharedTypes && options.shared_types.delete(query.typesKey)
-+ errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
++ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
- : query.prepared && retryRoutines.has(errorResponse.routine)
@@ -1809,7 +1813,7 @@ index 1b1cccd..084ac14 100644
} else {
query.resolve(results || result)
}
-@@ -547,9 +836,16 @@
+@@ -547,9 +838,16 @@
errored(errorResponse)
}
@@ -1826,7 +1830,7 @@ index 1b1cccd..084ac14 100644
if (initial) {
if (target_session_attrs) {
-@@ -559,28 +855,54 @@
+@@ -559,28 +857,54 @@
return terminate()
}
@@ -1887,7 +1891,7 @@ index 1b1cccd..084ac14 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,7 +952,11 @@
+@@ -630,7 +954,11 @@
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
@@ -1899,7 +1903,7 @@ index 1b1cccd..084ac14 100644
}
function RowDescription(x) {
-@@ -767,15 +1093,23 @@
+@@ -767,15 +1095,23 @@
async function fetchArrayTypes() {
needsTypes = false
@@ -1931,7 +1935,7 @@ index 1b1cccd..084ac14 100644
}
function addArrayType(oid, typarray) {
-@@ -821,7 +1155,16 @@
+@@ -821,7 +1157,16 @@
function retry(q, error) {
delete statements[q.signature]
q.retried = error
@@ -1949,7 +1953,7 @@ index 1b1cccd..084ac14 100644
}
function NotificationResponse(x) {
-@@ -1039,6 +1382,59 @@
+@@ -1039,6 +1384,59 @@
return buffer
}
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index 4bf57e47cf..d08adf5e9c 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -3,6 +3,12 @@ import { setTimeout as delay } from 'node:timers/promises';
import { markNotAdmitted, OperationError, opError } from '../ops/contract.ts';
import { getCode, isConnectionLoss, isStalePlanError } from '../retry-matcher.ts';
+/**
+ * GST-2260: how many times an admission a stale plan aborted is re-run. The first failure makes every pooled connection
+ * prepare again, so one re-run is normally enough; a few more cover migrations that change the same table one after
+ * another. A stale plan that keeps coming back (a pooler that maps statements onto an older server-side one) rethrows.
+ */
+export const STALE_PLAN_RETRIES = 3;
/** #6355: how many times an admission attempt is re-run after the session dropped under it, and the pauses before each re-run. */
export const CONNECTION_LOSS_RETRY_MS = [100, 300, 900] as const;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -36,6 +42,7 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
recover?: (error: unknown) => Promise<void>): Promise<T> {
const deadline = performance.now() + budgetMs;
let lost = 0;
+ let stale = 0;
for (;;) {
try {
return await attempt(Math.max(1, Math.floor(deadline - performance.now())));
@@ -50,7 +57,7 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
await recover?.(error).catch(() => undefined);
continue;
}
- if (!['40001', '40P01', '55P03', '57014'].includes(code ?? '') && !isStalePlanError(error)) throw error;
+ if (isStalePlanError(error) ? ++stale > STALE_PLAN_RETRIES : !['40001', '40P01', '55P03', '57014'].includes(code ?? '')) throw error;
const remaining = deadline - performance.now();
if (remaining <= 25) {
const unavailable = new OperationError('storage_error', 'Write admission is temporarily blocked by database contention.',
diff --git a/test/stale-plan-heal.test.ts b/test/stale-plan-heal.test.ts
index f324ba6406..2d3e1b733b 100644
--- a/test/stale-plan-heal.test.ts
+++ b/test/stale-plan-heal.test.ts
@@ -19,7 +19,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import postgres from '#postgres';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
-import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';
+import { retryWriteAdmission, STALE_PLAN_RETRIES } from '../src/core/persistence/admission-retry.ts';
import { transientDatabaseFailure } from '../src/core/persistence/coordinator.ts';
import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
import { sqlQueryForEngine } from '../src/core/sql-query.ts';
@@ -43,6 +43,23 @@ const CHANGES = [
['DROP COLUMN', (t: string, step: number) => `ALTER TABLE ${t} DROP COLUMN ${step ? 'note' : 'spare'}`],
] as const;
+describe('write admission and a stale plan that keeps coming back (GST-2260)', () => {
+ test('it is re-run a bounded number of times and then rethrown as it was, never reported as contention', async () => {
+ const stalePlan = Object.assign(new Error('cached plan must not change result type'), { code: '0A000', routine: 'RevalidateCachedQuery' });
+ let attempts = 0;
+ const thrown = await caught(retryWriteAdmission(randomUUID(), async () => { attempts++; throw stalePlan; }, 5000));
+ expect(thrown).toBe(stalePlan);
+ expect(attempts).toBe(STALE_PLAN_RETRIES + 1);
+ });
+
+ test('another 0A000 is not a stale plan and is not retried', async () => {
+ const unsupported = Object.assign(new Error('FOR SHARE is not allowed with aggregate functions'), { code: '0A000', routine: 'CheckSelectLocking' });
+ let attempts = 0;
+ expect(await caught(retryWriteAdmission(randomUUID(), async () => { attempts++; throw unsupported; }, 5000))).toBe(unsupported);
+ expect(attempts).toBe(1);
+ });
+});
+
describe.skipIf(!url)('a prepared SELECT * after another connection changes its table (GST-2260)', () => {
let admin: ReturnType<typeof postgres>;
const engines: PostgresEngine[] = [];
diff --git a/vendor/README.md b/vendor/README.md
index 88da88d897..116c3fa2de 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -153,8 +153,11 @@ already aborted, so each pooled connection failed once. With the patch the
first such error starts a new process-wide plan generation, and each
connection drops its prepared statements before it builds its next query (the
server-side statements stay until the connection closes; new ones take new
-names). A `prepare: false` pool keeps no prepared statements, so nothing
-changes there. GBrain's write retry loops treat the aborted transaction as
+names). Only a statement the connection had cached starts a generation: a
+fresh statement that fails this way means a pooler (PgBouncer with
+`max_prepared_statements`) mapped it onto an older server-side statement,
+which preparing again cannot heal. A `prepare: false` pool keeps no prepared
+statements, so nothing changes there. GBrain's write retry loops treat the aborted transaction as
transient (`isStalePlanError` in `src/core/retry-matcher.ts`;
`test/stale-plan-heal.test.ts`).
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index 4c661265f6..43312ff0cd 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -35,7 +35,9 @@ const retryRoutines = new Set([
// table it reads with SELECT * or RETURNING *) fails on every connection that prepared it. Stock postgres.js forgets it
// only on the connection that failed, so each pooled connection failed once, and inside a transaction the caller saw
// the failure. The first one in the process starts a new plan generation: each connection drops its prepared
-// statements before it builds its next query, and prepares them again.
+// statements before it builds its next query, and prepares them again. Only a statement this connection had cached
+// starts one: a fresh statement that fails this way (a pooler mapping it onto an older server-side statement) is not
+// healed by preparing again.
let planGeneration = 0
const errorFields = {
@@ -821,7 +823,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
query.sharedTypes && options.shared_types.delete(query.typesKey)
- errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
+ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index 222249b912..1c709f4b45 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -33,7 +33,9 @@ const retryRoutines = new Set([
// table it reads with SELECT * or RETURNING *) fails on every connection that prepared it. Stock postgres.js forgets it
// only on the connection that failed, so each pooled connection failed once, and inside a transaction the caller saw
// the failure. The first one in the process starts a new plan generation: each connection drops its prepared
-// statements before it builds its next query, and prepares them again.
+// statements before it builds its next query, and prepares them again. Only a statement this connection had cached
+// starts one: a fresh statement that fails this way (a pooler mapping it onto an older server-side statement) is not
+// healed by preparing again.
let planGeneration = 0
const errorFields = {
@@ -819,7 +821,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
query.sharedTypes && options.shared_types.delete(query.typesKey)
- errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
+ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index 084ac14e51..c5130e84e8 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -33,7 +33,9 @@ const retryRoutines = new Set([
// table it reads with SELECT * or RETURNING *) fails on every connection that prepared it. Stock postgres.js forgets it
// only on the connection that failed, so each pooled connection failed once, and inside a transaction the caller saw
// the failure. The first one in the process starts a new plan generation: each connection drops its prepared
-// statements before it builds its next query, and prepares them again.
+// statements before it builds its next query, and prepares them again. Only a statement this connection had cached
+// starts one: a fresh statement that fails this way (a pooler mapping it onto an older server-side statement) is not
+// healed by preparing again.
let planGeneration = 0
const errorFields = {
@@ -819,7 +821,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
query.sharedTypes && options.shared_types.delete(query.typesKey)
- errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
+ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled