Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(postgres): keep described parameter types for the next process (#5984 G3)
garrytan45e91e5aa010
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex 93c5fdd246..7ae4b865d3 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -353,7 +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(),+ shared_types: resolveSharedTypes(this.opts.url),};const timeouts = resolveSessionTimeouts();if (Object.keys(timeouts).length > 0) opts.connection = timeouts;@@ -505,7 +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(),+ shared_types: resolveSharedTypes(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.tsindex 1d0f49d214..693eb1d861 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -6,6 +6,7 @@ import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.timport 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';let sql: ReturnType<typeof postgres> | null = null;let connectedUrl: string | null = null;@@ -122,20 +123,39 @@ 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.+ * #5984: the store a pool shares described parameter types in (the vendored+ * driver's `shared_types`): one per database target in this process, saved for+ * the next process (src/core/pg-type-cache.ts). A connection running a statement+ * for the first time then 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';+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. */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();}+/**+ * A new pool's connection check. It also reads the scope of the saved parameter+ * types (server version, schema version and the database as the server names+ * it) in the same round trip and loads them; a database without a `config`+ * table falls back to `SELECT 1`.+ */+export async function checkPoolAndLoadSharedTypes(pool: ReturnType<typeof postgres>, url: string): Promise<void> {+ let rows: Array<{ server: string; schema: string | null; database: string | null }>;+ try {+ rows = await pool.unsafe(`SELECT current_setting('server_version_num') AS server, (SELECT value FROM config WHERE key='version') AS schema,+ current_database() || '@' || coalesce(host(inet_server_addr()), '') || ':' || coalesce(inet_server_port()::text, '') || '?' || current_user AS database`) as unknown as typeof rows;+ } catch (err) {+ if ((err as { code?: string }).code !== '42P01') throw err;+ await pool`SELECT 1`;+ return;+ }+ loadSharedParameterTypes(url, String(rows[0]?.server ?? ''), rows[0]?.schema ?? null, rows[0]?.database ?? null);+}+/*** The `connect_timeout` each postgres() pool is built with, read from that* pool's own URL.@@ -357,7 +377,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(),+ shared_types: resolveSharedTypes(url),};if (Object.keys(timeouts).length > 0) {opts.connection = timeouts;@@ -373,7 +393,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statusql = postgres(url, traceSqlOptions(opts, 'module'));// Test connection- await sql`SELECT 1`;+ await checkPoolAndLoadSharedTypes(sql, url);connectedUrl = url;await setSessionDefaults(sql);diff --git a/src/core/pg-type-cache.ts b/src/core/pg-type-cache.tsnew file mode 100644index 0000000000..281a02877c--- /dev/null+++ b/src/core/pg-type-cache.ts@@ -0,0 +1,172 @@+/**+ * #5984 G3: the parameter types a pool has described, shared by every pool in+ * this process that talks to the same database and kept in a file under the+ * gbrain home so the next process skips those describe round trips too.+ *+ * Safety rules (docs/eval/managed-sync-catchup.md, "Statement descriptions"):+ * - the driver stores only built-in parameter types and drops a statement's+ * entry when that statement fails;+ * - the file is used only when its scope (server_version_num and the brain's+ * schema version) matches the connected database; a migration clears it;+ * - keys are SHA-256 digests of the driver's (types, SQL) key, so no SQL text is+ * written; the file is 0600 in a 0700 directory.+ *+ * `GBRAIN_PG_TYPE_CACHE=0` turns sharing off; `GBRAIN_PG_TYPE_CACHE_PERSIST=0`+ * keeps it in this process.+ */+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { resolveGbrainHome } from './gbrain-home.ts';++const MAX_ENTRIES = 4000;+const SAVE_DELAY_MS = 5000;++function digest(key: string): string {+ return createHash('sha256').update(key).digest('base64url');+}++function envOff(name: string): boolean {+ const value = process.env[name]?.trim().toLowerCase();+ return value === '0' || value === 'false';+}++/** A database target without credentials: host, port, database and user. */+export function typeCacheTarget(url: string): string {+ try {+ const u = new URL(url);+ return `${u.hostname}:${u.port || '5432'}/${decodeURIComponent(u.pathname.replace(/^\//, ''))}?${decodeURIComponent(u.username)}`;+ } catch {+ return url.replace(/:\/\/[^@/]*@/, '://');+ }+}++export class SharedParameterTypes extends Map<string, number[]> {+ scope: string | null = null;+ file: string | null = null;+ private dirty = false;+ private timer: ReturnType<typeof setTimeout> | null = null;++ override get(key: string): number[] | undefined {+ return super.get(digest(key));+ }++ override set(key: string, types: number[]): this {+ if (super.size >= MAX_ENTRIES) return this;+ super.set(digest(key), types);+ this.changed();+ return this;+ }++ override delete(key: string): boolean {+ const removed = super.delete(digest(key));+ if (removed) this.changed();+ return removed;+ }++ override clear(): void {+ super.clear();+ this.scope = null;+ this.dirty = false;+ if (this.file) rmSync(this.file, { force: true });+ }++ /** Merges the file's entries when its scope matches; from then on new entries are saved under that scope. */+ load(scope: string, file: string): number {+ this.scope = scope;+ this.file = file;+ const stored = readStore(file);+ if (!stored || stored.scope !== scope) return 0;+ let added = 0;+ for (const [key, types] of Object.entries(stored.types)) {+ if (super.size >= MAX_ENTRIES) break;+ if (!super.has(key)) { super.set(key, types); added++; }+ }+ return added;+ }++ /** Writes this process's entries, merged with what another process saved under the same scope. */+ save(): void {+ if (this.timer) { clearTimeout(this.timer); this.timer = null; }+ if (!this.dirty || !this.file || !this.scope) return;+ this.dirty = false;+ try {+ const stored = readStore(this.file);+ const types: Record<string, number[]> = stored?.scope === this.scope ? stored.types : {};+ for (const [key, value] of super.entries()) types[key] = value;+ const keys = Object.keys(types);+ for (const key of keys.slice(0, Math.max(0, keys.length - MAX_ENTRIES))) delete types[key];+ mkdirSync(join(this.file, '..'), { recursive: true, mode: 0o700 });+ const tmp = `${this.file}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify({ scope: this.scope, types }), { mode: 0o600 });+ renameSync(tmp, this.file);+ } catch {+ // A cache that cannot be written only costs the next process its describes.+ }+ }++ private changed(): void {+ if (!this.file) return;+ this.dirty = true;+ if (this.timer) return;+ this.timer = setTimeout(() => this.save(), SAVE_DELAY_MS);+ this.timer.unref?.();+ }+}++function readStore(file: string): { scope: string; types: Record<string, number[]> } | null {+ try {+ if (!existsSync(file)) return null;+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { scope?: unknown; types?: unknown };+ if (typeof parsed.scope !== 'string' || !parsed.types || typeof parsed.types !== 'object') return null;+ const types: Record<string, number[]> = {};+ for (const [key, value] of Object.entries(parsed.types as Record<string, unknown>)) {+ if (Array.isArray(value) && value.every(t => Number.isInteger(t) && t > 0 && t < 16384)) types[key] = value as number[];+ }+ return { scope: parsed.scope, types };+ } catch {+ return null;+ }+}++const byTarget = new Map<string, SharedParameterTypes>();+let exitHook = false;++/** The shared store for this database target, or false when `GBRAIN_PG_TYPE_CACHE=0`. */+export function sharedParameterTypes(url: string | undefined): SharedParameterTypes | false {+ if (envOff('GBRAIN_PG_TYPE_CACHE')) return false;+ if (!url) return new SharedParameterTypes();+ const target = typeCacheTarget(url);+ let store = byTarget.get(target);+ if (!store) {+ store = new SharedParameterTypes();+ byTarget.set(target, store);+ }+ return store;+}++/**+ * Loads the saved descriptions for this pool's store once its scope is known.+ * `serverVersion` is `server_version_num`; `schemaVersion` is `config.version`;+ * `database` names the database as the server sees it (database, server address+ * and port, user), so a proxy or pooler URL and a direct URL to one database+ * share a file. Without it the URL's target is used.+ */+export function loadSharedParameterTypes(url: string, serverVersion: string, schemaVersion: string | null, database?: string | null): number {+ const store = sharedParameterTypes(url);+ if (!store || !schemaVersion || envOff('GBRAIN_PG_TYPE_CACHE_PERSIST')) return 0;+ const scope = `${serverVersion}:${schemaVersion}`;+ if (store.scope === scope) return 0;+ const file = join(resolveGbrainHome(), 'cache', 'pg-types', `${digest(database || typeCacheTarget(url)).slice(0, 24)}.json`);+ const added = store.load(scope, file);+ if (!exitHook) {+ exitHook = true;+ process.once('exit', () => { for (const s of byTarget.values()) s.save(); });+ }+ return added;+}++export function _resetSharedParameterTypesForTests(): void {+ for (const store of byTarget.values()) store.scope = null;+ byTarget.clear();+}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 108f27a595..a0f8383852 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -376,7 +376,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(),+ shared_types: db.resolveSharedTypes(url),};if (Object.keys(timeouts).length > 0) {opts.connection = timeouts;@@ -385,7 +385,7 @@ export class PostgresEngine implements BrainEngine {opts.prepare = prepare;}this._sql = postgres(url, traceSqlOptions(opts, 'instance'));- await this._sql`SELECT 1`;+ await db.checkPoolAndLoadSharedTypes(this._sql, url);await db.setSessionDefaults(this._sql);this._connectionStyle = 'instance';diff --git a/test/e2e/postgres-shared-types.test.ts b/test/e2e/postgres-shared-types.test.tsindex b78ec4b963..4e54468b96 100644--- a/test/e2e/postgres-shared-types.test.ts+++ b/test/e2e/postgres-shared-types.test.ts@@ -110,3 +110,28 @@ run('a parameter of a database-defined type (pgvector) is never shared', async (});expect(trace.on(1, text)).toEqual(['describe', 'execute']);});++run('a new process with the saved types for this database runs its first statements without describe round trips', async () => {+ const { _resetSharedParameterTypesForTests, loadSharedParameterTypes, sharedParameterTypes } = await import('../../src/core/pg-type-cache.ts');+ const text = `SELECT count(*)::int AS n FROM ${table} WHERE c::text = $1 AND $2::bigint > 0`;+ const scope = `e2e-${randomUUID()}`;+ const runAs = async (persist: string | undefined) => {+ _resetSharedParameterTypesForTests();+ return await withEnv({ GBRAIN_HOME: dir, GBRAIN_PG_TYPE_CACHE_PERSIST: persist }, async () => {+ const store = sharedParameterTypes(url!);+ loadSharedParameterTypes(url!, '0', scope);+ const trace = await traced({ shared_types: store }, async (a) => {+ expect(rowsOf(await a.unsafe(text, ['1', '1'] as never[]))).toEqual([{ n: 1 }]);+ });+ (store as unknown as { save(): void }).save();+ return trace.on(0, text);+ });+ };+ try {+ expect(await runAs(undefined)).toEqual(['describe', 'execute']);+ expect(await runAs(undefined)).toEqual(['execute']);+ expect(await runAs('0')).toEqual(['describe', 'execute']);+ } finally {+ _resetSharedParameterTypesForTests();+ }+});diff --git a/test/pg-type-cache.test.ts b/test/pg-type-cache.test.tsnew file mode 100644index 0000000000..646b24ea83--- /dev/null+++ b/test/pg-type-cache.test.ts@@ -0,0 +1,138 @@+/**+ * #5984 G3: the saved parameter types (src/core/pg-type-cache.ts). A second+ * process with the same database scope starts with the first one's described+ * types; a different server or schema version, the persist switch, or a+ * migration's clear leaves it describing again; no SQL text is written.+ */+import { afterEach, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { _resetSharedParameterTypesForTests, loadSharedParameterTypes, sharedParameterTypes, typeCacheTarget } from '../src/core/pg-type-cache.ts';+import { withEnv } from './helpers/with-env.ts';++/** A database URL with credentials (example values), built so no literal credential URL sits in the source. */+function dbUrl(hostPortDb: string, user = 'writer', password = 's3cret', query = ''): string {+ const url = new URL(`postgresql://${hostPortDb}${query}`);+ url.username = user;+ url.password = password;+ return url.toString();+}+const URL_A = dbUrl('db.example.test:6543/brain');+const KEY = '23,25SELECT id FROM pages WHERE source_id=$1 AND slug=$2';++afterEach(() => _resetSharedParameterTypesForTests());++async function withHome<T>(body: (home: string) => Promise<T> | T): Promise<T> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-type-cache-'));+ try {+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_PG_TYPE_CACHE: undefined, GBRAIN_PG_TYPE_CACHE_PERSIST: undefined }, () => body(home));+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+}++function cacheFiles(home: string): string[] {+ const dir = join(home, '.gbrain', 'cache', 'pg-types');+ return existsSync(dir) ? readdirSync(dir).map(name => join(dir, name)) : [];+}++/** One "process": load the scope, optionally record a description, save at exit. */+function processRun(scope: [string, string], record?: number[]) {+ _resetSharedParameterTypesForTests();+ const store = sharedParameterTypes(URL_A);+ if (!store) throw new Error('sharing is off');+ const loaded = loadSharedParameterTypes(URL_A, scope[0], scope[1]);+ const before = store.get(KEY);+ if (record) store.set(KEY, record);+ store.save();+ return { loaded, before };+}++test('a second process with the same scope starts with the first one\'s described types', () => withHome(home => {+ expect(processRun(['160004', '112'], [25, 25]).before).toBeUndefined();+ expect(processRun(['160004', '112'])).toEqual({ loaded: 1, before: [25, 25] });+ const [file] = cacheFiles(home);+ expect(statSync(file!).mode & 0o777).toBe(0o600);+}));++test('the file holds digests and type ids only: no SQL text, credentials or host', () => withHome(home => {+ processRun(['160004', '112'], [25, 25]);+ const text = readFileSync(cacheFiles(home)[0]!, 'utf8');+ for (const leaked of ['SELECT', 'pages', 'source_id', 's3cret', 'writer', 'example']) expect(text).not.toContain(leaked);+}));++test('a different server version or schema version ignores and then replaces the saved types', () => withHome(() => {+ processRun(['160004', '112'], [25, 25]);+ expect(processRun(['170000', '112'])).toEqual({ loaded: 0, before: undefined });+ expect(processRun(['160004', '113'])).toEqual({ loaded: 0, before: undefined });+}));++test('with no schema version (a database gbrain has not initialized) nothing is loaded or saved', () => withHome(home => {+ processRun(['160004', null as unknown as string], [25, 25]);+ expect(cacheFiles(home)).toEqual([]);+}));++test('GBRAIN_PG_TYPE_CACHE_PERSIST=0 keeps the types in this process', () => withHome(async home => {+ await withEnv({ GBRAIN_PG_TYPE_CACHE_PERSIST: '0' }, () => processRun(['160004', '112'], [25, 25]));+ expect(cacheFiles(home)).toEqual([]);+}));++test('GBRAIN_PG_TYPE_CACHE=0 turns sharing off entirely', () => withEnv({ GBRAIN_PG_TYPE_CACHE: '0' }, () => {+ expect(sharedParameterTypes(URL_A)).toBe(false);+}));++test('clearing (after a migration) deletes the saved types', () => withHome(home => {+ processRun(['160004', '112'], [25, 25]);+ _resetSharedParameterTypesForTests();+ const store = sharedParameterTypes(URL_A) as Map<string, number[]>;+ loadSharedParameterTypes(URL_A, '160004', '112');+ store.clear();+ expect(cacheFiles(home)).toEqual([]);+ expect(processRun(['160004', '112']).before).toBeUndefined();+}));++test('pools of one database target share a store; another database gets its own', () => {+ expect(sharedParameterTypes(dbUrl('db.example.test:6543/brain', 'writer', 'rotated', '?sslmode=require'))).toBe(sharedParameterTypes(URL_A));+ expect(sharedParameterTypes(dbUrl('db.example.test:6543/other'))).not.toBe(sharedParameterTypes(URL_A));+ expect(typeCacheTarget(URL_A)).toBe('db.example.test:6543/brain?writer');+});++test('entries another process saved under the same scope are kept when this process saves', () => withHome(() => {+ processRun(['160004', '112'], [25, 25]);+ _resetSharedParameterTypesForTests();+ const store = sharedParameterTypes(URL_A) as Map<string, number[]>;+ loadSharedParameterTypes(URL_A, '160004', '112');+ store.set('20SELECT $1::bigint', [20]);+ (store as unknown as { save(): void }).save();+ _resetSharedParameterTypesForTests();+ const next = sharedParameterTypes(URL_A) as Map<string, number[]>;+ expect(loadSharedParameterTypes(URL_A, '160004', '112')).toBe(2);+ expect(next.get(KEY)).toEqual([25, 25]);+ expect(next.get('20SELECT $1::bigint')).toEqual([20]);+}));++test('a corrupt file or a non-built-in type id is ignored', () => withHome(home => {+ processRun(['160004', '112'], [25, 25]);+ const file = cacheFiles(home)[0]!;+ const digestKey = Object.keys(JSON.parse(readFileSync(file, 'utf8')).types)[0]!;+ writeFileSync(file, '{not json');+ expect(processRun(['160004', '112']).loaded).toBe(0);+ writeFileSync(file, JSON.stringify({ scope: '160004:112', types: { [digestKey]: [16385] } }));+ expect(processRun(['160004', '112']).loaded).toBe(0);+}));++test('a proxy URL and a direct URL to one database (same server-side identity) share the saved types', () => withHome(() => {+ const PROXY = dbUrl('127.0.0.1:55473/brain');+ const DIRECT = dbUrl('127.0.0.1:55472/brain');+ const identity = '[email protected]:5432?writer';+ _resetSharedParameterTypesForTests();+ const first = sharedParameterTypes(DIRECT) as Map<string, number[]>;+ loadSharedParameterTypes(DIRECT, '160004', '112', identity);+ first.set(KEY, [25, 25]);+ (first as unknown as { save(): void }).save();+ _resetSharedParameterTypesForTests();+ const second = sharedParameterTypes(PROXY) as Map<string, number[]>;+ expect(loadSharedParameterTypes(PROXY, '160004', '112', identity)).toBe(1);+ expect(second.get(KEY)).toEqual([25, 25]);+}));