Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep a statement described before a plan generation out of the new one, and narrow the OAuth retry

garrytan4930166cddd6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4be5ec6db8..90b6b24de6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,14 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**A running `gbrain serve`, worker or autopilot no longer fails writes after another process changes a table's columns (GST-2260).** When `gbrain apply-migrations` or an upgrade in another process added, renamed or dropped a column, every pooled connection that had already prepared a `SELECT *` or `RETURNING *` on that table failed its next run with "cached plan must not change result type". Outside a transaction the driver quietly prepared the statement again, but inside one the error had already aborted the transaction, so the caller saw it: a `put_page` came back `internal_error`, or was accepted and then failed at publication, once for each statement on each pooled connection. Now the first such error makes every connection in the process prepare its statements again before its next query, the write paths re-run the transaction it aborted, and so do an OAuth token grant and a minion job's completion or failure record. Pools that do not prepare statements (transaction-mode pooler URLs, `prepare: false`) and PGLite are unchanged.
+**A running `gbrain serve`, worker or autopilot no longer fails writes after another process changes a table's columns (GST-2260).** When `gbrain apply-migrations` or an upgrade in another process added, renamed or dropped a column, every pooled connection that had already prepared a `SELECT *` or `RETURNING *` on that table failed its next run with "cached plan must not change result type". Outside a transaction the driver quietly prepared the statement again, but inside one the error had already aborted the transaction, so the caller saw it: a `put_page` came back `internal_error`, or was accepted and then failed at publication, once for each statement on each pooled connection. Now the first such error makes every connection in the process prepare its statements again before its next query, the write paths re-run the transaction it aborted, and so do an OAuth token grant whose client read meets it and a minion job's completion or failure record. Pools that do not prepare statements (transaction-mode pooler URLs, `prepare: false`) and PGLite are unchanged.
### Itemized changes
-- `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.
+- `vendor/postgres` (`patches/[email protected]`): the first `RevalidateCachedQuery` error on a statement a connection had cached starts a process-wide plan generation; each connection drops its prepared statements before it builds its next query, and a statement described under an older generation is not cached in the new one.
- `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 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.
+- `src/core/oauth-grants.ts`: the client-locked OAuth grant transaction runs once more when a stale plan fails its opening client read, before the callback writes anything.
+- `src/core/minions/queue.ts`: `completeJob` and `failJob`, whose transactions do only database work, run once more after a stale plan.
- Tests: `test/stale-plan-heal.test.ts` (Postgres; listed in `test/postgres-unit-arms.txt`).
## [0.60.627.0] - 2026-11-09
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 838e1d95f3..830423a89f 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/guardrails.ts` — vendor-neutral content guardrail seams (`registerGuardrailProvider`, `classify`). `loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })` accepts ONLY an absolute path or a `~/` path for `GBRAIN_GUARDRAILS_MODULE`; cwd-relative specs (`./`, `../`, bare `.`) and bare package specifiers (`pkg`, `@scope/pkg`, `pkg/sub` — in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout's `node_modules/<name>/` would load) throw `GuardrailLoadError` before any import, and when `env` is `process.env` (or `opts.cwd` is given) a spec that a cwd .env file assigns is refused via `cwdDotenvAssignsKey` (message composed from env-trust's `CWD_DOTENV_REMEDIATION`) unless `opts.skipCwdCheck` (preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned by `test/guardrails.test.ts` + `test/guardrails-env-load.test.ts`.
-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. #6202 first-consent source choice: `begin()` marks a request `sourceChoice.editable` only for a self-registered client's first consent (`registered_via='dcr'`, set by the DCR insert and by migration `oauth_client_registered_via` as a nullable column; `grant_revision = 0`; no `client_credentials`; a source grant) and offers the active sources; `decide(id, approve, choice?)` refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request calls `recordFirstConsentInTransaction` (`grants/service.ts`) inside the locked transaction before the code insert: revision 0 → 1 with an `action='consent'`, `actor='owner'` audit row even for an unchanged source, the final source share-locked and required active on every first consent, changed or not (a `GrantError` maps to 409 `client_policy_changed`, request terminal). `registered_via` is part of `policyDigest`. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions (the POST body allows `source_id` only as a string on `approve`; any other key or shape is 403 `invalid_consent`), and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) and `source_id` is posted only when it differs from the current source. GST-2260: `locked()` runs its transaction once more when a stale plan (`isStalePlanError`, `retryOnStalePlan` in `retry-matcher.ts`) aborted it, since every callback is database work only (`test/stale-plan-heal.test.ts`). Tests: `test/oauth-owner-consent.test.ts`, `test/oauth-consent-security.test.ts`, `test/oauth-client-registered-via-migration.test.ts`, `test/e2e/oauth-owner-consent-source-postgres.test.ts`, `test/e2e/oauth-client-registered-via-postgres.test.ts`, `admin/e2e/admin.pw.ts`.
+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. #6202 first-consent source choice: `begin()` marks a request `sourceChoice.editable` only for a self-registered client's first consent (`registered_via='dcr'`, set by the DCR insert and by migration `oauth_client_registered_via` as a nullable column; `grant_revision = 0`; no `client_credentials`; a source grant) and offers the active sources; `decide(id, approve, choice?)` refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request calls `recordFirstConsentInTransaction` (`grants/service.ts`) inside the locked transaction before the code insert: revision 0 → 1 with an `action='consent'`, `actor='owner'` audit row even for an unchanged source, the final source share-locked and required active on every first consent, changed or not (a `GrantError` maps to 409 `client_policy_changed`, request terminal). `registered_via` is part of `policyDigest`. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions (the POST body allows `source_id` only as a string on `approve`; any other key or shape is 403 `invalid_consent`), and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) and `source_id` is posted only when it differs from the current source. GST-2260: `locked()` runs its transaction once more when a stale plan (`isStalePlanError` in `retry-matcher.ts`) aborted its opening client read, which comes before the callback writes anything, so it is safe even under a non-transactional caller (mcp-provision) (`test/stale-plan-heal.test.ts`). Tests: `test/oauth-owner-consent.test.ts`, `test/oauth-consent-security.test.ts`, `test/oauth-client-registered-via-migration.test.ts`, `test/e2e/oauth-owner-consent-source-postgres.test.ts`, `test/e2e/oauth-client-registered-via-postgres.test.ts`, `admin/e2e/admin.pw.ts`.
- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant through `resolveTokenGrant` (`src/core/grants/legacy-token.ts`, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read; `[]` takes-holders preserved as explicit deny-all, NULL → the `/mcp` dispatch site's fail-closed `['world']`). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).
diff --git a/patches/[email protected] b/patches/[email protected]
index b3ae640b62..541830eac1 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..1c709f4 100644
+index 07f6716..848e9e5 100644
--- a/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -20,6 +20,7 @@
@@ -10,7 +10,7 @@ index 07f6716..1c709f4 100644
, noop = () => { /* noop */ }
const retryRoutines = new Set([
-@@ -28,6 +29,15 @@
+@@ -28,6 +29,16 @@
'transformAssignedExpr'
])
@@ -19,14 +19,15 @@ index 07f6716..1c709f4 100644
+// 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. 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.
++// in the current generation starts one: not one already in flight when another connection started it, and not a
++// fresh statement that fails this way (a pooler mapping it onto an older server-side statement), which preparing
++// again cannot heal.
+let planGeneration = 0
+
const errorFields = {
83 : 'severity_local', // S
86 : 'severity', // V
-@@ -49,7 +59,7 @@
+@@ -49,7 +60,7 @@
82 : 'routine' // R
}
@@ -35,7 +36,7 @@ index 07f6716..1c709f4 100644
const {
sslnegotiation,
ssl,
-@@ -64,6 +74,7 @@
+@@ -64,6 +75,7 @@
onnotify,
onparameter,
max_pipeline,
@@ -43,7 +44,7 @@ index 07f6716..1c709f4 100644
keep_alive,
backoff,
target_session_attrs
-@@ -75,9 +86,14 @@
+@@ -75,9 +87,14 @@
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
@@ -58,7 +59,7 @@ index 07f6716..1c709f4 100644
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
-@@ -86,6 +102,7 @@
+@@ -86,6 +103,7 @@
, statements = {}
, statementId = Math.random().toString(36).slice(2)
, statementCount = 1
@@ -66,7 +67,7 @@ index 07f6716..1c709f4 100644
, closedTime = 0
, remaining = 0
, hostIndex = 0
-@@ -95,6 +112,9 @@
+@@ -95,6 +113,9 @@
, rows = 0
, serverSignature = null
, nextWriteTimer = null
@@ -76,7 +77,7 @@ index 07f6716..1c709f4 100644
, terminated = false
, incomings = null
, results = null
-@@ -105,11 +125,19 @@
+@@ -105,11 +126,19 @@
, ended = null
, nonce = null
, query = null
@@ -96,7 +97,7 @@ index 07f6716..1c709f4 100644
connect(query) {
initial = query
reconnect()
-@@ -143,11 +171,13 @@
+@@ -143,11 +172,13 @@
}
async function cancel({ pid, secret }, resolve, reject) {
@@ -112,7 +113,7 @@ index 07f6716..1c709f4 100644
} catch (error) {
reject(error)
}
-@@ -163,22 +193,174 @@
+@@ -163,22 +194,174 @@
if (q.cancelled)
return
@@ -293,11 +294,12 @@ index 07f6716..1c709f4 100644
}
}
-@@ -232,13 +414,19 @@
+@@ -232,13 +415,20 @@
q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)
q.string = string
q.signature = q.prepare && types + string
+ statementGeneration !== planGeneration && (statements = {}, statementGeneration = planGeneration)
++ q.generation = statementGeneration
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -315,7 +317,7 @@ index 07f6716..1c709f4 100644
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
-@@ -295,10 +483,11 @@
+@@ -295,10 +485,11 @@
/* c8 ignore next 3 */
function drain() {
@@ -328,7 +330,7 @@ index 07f6716..1c709f4 100644
if (incomings) {
incomings.push(x)
remaining -= x.length
-@@ -330,6 +519,9 @@
+@@ -330,6 +521,9 @@
remaining = 0
incomings = null
}
@@ -338,7 +340,7 @@ index 07f6716..1c709f4 100644
}
async function connect() {
-@@ -366,6 +558,7 @@
+@@ -366,6 +560,7 @@
try {
statements = {}
needsTypes = options.fetch_types
@@ -346,7 +348,7 @@ index 07f6716..1c709f4 100644
statementId = Math.random().toString(36).slice(2)
statementCount = 1
lifeTimer.start()
-@@ -379,20 +572,35 @@
+@@ -379,20 +574,35 @@
}
function error(err) {
@@ -382,7 +384,7 @@ index 07f6716..1c709f4 100644
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
-@@ -437,20 +645,53 @@
+@@ -437,20 +647,53 @@
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
@@ -438,7 +440,7 @@ index 07f6716..1c709f4 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -459,6 +700,10 @@
+@@ -459,6 +702,10 @@
/* Handlers */
function handle(xs, x = xs[0]) {
@@ -449,7 +451,7 @@ index 07f6716..1c709f4 100644
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
-@@ -489,6 +734,39 @@
+@@ -489,6 +736,39 @@
)(xs)
}
@@ -489,7 +491,7 @@ index 07f6716..1c709f4 100644
function DataRow(x) {
let index = 7
let length
-@@ -533,13 +811,26 @@
+@@ -533,13 +813,26 @@
}
function ReadyForQuery(x) {
@@ -503,7 +505,7 @@ index 07f6716..1c709f4 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)
-+ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
++ query.prepared && query.generation === planGeneration && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
- : query.prepared && retryRoutines.has(errorResponse.routine)
@@ -517,7 +519,7 @@ index 07f6716..1c709f4 100644
} else {
query.resolve(results || result)
}
-@@ -547,9 +838,16 @@
+@@ -547,9 +840,16 @@
errored(errorResponse)
}
@@ -534,7 +536,7 @@ index 07f6716..1c709f4 100644
if (initial) {
if (target_session_attrs) {
-@@ -559,28 +857,54 @@
+@@ -559,28 +859,54 @@
return terminate()
}
@@ -595,10 +597,13 @@ index 07f6716..1c709f4 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,7 +954,11 @@
+@@ -629,8 +955,13 @@
+ for (let i = 0; i < length; ++i)
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
- query.prepare && (statements[query.signature] = query.statement)
+- query.prepare && (statements[query.signature] = query.statement)
++ // GBrain (GST-2260): a statement built before this connection's plan generation moved stays out of its new map.
++ query.prepare && query.generation === statementGeneration && (statements[query.signature] = query.statement)
+ // GBrain: only built-in parameter types are shared; a database's own types may be recreated under a new oid.
+ query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
+ && options.shared_types.set(query.typesKey, query.statement.types.slice())
@@ -607,7 +612,7 @@ index 07f6716..1c709f4 100644
}
function RowDescription(x) {
-@@ -767,15 +1095,23 @@
+@@ -767,15 +1098,23 @@
async function fetchArrayTypes() {
needsTypes = false
@@ -639,7 +644,7 @@ index 07f6716..1c709f4 100644
}
function addArrayType(oid, typarray) {
-@@ -821,7 +1157,16 @@
+@@ -821,7 +1160,16 @@
function retry(q, error) {
delete statements[q.signature]
q.retried = error
@@ -657,7 +662,7 @@ index 07f6716..1c709f4 100644
}
function NotificationResponse(x) {
-@@ -1039,6 +1384,59 @@
+@@ -1039,6 +1387,59 @@
return buffer
}
@@ -1295,7 +1300,7 @@ index 0578284..e80a868 100644
return '$' + (types.push(
diff --git a/src/connection.js b/vendor/postgres/src/connection.js
-index 1b1cccd..c5130e8 100644
+index 1b1cccd..64f43ba 100644
--- a/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -20,6 +20,7 @@
@@ -1306,7 +1311,7 @@ index 1b1cccd..c5130e8 100644
, noop = () => { /* noop */ }
const retryRoutines = new Set([
-@@ -28,6 +29,15 @@
+@@ -28,6 +29,16 @@
'transformAssignedExpr'
])
@@ -1315,14 +1320,15 @@ index 1b1cccd..c5130e8 100644
+// 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. 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.
++// in the current generation starts one: not one already in flight when another connection started it, and not a
++// fresh statement that fails this way (a pooler mapping it onto an older server-side statement), which preparing
++// again cannot heal.
+let planGeneration = 0
+
const errorFields = {
83 : 'severity_local', // S
86 : 'severity', // V
-@@ -49,7 +59,7 @@
+@@ -49,7 +60,7 @@
82 : 'routine' // R
}
@@ -1331,7 +1337,7 @@ index 1b1cccd..c5130e8 100644
const {
sslnegotiation,
ssl,
-@@ -64,6 +74,7 @@
+@@ -64,6 +75,7 @@
onnotify,
onparameter,
max_pipeline,
@@ -1339,7 +1345,7 @@ index 1b1cccd..c5130e8 100644
keep_alive,
backoff,
target_session_attrs
-@@ -75,9 +86,14 @@
+@@ -75,9 +87,14 @@
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
@@ -1354,7 +1360,7 @@ index 1b1cccd..c5130e8 100644
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
-@@ -86,6 +102,7 @@
+@@ -86,6 +103,7 @@
, statements = {}
, statementId = Math.random().toString(36).slice(2)
, statementCount = 1
@@ -1362,7 +1368,7 @@ index 1b1cccd..c5130e8 100644
, closedTime = 0
, remaining = 0
, hostIndex = 0
-@@ -95,6 +112,9 @@
+@@ -95,6 +113,9 @@
, rows = 0
, serverSignature = null
, nextWriteTimer = null
@@ -1372,7 +1378,7 @@ index 1b1cccd..c5130e8 100644
, terminated = false
, incomings = null
, results = null
-@@ -105,11 +125,19 @@
+@@ -105,11 +126,19 @@
, ended = null
, nonce = null
, query = null
@@ -1392,7 +1398,7 @@ index 1b1cccd..c5130e8 100644
connect(query) {
initial = query
reconnect()
-@@ -143,11 +171,13 @@
+@@ -143,11 +172,13 @@
}
async function cancel({ pid, secret }, resolve, reject) {
@@ -1408,7 +1414,7 @@ index 1b1cccd..c5130e8 100644
} catch (error) {
reject(error)
}
-@@ -163,22 +193,174 @@
+@@ -163,22 +194,174 @@
if (q.cancelled)
return
@@ -1589,11 +1595,12 @@ index 1b1cccd..c5130e8 100644
}
}
-@@ -232,13 +414,19 @@
+@@ -232,13 +415,20 @@
q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)
q.string = string
q.signature = q.prepare && types + string
+ statementGeneration !== planGeneration && (statements = {}, statementGeneration = planGeneration)
++ q.generation = statementGeneration
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -1611,7 +1618,7 @@ index 1b1cccd..c5130e8 100644
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
-@@ -295,10 +483,11 @@
+@@ -295,10 +485,11 @@
/* c8 ignore next 3 */
function drain() {
@@ -1624,7 +1631,7 @@ index 1b1cccd..c5130e8 100644
if (incomings) {
incomings.push(x)
remaining -= x.length
-@@ -330,6 +519,9 @@
+@@ -330,6 +521,9 @@
remaining = 0
incomings = null
}
@@ -1634,7 +1641,7 @@ index 1b1cccd..c5130e8 100644
}
async function connect() {
-@@ -366,6 +558,7 @@
+@@ -366,6 +560,7 @@
try {
statements = {}
needsTypes = options.fetch_types
@@ -1642,7 +1649,7 @@ index 1b1cccd..c5130e8 100644
statementId = Math.random().toString(36).slice(2)
statementCount = 1
lifeTimer.start()
-@@ -379,20 +572,35 @@
+@@ -379,20 +574,35 @@
}
function error(err) {
@@ -1678,7 +1685,7 @@ index 1b1cccd..c5130e8 100644
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
-@@ -437,20 +645,53 @@
+@@ -437,20 +647,53 @@
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
@@ -1734,7 +1741,7 @@ index 1b1cccd..c5130e8 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -459,6 +700,10 @@
+@@ -459,6 +702,10 @@
/* Handlers */
function handle(xs, x = xs[0]) {
@@ -1745,7 +1752,7 @@ index 1b1cccd..c5130e8 100644
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
-@@ -489,6 +734,39 @@
+@@ -489,6 +736,39 @@
)(xs)
}
@@ -1785,7 +1792,7 @@ index 1b1cccd..c5130e8 100644
function DataRow(x) {
let index = 7
let length
-@@ -533,13 +811,26 @@
+@@ -533,13 +813,26 @@
}
function ReadyForQuery(x) {
@@ -1799,7 +1806,7 @@ index 1b1cccd..c5130e8 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)
-+ query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
++ query.prepared && query.generation === planGeneration && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
- : query.prepared && retryRoutines.has(errorResponse.routine)
@@ -1813,7 +1820,7 @@ index 1b1cccd..c5130e8 100644
} else {
query.resolve(results || result)
}
-@@ -547,9 +838,16 @@
+@@ -547,9 +840,16 @@
errored(errorResponse)
}
@@ -1830,7 +1837,7 @@ index 1b1cccd..c5130e8 100644
if (initial) {
if (target_session_attrs) {
-@@ -559,28 +857,54 @@
+@@ -559,28 +859,54 @@
return terminate()
}
@@ -1891,10 +1898,13 @@ index 1b1cccd..c5130e8 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,7 +954,11 @@
+@@ -629,8 +955,13 @@
+ for (let i = 0; i < length; ++i)
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
- query.prepare && (statements[query.signature] = query.statement)
+- query.prepare && (statements[query.signature] = query.statement)
++ // GBrain (GST-2260): a statement built before this connection's plan generation moved stays out of its new map.
++ query.prepare && query.generation === statementGeneration && (statements[query.signature] = query.statement)
+ // GBrain: only built-in parameter types are shared; a database's own types may be recreated under a new oid.
+ query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
+ && options.shared_types.set(query.typesKey, query.statement.types.slice())
@@ -1903,7 +1913,7 @@ index 1b1cccd..c5130e8 100644
}
function RowDescription(x) {
-@@ -767,15 +1095,23 @@
+@@ -767,15 +1098,23 @@
async function fetchArrayTypes() {
needsTypes = false
@@ -1935,7 +1945,7 @@ index 1b1cccd..c5130e8 100644
}
function addArrayType(oid, typarray) {
-@@ -821,7 +1157,16 @@
+@@ -821,7 +1160,16 @@
function retry(q, error) {
delete statements[q.signature]
q.retried = error
@@ -1953,7 +1963,7 @@ index 1b1cccd..c5130e8 100644
}
function NotificationResponse(x) {
-@@ -1039,6 +1384,59 @@
+@@ -1039,6 +1387,59 @@
return buffer
}
diff --git a/src/core/oauth-grants.ts b/src/core/oauth-grants.ts
index 83a4a67a16..0b4af8472f 100644
--- a/src/core/oauth-grants.ts
+++ b/src/core/oauth-grants.ts
@@ -9,7 +9,7 @@ import { generateToken, hashToken } from './utils.ts';
import { hasScope, parseScopeString } from './scope.ts';
import { TOKEN_TTL_MAX_SECONDS, intersectGrantedScopes } from './grants/model.ts';
import { safeHexEqual } from './timing-safe.ts';
-import { retryOnStalePlan } from './retry-matcher.ts';
+import { isStalePlanError } from './retry-matcher.ts';
import { clientHoldsAuthorization, GrantError, recordFirstConsentInTransaction } from './grants/service.ts';
export type OAuthTransaction = <T>(fn: (sql: SqlQuery) => Promise<T>) => Promise<T>;
@@ -129,12 +129,21 @@ export class OAuthGrants {
private async locked<T>(clientId: string, fn: (sql: SqlQuery, row: ClientRow) => Promise<T>): Promise<T> {
const options = this.options;
if (!options.transaction) throw new ServerError('OAuth grant transactions are unavailable');
- // GST-2260: every caller's callback is database work only, so a transaction a stale plan aborted runs again.
- return retryOnStalePlan(() => options.transaction!(async sql => {
+ // GST-2260: a stale plan on the client read runs the transaction again. That read comes before the callback writes
+ // anything, so the second run is safe even when the caller's transaction is not a real one (mcp-provision).
+ let entered = false;
+ const run = () => options.transaction!(async sql => {
const [row] = await sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId} FOR UPDATE`;
+ entered = true;
assertActive(row);
return fn(sql, row);
- }));
+ });
+ try {
+ return await run();
+ } catch (error) {
+ if (entered || !isStalePlanError(error)) throw error;
+ return run();
+ }
}
private prune(): void {
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index d08adf5e9c..aea21b7708 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -60,6 +60,7 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
if (isStalePlanError(error) ? ++stale > STALE_PLAN_RETRIES : !['40001', '40P01', '55P03', '57014'].includes(code ?? '')) throw error;
const remaining = deadline - performance.now();
if (remaining <= 25) {
+ if (isStalePlanError(error)) throw error;
const unavailable = new OperationError('storage_error', 'Write admission is temporarily blocked by database contention.',
`Retry the same operation, arguments, and request_id ${requestId}. No queued receipt has been confirmed.`);
unavailable.writeError = 'storage_error';
diff --git a/test/stale-plan-heal.test.ts b/test/stale-plan-heal.test.ts
index 2d3e1b733b..6e1fde45bc 100644
--- a/test/stale-plan-heal.test.ts
+++ b/test/stale-plan-heal.test.ts
@@ -17,6 +17,8 @@
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
+import net from 'node:net';
+import type { AddressInfo } from 'node:net';
import postgres from '#postgres';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
import { retryWriteAdmission, STALE_PLAN_RETRIES } from '../src/core/persistence/admission-retry.ts';
@@ -114,6 +116,58 @@ describe.skipIf(!url)('a prepared SELECT * after another connection changes its
} finally { await unnamed.end({ timeout: 1 }); }
});
+ /** A TCP relay to the database that can hold the server's answers back, to deliver one connection's reply late. */
+ async function relay() {
+ const target = new URL(url!);
+ let held: Array<string | Buffer> | null = null;
+ let client: net.Socket | null = null;
+ const sockets: net.Socket[] = [];
+ const server = net.createServer(c => {
+ client = c;
+ const s = net.connect(Number(target.port || 5432), target.hostname);
+ sockets.push(c, s);
+ c.on('data', d => s.write(d));
+ s.on('data', d => { if (held) held.push(d); else c.write(d); });
+ c.on('close', () => s.destroy()); s.on('close', () => c.destroy());
+ c.on('error', () => {}); s.on('error', () => {});
+ });
+ const port = await new Promise<number>(resolve => server.listen(0, '127.0.0.1', () => resolve((server.address() as AddressInfo).port)));
+ const relayed = new URL(url!); relayed.hostname = '127.0.0.1'; relayed.port = String(port);
+ return {
+ url: relayed.toString(),
+ hold() { held = []; },
+ release() { const out = held ?? []; held = null; for (const d of out) client!.write(d); },
+ close() { for (const s of sockets) s.destroy(); server.close(); },
+ };
+ }
+
+ test('a statement described before the change but answered after the pool healed is not kept as prepared', async () => {
+ const { select, alter } = await setup(1, CHANGES[0][1]);
+ const types = new Map();
+ const late = await relay();
+ const a = postgres(url!, { max: 1, shared_types: types, onnotice: () => {} });
+ const b = postgres(late.url, { max: 1, shared_types: types, onnotice: () => {} });
+ try {
+ expect(Array.from(await a.unsafe(select, [1], { prepare: true }) as Iterable<{ id: number }>)[0]!.id).toBe(1);
+ await b.unsafe('SELECT 1');
+ late.hold();
+ const described = b.unsafe(select, [1], { prepare: true }).execute();
+ await new Promise(resolve => setTimeout(resolve, 300));
+ await alter();
+ expect(Array.from(await a.unsafe(select, [1], { prepare: true }) as Iterable<{ id: number }>)[0]!.id).toBe(1);
+ const unrelated = b.unsafe('SELECT 2 AS n').execute();
+ late.release();
+ await described;
+ await unrelated;
+ const inTx = await caught(b.begin(tx => tx.unsafe(select, [1], { prepare: true })));
+ expect(inTx).toBeNull();
+ } finally {
+ await a.end({ timeout: 1 });
+ await b.end({ timeout: 1 });
+ late.close();
+ }
+ });
+
for (const [name, change] of CHANGES) {
test(`${name}: the in-transaction stale-plan error is retryable and the admission loop re-runs it with no caller-visible error`, async () => {
const { inTx, alter } = await setup(1, change);
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index 43312ff0cd..d19c03034a 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -36,8 +36,9 @@ const retryRoutines = new Set([
// 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. 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.
+// in the current generation starts one: not one already in flight when another connection started it, and not a
+// fresh statement that fails this way (a pooler mapping it onto an older server-side statement), which preparing
+// again cannot heal.
let planGeneration = 0
const errorFields = {
@@ -417,6 +418,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.string = string
q.signature = q.prepare && types + string
statementGeneration !== planGeneration && (statements = {}, statementGeneration = planGeneration)
+ q.generation = statementGeneration
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -823,7 +825,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)
- query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
+ query.prepared && query.generation === planGeneration && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled
@@ -955,7 +957,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
for (let i = 0; i < length; ++i)
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
- query.prepare && (statements[query.signature] = query.statement)
+ // GBrain (GST-2260): a statement built before this connection's plan generation moved stays out of its new map.
+ query.prepare && query.generation === statementGeneration && (statements[query.signature] = query.statement)
// GBrain: only built-in parameter types are shared; a database's own types may be recreated under a new oid.
query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
&& options.shared_types.set(query.typesKey, query.statement.types.slice())
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index 1c709f4b45..848e9e52b4 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -34,8 +34,9 @@ const retryRoutines = new Set([
// 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. 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.
+// in the current generation starts one: not one already in flight when another connection started it, and not a
+// fresh statement that fails this way (a pooler mapping it onto an older server-side statement), which preparing
+// again cannot heal.
let planGeneration = 0
const errorFields = {
@@ -415,6 +416,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.string = string
q.signature = q.prepare && types + string
statementGeneration !== planGeneration && (statements = {}, statementGeneration = planGeneration)
+ q.generation = statementGeneration
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -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)
- query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
+ query.prepared && query.generation === planGeneration && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled
@@ -953,7 +955,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
for (let i = 0; i < length; ++i)
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
- query.prepare && (statements[query.signature] = query.statement)
+ // GBrain (GST-2260): a statement built before this connection's plan generation moved stays out of its new map.
+ query.prepare && query.generation === statementGeneration && (statements[query.signature] = query.statement)
// GBrain: only built-in parameter types are shared; a database's own types may be recreated under a new oid.
query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
&& options.shared_types.set(query.typesKey, query.statement.types.slice())
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index c5130e84e8..64f43ba180 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -34,8 +34,9 @@ const retryRoutines = new Set([
// 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. 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.
+// in the current generation starts one: not one already in flight when another connection started it, and not a
+// fresh statement that fails this way (a pooler mapping it onto an older server-side statement), which preparing
+// again cannot heal.
let planGeneration = 0
const errorFields = {
@@ -415,6 +416,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.string = string
q.signature = q.prepare && types + string
statementGeneration !== planGeneration && (statements = {}, statementGeneration = planGeneration)
+ q.generation = statementGeneration
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -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)
- query.prepared && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
+ query.prepared && query.generation === planGeneration && errorResponse.routine === 'RevalidateCachedQuery' && planGeneration++
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled
@@ -953,7 +955,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
for (let i = 0; i < length; ++i)
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
- query.prepare && (statements[query.signature] = query.statement)
+ // GBrain (GST-2260): a statement built before this connection's plan generation moved stays out of its new map.
+ query.prepare && query.generation === statementGeneration && (statements[query.signature] = query.statement)
// GBrain: only built-in parameter types are shared; a database's own types may be recreated under a new oid.
query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
&& options.shared_types.set(query.typesKey, query.statement.types.slice())