Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(postgres): share described parameter types across a pool's connections (#5984)

garrytan883f4d7f5c38
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index d351b643b2..dc891f4a5f 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`.
+- `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`.
- `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 d632b06116..e7dee3d8ff 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -1,5 +1,5 @@
diff --git a/cjs/src/connection.js b/cjs/src/connection.js
-index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124dbb94e18b 100644
+index 07f6716702ac888215c86ad6e0071aaf55ae519c..f6d76e59ab690dc0a92986f90ade8839bc0470d4 100644
--- a/cjs/src/connection.js
+++ b/cjs/src/connection.js
@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
@@ -42,7 +42,25 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
} catch (error) {
sent.length === 0 && write(Sync)
errored(error)
-@@ -295,7 +301,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -235,10 +241,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ q.onlyDescribe && (delete statements[q.signature])
+ q.parameters = q.parameters || parameters
+ q.prepared = q.prepare && q.signature in statements
+- q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)
++ // GBrain: a statement this pool already described on another connection reuses its parameter
++ // types, so it is parsed, described and executed in one pipelined message group (no describe first).
++ q.typesKey = options.shared_types && parameters.length && !q.onlyDescribe ? types + string : null
++ const shared = !q.prepared && q.typesKey && options.shared_types.get(q.typesKey)
++ q.sharedTypes = !!shared
++ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared && !shared)
+ q.statement = q.prepared
+ ? statements[q.signature]
+- : { string, types, name: q.prepare ? statementId + statementCount++ : '' }
++ : { string, types: shared ? shared.slice() : types, name: q.prepare ? statementId + statementCount++ : '' }
+
+ typeof options.debug === 'function' && options.debug(id, string, parameters, types)
+ }
+@@ -295,7 +306,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
/* c8 ignore next 3 */
function drain() {
@@ -51,7 +69,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
}
function data(x) {
-@@ -379,6 +385,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -379,6 +390,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function error(err) {
@@ -60,7 +78,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
if (connection.queue === queues.connecting && options.host[retries + 1])
return
-@@ -388,6 +396,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -388,6 +401,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function errored(err) {
@@ -69,7 +87,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
stream && (stream.destroy(err), stream = null)
query && queryError(query, err)
initial && (queryError(initial, err), initial = null)
-@@ -447,6 +457,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -447,6 +462,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
socket.removeAllListeners()
socket = null
@@ -81,15 +99,19 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
if (initial)
return reconnect()
-@@ -533,6 +548,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,8 +553,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
if (query) {
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.retried
-@@ -564,10 +580,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ ? errored(query.retried)
+ : query.prepared && retryRoutines.has(errorResponse.routine)
+@@ -564,10 +587,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -104,7 +126,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
-@@ -580,7 +598,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -580,7 +605,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
@@ -113,8 +135,18 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124d
: connection.reserved()
: ending
? terminate()
+@@ -630,6 +655,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
+
+ query.prepare && (statements[query.signature] = query.statement)
++ // 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())
+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
+ }
+
diff --git a/cjs/src/index.js b/cjs/src/index.js
-index f09c61c7e998f411560b95c9a8e1ed6a97972c11..c72e4135627296dd00179e30d02094d591047267 100644
+index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3e5eb9ff7 100644
--- a/cjs/src/index.js
+++ b/cjs/src/index.js
@@ -200,40 +200,134 @@ function Postgres(a, b) {
@@ -367,11 +399,12 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..c72e4135627296dd00179e30d02094d5
}
}
-@@ -491,6 +616,7 @@ function parseOptions(a, b) {
+@@ -491,6 +616,8 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
++ shared_types : o.shared_types === false ? null : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
@@ -432,7 +465,7 @@ index 8438f5da92cf7637d98a33491d75c75b1c817c25..c444310ff87b0ac81fd19cd3170a0ba6
const out = xs[index++]
diff --git a/src/connection.js b/src/connection.js
-index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641cb55178d0 100644
+index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..792c83d36a32b8181a438e0b0e91e0a7db8083ca 100644
--- a/src/connection.js
+++ b/src/connection.js
@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
@@ -475,7 +508,25 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
} catch (error) {
sent.length === 0 && write(Sync)
errored(error)
-@@ -295,7 +301,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -235,10 +241,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ q.onlyDescribe && (delete statements[q.signature])
+ q.parameters = q.parameters || parameters
+ q.prepared = q.prepare && q.signature in statements
+- q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)
++ // GBrain: a statement this pool already described on another connection reuses its parameter
++ // types, so it is parsed, described and executed in one pipelined message group (no describe first).
++ q.typesKey = options.shared_types && parameters.length && !q.onlyDescribe ? types + string : null
++ const shared = !q.prepared && q.typesKey && options.shared_types.get(q.typesKey)
++ q.sharedTypes = !!shared
++ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared && !shared)
+ q.statement = q.prepared
+ ? statements[q.signature]
+- : { string, types, name: q.prepare ? statementId + statementCount++ : '' }
++ : { string, types: shared ? shared.slice() : types, name: q.prepare ? statementId + statementCount++ : '' }
+
+ typeof options.debug === 'function' && options.debug(id, string, parameters, types)
+ }
+@@ -295,7 +306,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
/* c8 ignore next 3 */
function drain() {
@@ -484,7 +535,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
}
function data(x) {
-@@ -379,6 +385,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -379,6 +390,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function error(err) {
@@ -493,7 +544,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
if (connection.queue === queues.connecting && options.host[retries + 1])
return
-@@ -388,6 +396,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -388,6 +401,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function errored(err) {
@@ -502,7 +553,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
stream && (stream.destroy(err), stream = null)
query && queryError(query, err)
initial && (queryError(initial, err), initial = null)
-@@ -447,6 +457,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -447,6 +462,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
socket.removeAllListeners()
socket = null
@@ -514,15 +565,19 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
if (initial)
return reconnect()
-@@ -533,6 +548,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,8 +553,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
if (query) {
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.retried
-@@ -564,10 +580,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ ? errored(query.retried)
+ : query.prepared && retryRoutines.has(errorResponse.routine)
+@@ -564,10 +587,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -537,7 +592,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
-@@ -580,7 +598,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -580,7 +605,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
@@ -546,8 +601,18 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641c
: connection.reserved()
: ending
? terminate()
+@@ -630,6 +655,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
+
+ query.prepare && (statements[query.signature] = query.statement)
++ // 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())
+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
+ }
+
diff --git a/src/index.js b/src/index.js
-index c7fba3dace20173f4cb13f3f138bb6d213b43683..e9af339e13ee79e38d13fe82733ed17dc7529b46 100644
+index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda0c1ea466 100644
--- a/src/index.js
+++ b/src/index.js
@@ -200,40 +200,134 @@ function Postgres(a, b) {
@@ -800,11 +865,12 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..e9af339e13ee79e38d13fe82733ed17d
}
}
-@@ -491,6 +616,7 @@ function parseOptions(a, b) {
+@@ -491,6 +616,8 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
++ shared_types : o.shared_types === false ? null : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
@@ -865,10 +931,10 @@ index c4ef97164f057db99dce1b9af3401dbb1af37e31..8fba891b879e8f5c7fdb03ea05907536
const out = xs[index++]
diff --git a/types/index.d.ts b/types/index.d.ts
-index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..19103a998359c7277cd966c246cf245aedec4297 100644
+index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..d7ba214bc614097fddbf2951127c5685d7c8e643 100644
--- a/types/index.d.ts
+++ b/types/index.d.ts
-@@ -119,6 +119,11 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
+@@ -119,6 +119,18 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
*/
publications: string
onclose: (connId: number) => void;
@@ -877,10 +943,17 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..19103a998359c7277cd966c246cf245a
+ * reused because its ReadyForQuery status was not idle ('T' or 'E').
+ */
+ onpoisoned: (status: string) => void;
++ /**
++ * GBrain: share the parameter types of a described statement across this pool's
++ * connections, so a connection running it for the first time skips the describe
++ * round trip and keeps pipelining. Only built-in types are shared.
++ * @default true
++ */
++ shared_types: boolean;
backoff: boolean | ((attemptNum: number) => number);
max_lifetime: number | null;
keep_alive: number | null;
-@@ -605,7 +610,7 @@ declare namespace postgres {
+@@ -605,7 +617,7 @@ declare namespace postgres {
writable(): Promise<Writable>;
execute(): this;
@@ -889,7 +962,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..19103a998359c7277cd966c246cf245a
/**
* @deprecated `.stream` has been renamed to `.forEach`
-@@ -659,6 +664,7 @@ declare namespace postgres {
+@@ -659,6 +671,7 @@ declare namespace postgres {
| Fragment[]
interface UnsafeQueryOptions {
@@ -897,7 +970,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..19103a998359c7277cd966c246cf245a
/**
* When executes query as prepared statement.
* @default false
-@@ -717,10 +723,11 @@ declare namespace postgres {
+@@ -717,10 +730,11 @@ declare namespace postgres {
begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
@@ -910,7 +983,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..19103a998359c7277cd966c246cf245a
savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
-@@ -728,6 +735,7 @@ declare namespace postgres {
+@@ -728,6 +742,7 @@ declare namespace postgres {
}
interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ac095d6518..47118065b8 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2202 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2998 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move)
-src/core/postgres-engine.ts 2944 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944
+src/core/postgres-engine.ts 2946 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
src/core/types.ts 2232 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index e12550448f..93c5fdd246 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 { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, endPoolBounded } from './db.ts';
+import { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded } from './db.ts';
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
@@ -353,6 +353,7 @@ export class ConnectionManager {
types: { bigint: postgres.BigInt },
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status),
+ shared_types: resolveSharedTypes(),
};
const timeouts = resolveSessionTimeouts();
if (Object.keys(timeouts).length > 0) opts.connection = timeouts;
@@ -504,6 +505,7 @@ export class ConnectionManager {
prepare: true,
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
onpoisoned: (status: string) => this.opts.onpoisoned?.('direct', status),
+ shared_types: resolveSharedTypes(),
// 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 390291f9f9..1d0f49d214 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -121,6 +121,21 @@ const FALLBACK_CONNECT_TIMEOUT_S = 10;
*/
const MAX_CONNECT_TIMEOUT_S = Math.floor(0x7fffffff / 1000);
+/**
+ * #5984: whether a pool shares the parameter types of a described statement
+ * across its connections (the vendored driver's `shared_types`), so a
+ * connection running a statement for the first time skips the describe round
+ * trip and keeps pipelining. On by default; GBRAIN_PG_TYPE_CACHE=0 turns it off.
+ */
+export function resolveSharedTypes(): boolean {
+ const value = process.env.GBRAIN_PG_TYPE_CACHE?.trim().toLowerCase();
+ return value !== '0' && value !== 'false';
+}
+/** Forgets the shared parameter 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();
+}
+
/**
* The `connect_timeout` each postgres() pool is built with, read from that
* pool's own URL.
@@ -342,6 +357,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statu
// `gbrain jobs submit --json | ...`). Opt back in with GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
onpoisoned: hooks.onpoisoned,
+ shared_types: resolveSharedTypes(),
};
if (Object.keys(timeouts).length > 0) {
opts.connection = timeouts;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 777d0ff387..0c46923de1 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -375,6 +375,7 @@ export class PostgresEngine implements BrainEngine {
// GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
onpoisoned: (status: string) => this.onPoisoned('read', status),
+ shared_types: db.resolveSharedTypes(),
};
if (Object.keys(timeouts).length > 0) {
opts.connection = timeouts;
@@ -559,6 +560,7 @@ export class PostgresEngine implements BrainEngine {
if (verify.healed.length > 0) {
process.stderr.write(` Schema verify: self-healed ${verify.healed.length} missing column(s)\n`);
}
+ if (applied > 0 || verify.healed.length > 0) db.clearSharedTypes(this.sql, pool);
// v0.30.1 (Fix 5): sweep zombie HNSW indexes (indisvalid=false) from
// crashed CREATE INDEX CONCURRENTLY calls. Best-effort; errors logged
diff --git a/test/e2e/postgres-shared-types.test.ts b/test/e2e/postgres-shared-types.test.ts
new file mode 100644
index 0000000000..ba18d6619f
--- /dev/null
+++ b/test/e2e/postgres-shared-types.test.ts
@@ -0,0 +1,110 @@
+/**
+ * #5984: the vendored driver shares a described statement's parameter types across
+ * a pool's connections (`shared_types`, vendor/README.md). A connection running the
+ * statement for the first time then skips the describe round trip, with the same
+ * results; a failure forgets the shared types, and a database's own types (pgvector)
+ * are never shared.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { traceSqlOptions } from '../../src/core/sql-trace.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const url = process.env.DATABASE_URL;
+const run = url ? test : test.skip;
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-shared-types-'));
+// The trace module opens its file once per process, so every test shares it and reads its own backends' rows.
+const traceFile = join(dir, 'trace.jsonl');
+const table = `shared_types_${randomUUID().replace(/-/g, '').slice(0, 12)}`;
+let admin: ReturnType<typeof postgres> | undefined;
+
+beforeAll(async () => {
+ if (!url) return;
+ assertSafeE2eDatabaseUrl(url);
+ admin = postgres(url, { max: 1, onnotice: () => {} });
+ await admin.unsafe(`CREATE TABLE ${table} (c int)`);
+ await admin.unsafe(`INSERT INTO ${table} VALUES (1)`);
+});
+afterAll(async () => {
+ await admin?.unsafe(`DROP TABLE IF EXISTS ${table}`);
+ await admin?.end();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+const rowsOf = (rows: Iterable<unknown>) => Array.from(rows);
+type TraceRow = { kind: string; sql: string; backend: number };
+/** Runs `body` with two reserved connections of one traced pool; returns the trace rows by backend. */
+async function traced(options: Record<string, unknown>, body: (a: postgres.ReservedSql, b: postgres.ReservedSql, sql: ReturnType<typeof postgres>) => Promise<void>) {
+ let pids: number[] = [];
+ await withEnv({ GBRAIN_SQL_TRACE: traceFile, GBRAIN_SQL_TRACE_LABEL: 'shared-types' }, async () => {
+ const sql = postgres(url!, traceSqlOptions({ max: 2, onnotice: () => {}, ...options }, 'test') as Parameters<typeof postgres>[1]);
+ try {
+ const a = await sql.reserve(), b = await sql.reserve();
+ try {
+ pids = [Number((await a`SELECT pg_backend_pid() AS pid`)[0]!.pid), Number((await b`SELECT pg_backend_pid() AS pid`)[0]!.pid)];
+ await body(a, b, sql);
+ } finally { a.release(); b.release(); }
+ await Bun.sleep(1200);
+ } finally { await sql.end(); }
+ });
+ const rows = readFileSync(traceFile, 'utf8').trim().split('\n').map(line => JSON.parse(line) as TraceRow);
+ return { on: (index: number, text: string) => rows.filter(r => r.backend === pids[index] && r.sql === text).map(r => r.kind) };
+}
+
+const MIXED = `SELECT $1::uuid[] AS ids, $2::text::jsonb AS doc, $3::bigint AS big, $4::boolean AS flag, $5::timestamptz AS at,
+ $6::bytea AS raw, $7::text AS none, $8::text AS words, $9::int AS n`;
+const ids = [randomUUID(), randomUUID()], at = new Date('2026-10-07T12:34:56.789Z');
+const mixed = () => [ids, JSON.stringify({ a: [1, 'two'], b: null }), '9007199254740993', true, at, Buffer.from([0, 1, 254]), null, 'naïve ☃ text', 42];
+
+for (const prepare of [true, false]) {
+ run(`a second connection runs a statement the pool described without a describe round trip, with the same results (prepare ${prepare})`, async () => {
+ const results: unknown[] = [];
+ const trace = await traced({ prepare }, async (a, b) => {
+ results.push(await a.unsafe(MIXED, mixed() as never[]));
+ results.push(await b.unsafe(MIXED, mixed() as never[]));
+ results.push(await b.unsafe(MIXED, mixed() as never[]));
+ });
+ expect(trace.on(0, MIXED)).toEqual(['describe', 'execute']);
+ expect(trace.on(1, MIXED)).toEqual(['execute', 'execute']);
+ const [first, second, third] = results.map(rows => JSON.parse(JSON.stringify((rows as Record<string, unknown>[])[0], (_k, v) => typeof v === 'bigint' ? String(v) : v)));
+ expect(second).toEqual(first);
+ expect(third).toEqual(first);
+ expect(first).toMatchObject({ ids, doc: { a: [1, 'two'], b: null }, big: '9007199254740993', flag: true, at: at.toISOString(), none: null, words: 'naïve ☃ text', n: 42 });
+ });
+}
+
+run('with shared_types off, each connection describes the statement itself', async () => {
+ const trace = await traced({ shared_types: false }, async (a, b) => {
+ await a.unsafe('SELECT $1::int AS n', [1]);
+ await b.unsafe('SELECT $1::int AS n', [2]);
+ });
+ expect(trace.on(0, 'SELECT $1::int AS n')).toEqual(['describe', 'execute']);
+ expect(trace.on(1, 'SELECT $1::int AS n')).toEqual(['describe', 'execute']);
+});
+
+run('a statement whose shared types no longer fit fails once, then describes again and succeeds', async () => {
+ const text = `SELECT c FROM ${table} WHERE c = $1`;
+ await traced({ prepare: true }, async (a, b, sql) => {
+ expect(rowsOf(await a.unsafe(text, ['1'], { prepare: true }))).toEqual([{ c: 1 }]);
+ await admin!.unsafe(`ALTER TABLE ${table} ALTER COLUMN c TYPE text USING c::text`);
+ const shared = (sql as unknown as { options: { shared_types: Map<string, number[]> } }).options.shared_types;
+ expect([...shared.values()].some(types => types.length === 1 && types[0] === 23)).toBe(true);
+ const failed = await b.unsafe(text, ['1'], { prepare: true }).then(() => null, (error: { code?: string }) => error);
+ expect(failed).toMatchObject({ code: '42883' });
+ expect(rowsOf(await b.unsafe(text, ['1'], { prepare: true }))).toEqual([{ c: '1' }]);
+ });
+});
+
+run('a parameter of a database-defined type (pgvector) is never shared', async () => {
+ const text = 'SELECT vector_dims($1::vector) AS dims';
+ const trace = await traced({}, async (a, b) => {
+ expect(rowsOf(await a.unsafe(text, ['[1,2,3]'], { prepare: true }))).toEqual([{ dims: 3 }]);
+ expect(rowsOf(await b.unsafe(text, ['[1,2,3]'], { prepare: true }))).toEqual([{ dims: 3 }]);
+ });
+ expect(trace.on(1, text)).toEqual(['describe', 'execute']);
+});
diff --git a/test/e2e/sql-trace-postgres.test.ts b/test/e2e/sql-trace-postgres.test.ts
index a3b0eec4d8..dbb3c6f79d 100644
--- a/test/e2e/sql-trace-postgres.test.ts
+++ b/test/e2e/sql-trace-postgres.test.ts
@@ -37,7 +37,8 @@ run('records each round trip with its statement, kind, label and backend pid', a
expect(rows[0]).toMatchObject({ kind: 'connect', sql: '<connect>' });
expect(rows.filter(r => r.kind !== 'connect').every(r => r.backend === Number(pid))).toBe(true);
const unsafe = rows.filter(r => r.sql === 'SELECT $1::int AS n').map(r => r.kind);
- expect(unsafe).toEqual(['describe', 'execute', 'describe', 'execute']);
+ // The second unprepared run reuses the parameter types the pool described (shared_types), so it skips the describe.
+ expect(unsafe).toEqual(['describe', 'execute', 'execute']);
expect(rows.filter(r => /^(begin|commit)$/.test(r.sql.trim())).map(r => r.sql.trim())).toEqual(['begin', 'commit']);
expect(rows.some(r => r.kind === 'simple' && r.sql === 'SELECT 1 AS one')).toBe(true);
expect(rows.every(r => r.ms >= 0)).toBe(true);
diff --git a/vendor/README.md b/vendor/README.md
index 4aff181daa..a4b55df0d8 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -37,6 +37,18 @@ must settle or retire the connection before another query can own it. This
is necessary for worker admission, query timeout and lease-release safety.
See issues #5466 and #5560 and `test/e2e/persistence-chaos.test.ts`.
+The patch also lets a pool share the parameter types of a described statement
+across its connections (`shared_types`, on by default; GBrain turns it off with
+`GBRAIN_PG_TYPE_CACHE=0`). Stock postgres.js describes every parameterized
+statement once per connection, and with `prepare: false` (transaction-mode
+poolers) on every run, before it can execute it; that describe costs a round
+trip and stops pipelining behind it. With the types known, the statement is
+parsed, described and executed in one message group. Only built-in types (oid
+below 16384) are shared, since a database's own types (pgvector) can be
+recreated under a new oid; a statement that fails forgets its shared types, and
+`PostgresEngine.initSchema` clears them after applying migrations (#5984,
+`test/e2e/postgres-shared-types.test.ts`).
+
## Reproduce and update
Run `bash vendor/update-postgres.sh --check` to download the pinned upstream
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index c893205f90..28a432b7ea 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -243,10 +243,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
- q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)
+ // GBrain: a statement this pool already described on another connection reuses its parameter
+ // types, so it is parsed, described and executed in one pipelined message group (no describe first).
+ q.typesKey = options.shared_types && parameters.length && !q.onlyDescribe ? types + string : null
+ const shared = !q.prepared && q.typesKey && options.shared_types.get(q.typesKey)
+ q.sharedTypes = !!shared
+ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared && !shared)
q.statement = q.prepared
? statements[q.signature]
- : { string, types, name: q.prepare ? statementId + statementCount++ : '' }
+ : { string, types: shared ? shared.slice() : types, name: q.prepare ? statementId + statementCount++ : '' }
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
@@ -553,6 +558,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
connection.status = x[5]
if (query) {
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.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine)
@@ -650,6 +657,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
+ // 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())
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
}
diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.js
index fa294e7960..2a0b505c70 100644
--- a/vendor/postgres/cf/src/index.js
+++ b/vendor/postgres/cf/src/index.js
@@ -618,6 +618,7 @@ function parseOptions(a, b) {
onnotify : o.onnotify,
onclose : o.onclose,
onpoisoned : o.onpoisoned,
+ shared_types : o.shared_types === false ? null : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index e5800bca79..f6d76e59ab 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -241,10 +241,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
- q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)
+ // GBrain: a statement this pool already described on another connection reuses its parameter
+ // types, so it is parsed, described and executed in one pipelined message group (no describe first).
+ q.typesKey = options.shared_types && parameters.length && !q.onlyDescribe ? types + string : null
+ const shared = !q.prepared && q.typesKey && options.shared_types.get(q.typesKey)
+ q.sharedTypes = !!shared
+ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared && !shared)
q.statement = q.prepared
? statements[q.signature]
- : { string, types, name: q.prepare ? statementId + statementCount++ : '' }
+ : { string, types: shared ? shared.slice() : types, name: q.prepare ? statementId + statementCount++ : '' }
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
@@ -551,6 +556,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
connection.status = x[5]
if (query) {
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.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine)
@@ -648,6 +655,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
+ // 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())
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
}
diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
index c72e413562..a58dbb6c1e 100644
--- a/vendor/postgres/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -617,6 +617,7 @@ function parseOptions(a, b) {
onnotify : o.onnotify,
onclose : o.onclose,
onpoisoned : o.onpoisoned,
+ shared_types : o.shared_types === false ? null : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index 9a61cd9dcc..792c83d36a 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -241,10 +241,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
- q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)
+ // GBrain: a statement this pool already described on another connection reuses its parameter
+ // types, so it is parsed, described and executed in one pipelined message group (no describe first).
+ q.typesKey = options.shared_types && parameters.length && !q.onlyDescribe ? types + string : null
+ const shared = !q.prepared && q.typesKey && options.shared_types.get(q.typesKey)
+ q.sharedTypes = !!shared
+ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared && !shared)
q.statement = q.prepared
? statements[q.signature]
- : { string, types, name: q.prepare ? statementId + statementCount++ : '' }
+ : { string, types: shared ? shared.slice() : types, name: q.prepare ? statementId + statementCount++ : '' }
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
@@ -551,6 +556,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
connection.status = x[5]
if (query) {
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.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine)
@@ -648,6 +655,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
+ // 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())
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
}
diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.js
index e9af339e13..58b370bb34 100644
--- a/vendor/postgres/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -617,6 +617,7 @@ function parseOptions(a, b) {
onnotify : o.onnotify,
onclose : o.onclose,
onpoisoned : o.onpoisoned,
+ shared_types : o.shared_types === false ? null : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.ts
index 19103a9983..d7ba214bc6 100644
--- a/vendor/postgres/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -124,6 +124,13 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
* reused because its ReadyForQuery status was not idle ('T' or 'E').
*/
onpoisoned: (status: string) => void;
+ /**
+ * GBrain: share the parameter types of a described statement across this pool's
+ * connections, so a connection running it for the first time skips the describe
+ * round trip and keeps pipelining. Only built-in types are shared.
+ * @default true
+ */
+ shared_types: boolean;
backoff: boolean | ((attemptNum: number) => number);
max_lifetime: number | null;
keep_alive: number | null;