Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(postgres): one pg_type fetch per database per process; transaction pipelining on pooler URLs (#6930)

garrytan8b24c1514f87
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index a5b7df2548..506cab9b5a 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -3,8 +3,8 @@
[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`; 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`.
+- `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`). #6930: `array_types` hands every pool for one database target the array types the process's first connection fetched, so later connections skip the pg_type round trip; `transaction_pipeline` pipelines on a connection its owner holds (`sql.begin`, `sql.reserve`) while every statement in flight leaves it inside a transaction and never behind COMMIT/ROLLBACK/END/ABORT/PREPARE TRANSACTION, so a transaction-mode pooler URL (`max_pipeline` 0, `db.transactionPipelineOptions`, `GBRAIN_PG_TXN_PIPELINE=0` off) keeps #6543's boundary; pinned by `test/pathological/pg-round-trips-6930.test.ts` and `test/e2e/pgbouncer-transaction-pipeline-6930.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`. #6930: `sharedArrayTypes(url)` is the per-target, in-process-only `array_types` store (extension OIDs belong to one catalog); `GBRAIN_PG_TYPE_CACHE=0` turns it off and `clearSharedTypes` empties it.
- `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/src/core/connection-manager.ts b/src/core/connection-manager.ts
index f45a960dbc..907e881c7d 100644
--- a/src/core/connection-manager.ts
+++ b/src/core/connection-manager.ts
@@ -38,7 +38,7 @@
import postgres from '#postgres'
import { traceSqlOptions } from './sql-trace.ts';
-import { gbrainApplicationName, readPoolPipelineOptions, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';
+import { gbrainApplicationName, readPoolPipelineOptions, transactionPipelineOptions, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, resolveArrayTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
@@ -352,7 +352,9 @@ export class ConnectionManager {
types: { bigint: postgres.BigInt },
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
shared_types: resolveSharedTypes(this.opts.url),
+ array_types: resolveArrayTypes(this.opts.url),
...readPoolPipelineOptions(this.opts.url),
+ ...transactionPipelineOptions(this.opts.url),
};
const timeouts = resolveSessionTimeouts();
Object.assign(opts, poolHealthOptions({ ...this.opts.health?.('read'), onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status) }, timeouts.statement_timeout));
@@ -506,6 +508,7 @@ export class ConnectionManager {
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
...poolHealthOptions({ ...this.opts.health?.('direct'), onpoisoned: (status: string) => this.opts.onpoisoned?.('direct', status) }, String(DDL_STMT_TIMEOUT_MS)),
shared_types: resolveSharedTypes(this._directUrl),
+ array_types: resolveArrayTypes(this._directUrl),
// Apply DDL session GUCs as connection startup parameters (durable
// through any intermediary pooling layer, same trick as
// resolveSessionTimeouts).
diff --git a/src/core/db.ts b/src/core/db.ts
index a6f1126e69..82d28a321a 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -7,7 +7,7 @@ import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.t
import type { BrainEngine } from './engine.ts';
import { verifySchema } from './schema-verify.ts';
import { isConnectTimeoutError, isRetryableConnError } from './retry-matcher.ts';
-import { loadSharedParameterTypes, sharedParameterTypes, type SharedParameterTypes } from './pg-type-cache.ts';
+import { loadSharedParameterTypes, sharedArrayTypes, sharedParameterTypes, type SharedArrayTypes, type SharedParameterTypes } from './pg-type-cache.ts';
let sql: ReturnType<typeof postgres> | null = null;
let connectedUrl: string | null = null;
@@ -150,6 +150,21 @@ export function readPoolPipelineOptions(url: string): { max_pipeline?: number }
return value === null ? {} : { max_pipeline: value };
}
+/** Pipeline depth inside a transaction on a pool that does not pipeline across transactions (#6930). */
+export const TRANSACTION_PIPELINE_DEPTH = 100;
+
+/**
+ * #6930: a read-side pool that `resolveReadPoolPipeline` keeps from pipelining (a transaction-mode pooler) still
+ * pipelines the statements of one transaction on the connection its owner holds (sql.begin, sql.reserve): the pooler
+ * pins one server connection from BEGIN until the transaction ends, and the driver never sends a statement behind one
+ * that may end the transaction, so #6543's boundary stays closed. Prepared statements stay off (`resolvePrepare`).
+ * `GBRAIN_PG_TXN_PIPELINE=0` restores one round trip per statement.
+ */
+export function transactionPipelineOptions(url: string): { transaction_pipeline?: number } {
+ const off = process.env.GBRAIN_PG_TXN_PIPELINE === '0' || process.env.GBRAIN_PG_TXN_PIPELINE === 'false';
+ return !off && resolveReadPoolPipeline(url).value === 0 ? { transaction_pipeline: TRANSACTION_PIPELINE_DEPTH } : {};
+}
+
/**
* Seconds a pool waits for a connection before giving up with CONNECT_TIMEOUT
* when its URL names no `connect_timeout` of its own.
@@ -174,9 +189,17 @@ const MAX_CONNECT_TIMEOUT_S = Math.floor(0x7fffffff / 1000);
export function resolveSharedTypes(url?: string): SharedParameterTypes | false {
return sharedParameterTypes(url);
}
-/** Forgets the shared parameter types of these pools; a schema change may have changed them. */
+/** #6930: the array types every pool for this database target shares, so only the process's first connection fetches them. */
+export function resolveArrayTypes(url?: string): SharedArrayTypes | null {
+ return sharedArrayTypes(url);
+}
+/** Forgets the shared parameter and array types of these pools; a schema change may have changed them. */
export function clearSharedTypes(...pools: unknown[]): void {
- for (const pool of pools) (pool as { options?: { shared_types?: Map<string, number[]> | null } } | null)?.options?.shared_types?.clear();
+ for (const pool of pools) {
+ const options = (pool as { options?: { shared_types?: Map<string, number[]> | null; array_types?: SharedArrayTypes | null } } | null)?.options;
+ options?.shared_types?.clear();
+ if (options?.array_types) options.array_types.rows = null;
+ }
}
/**
@@ -517,7 +540,9 @@ export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {})
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
...poolHealthOptions(hooks, timeouts.statement_timeout),
shared_types: resolveSharedTypes(url),
+ array_types: resolveArrayTypes(url),
...readPoolPipelineOptions(url),
+ ...transactionPipelineOptions(url),
};
opts.connection = { ...timeouts, application_name: gbrainApplicationName() };
if (typeof prepare === 'boolean') {
diff --git a/src/core/pg-type-cache.ts b/src/core/pg-type-cache.ts
index 281a02877c..7621667ba1 100644
--- a/src/core/pg-type-cache.ts
+++ b/src/core/pg-type-cache.ts
@@ -166,7 +166,29 @@ export function loadSharedParameterTypes(url: string, serverVersion: string, sch
return added;
}
+/**
+ * #6930: the array types (`pg_type` element/array pairs, extension types included) the first connection to a
+ * database target fetched in this process. Every pool for that target shares the object, so later connections, of any
+ * pool, skip the pg_type round trip. Kept in this process only: extension type OIDs belong to one database's catalog.
+ * `GBRAIN_PG_TYPE_CACHE=0` turns it off (each connection fetches, the driver's stock behaviour).
+ */
+export interface SharedArrayTypes { rows: Array<[number, number]> | null }
+const arrayTypesByTarget = new Map<string, SharedArrayTypes>();
+
+export function sharedArrayTypes(url: string | undefined): SharedArrayTypes | null {
+ if (envOff('GBRAIN_PG_TYPE_CACHE')) return null;
+ if (!url) return { rows: null };
+ const target = typeCacheTarget(url);
+ let store = arrayTypesByTarget.get(target);
+ if (!store) {
+ store = { rows: null };
+ arrayTypesByTarget.set(target, store);
+ }
+ return store;
+}
+
export function _resetSharedParameterTypesForTests(): void {
for (const store of byTarget.values()) store.scope = null;
byTarget.clear();
+ arrayTypesByTarget.clear();
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 89819c9371..9e4fe37e49 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -423,7 +423,7 @@ export class PostgresEngine implements BrainEngine {
// GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
...db.poolHealthOptions({ ...this.poolHealth('read'), onpoisoned: (status: string) => this.onPoisoned('read', status) }, timeouts.statement_timeout),
- shared_types: db.resolveSharedTypes(url), ...db.readPoolPipelineOptions(url),
+ shared_types: db.resolveSharedTypes(url), array_types: db.resolveArrayTypes(url), ...db.readPoolPipelineOptions(url), ...db.transactionPipelineOptions(url),
};
opts.connection = { ...timeouts, application_name: db.gbrainApplicationName() };
if (typeof prepare === 'boolean') {