Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(bench): env-gated wire-level SQL trace (GBRAIN_SQL_TRACE)

garrytan8c929d6ab1d9
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 3ab112e097..a05598eb64 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -39,6 +39,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/snapshot-schema-inputs.ts` — the inputs of the PGLite snapshot schema hash (`computeSnapshotSchemaHash` in `pglite-engine.ts` hashes each file's raw bytes). Computed, not hand-kept: the static import closure (`import`, `export ... from`; type-only imports skipped) of `SNAPSHOT_SCHEMA_ROOTS` (`pglite-schema.ts`, `schema-migrations/registry.generated.ts`, `migrate.ts`, `engine-sql/bootstrap.ts`) plus `SNAPSHOT_SCHEMA_LEAVES`; every literal dynamic `import()` inside the closure must be classified as a leaf or in `SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED`. Pure (the caller supplies file access). `test/snapshot-inputs-closure.test.ts` names any missing file and checks every `pglite-snapshot-*` CI cache key covers the same inputs.
+- `src/core/sql-trace.ts` — env-gated wire-level SQL trace for benchmarks. `traceSqlOptions(options, pool)` returns the postgres.js options untouched unless `GBRAIN_SQL_TRACE=<file.jsonl>` is set; then it supplies a tracing socket and sets `application_name` to `gbrain:<GBRAIN_SQL_TRACE_LABEL or command>:<pid>:<pool>`. All four pool construction sites use it (`db.ts` module singleton, `PostgresEngine` instance pool, `ConnectionManager` read and direct pools), so `executeRaw`, `tx.unsafe`, the engine-sql adapter and tagged templates are all seen. Each Sync, simple Query or describe Flush and its reply is one JSONL record (statement text without parameter values, start, duration, process, pool, client connection, backend pid, SQLSTATE on error); a `connect` record covers TCP plus the startup handshake. TLS connections are recorded once as `tls_untraced`. Records are buffered and flushed every second and at exit. Consumed by `scripts/bench/managed-sync-catchup.ts` ([record](../../eval/managed-sync-catchup.md)); pinned by `test/sql-trace.test.ts` and `test/e2e/sql-trace-postgres.test.ts`.
+
- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.
- `src/core/worker-pool.ts` — Canonical sliding-pool + bounded-semaphore primitive (used by the `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts`'s `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem`, then the pool JOINS every worker (each finishes its current item) before rethrowing — the budget cap is a structural ceiling under concurrency and no worker is left running detached past the caller's catch. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d0c6f75034..75ff5778c2 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2233 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 333 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)
src/core/pglite-engine.ts 2921 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); 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)
-src/core/postgres-engine.ts 2914 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)
+src/core/postgres-engine.ts 2915 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); +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts)
src/core/search/hybrid.ts 1584 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
src/core/types.ts 2123 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)
src/core/minions/queue.ts 2522 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
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index b966803337..32dea22461 100644
--- a/src/core/connection-manager.ts
+++ b/src/core/connection-manager.ts
@@ -37,6 +37,7 @@
*/
import postgres from '#postgres'
+import { traceSqlOptions } from './sql-trace.ts';
import { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, endPoolBounded } from './db.ts';
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
@@ -356,7 +357,7 @@ export class ConnectionManager {
if (Object.keys(timeouts).length > 0) opts.connection = timeouts;
const prepare = resolvePrepare(this.opts.url);
if (typeof prepare === 'boolean') opts.prepare = prepare;
- this._readPool = postgres(this.opts.url, opts);
+ this._readPool = postgres(this.opts.url, traceSqlOptions(opts, 'read'));
logConnectionEvent({ pool: 'read', op: 'init' });
return this._readPool;
}
@@ -513,7 +514,7 @@ export class ConnectionManager {
const t0 = Date.now();
let pool: Sql | null = null;
try {
- pool = postgres(this._directUrl, opts);
+ pool = postgres(this._directUrl, traceSqlOptions(opts, 'direct'));
// Probe to validate connectivity early.
await pool`SELECT 1`;
logConnectionEvent({
diff --git a/src/core/db.ts b/src/core/db.ts
index a1c86a664e..8a614edf6c 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,4 +1,5 @@
import postgres from '#postgres'
+import { traceSqlOptions } from './sql-trace.ts';
import { GBrainError, type EngineConfig } from './types.ts';
import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
@@ -314,7 +315,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statu
);
}
}
- sql = postgres(url, opts);
+ sql = postgres(url, traceSqlOptions(opts, 'module'));
// Test connection
await sql`SELECT 1`;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index a52481e1e5..ef8c0e18c7 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -12,6 +12,7 @@ import type { PageReadScope } from './types.ts';
import type { PageReadPolicy } from './types.ts';
import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';
import postgres from '#postgres'
+import { traceSqlOptions } from './sql-trace.ts';
import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';
export { hasPostgresCancellationCapability } from './postgres-engine/cancellation.ts';
import type {
@@ -377,7 +378,7 @@ export class PostgresEngine implements BrainEngine {
if (typeof prepare === 'boolean') {
opts.prepare = prepare;
}
- this._sql = postgres(url, opts);
+ this._sql = postgres(url, traceSqlOptions(opts, 'instance'));
await this._sql`SELECT 1`;
await db.setSessionDefaults(this._sql);
this._connectionStyle = 'instance';
diff --git a/src/core/sql-trace.ts b/src/core/sql-trace.ts
new file mode 100644
index 0000000000..082031683c
--- /dev/null
+++ b/src/core/sql-trace.ts
@@ -0,0 +1,139 @@
+/**
+ * Env-gated wire-level SQL trace for benchmarks (`GBRAIN_SQL_TRACE=<file.jsonl>`,
+ * docs/eval/managed-sync-catchup.md). Every postgres.js pool (module singleton,
+ * instance pool, read and direct pools) passes its options through
+ * `traceSqlOptions`, so `executeRaw`, `tx.unsafe`, the engine-sql adapter and
+ * tagged templates are all seen at the socket. Each Sync or simple Query sent
+ * and its ReadyForQuery reply is one record: one database round trip, including
+ * the describe round trip an unprepared parameterized statement pays. Records
+ * carry the statement text (never parameter values), start, duration, process,
+ * pool, client connection and backend pid; `application_name` names the process
+ * so `pg_stat_activity` lock samples can be attributed. TLS connections are not
+ * decodable and are recorded once as `kind: "tls_untraced"`.
+ *
+ * Off (the default) it returns the options object untouched: no socket wrapper,
+ * no per-query work.
+ */
+import { appendFileSync } from 'node:fs';
+import net from 'node:net';
+
+interface Pending { sql: string; kind: 'execute' | 'describe' | 'simple' | 'connect'; t: number; err?: string; flush?: boolean }
+interface TraceConnection {
+ id: number; backend: number; prepared: Map<string, string>; text: string; executed: boolean; pending: Pending[];
+ out: Buffer | null; startup: boolean; opaque: boolean;
+ inHeader: Buffer; inType: number; inLeft: number; inBody: Buffer[] | null;
+}
+
+let connections = 0;
+let buffered: string[] = [];
+let flushOnExit = false;
+const clock = () => performance.timeOrigin + performance.now();
+const SSL_REQUEST = 80877103;
+const KEEP_BODY = new Set([0x4b, 0x45, 0x5a, 0x54, 0x6e]);
+
+function cstring(buf: Buffer, at: number): [string, number] {
+ const end = buf.indexOf(0, at);
+ return end < 0 ? [buf.toString('utf8', at), buf.length] : [buf.toString('utf8', at, end), end + 1];
+}
+
+function emit(file: string, record: Record<string, unknown>): void {
+ buffered.push(JSON.stringify(record));
+ if (!flushOnExit) { flushOnExit = true; process.on('exit', () => flush(file)); setInterval(() => flush(file), 1000).unref(); }
+ if (buffered.length >= 500) flush(file);
+}
+function flush(file: string): void {
+ if (!buffered.length) return;
+ const lines = buffered.join('\n') + '\n';
+ buffered = [];
+ try { appendFileSync(file, lines); } catch { /* a trace that cannot be written never fails the traced process */ }
+}
+
+function outgoing(c: TraceConnection, chunk: Buffer): void {
+ let buf = c.out ? Buffer.concat([c.out, chunk]) : chunk;
+ c.out = null;
+ while (!c.opaque) {
+ if (c.startup) {
+ if (buf.length < 8) break;
+ const len = buf.readInt32BE(0);
+ if (buf.readInt32BE(4) === SSL_REQUEST) { c.opaque = true; break; }
+ if (buf.length < len) break;
+ c.startup = false; buf = buf.subarray(len); continue;
+ }
+ if (buf.length < 5) break;
+ const total = 1 + buf.readInt32BE(1);
+ if (buf.length < total) break;
+ const type = buf[0]; const body = buf.subarray(5, total);
+ if (type === 0x50) { const [name, at] = cstring(body, 0); c.text = cstring(body, at)[0]; c.prepared.set(name, c.text); }
+ else if (type === 0x42) { const [, at] = cstring(body, 0); c.text = c.prepared.get(cstring(body, at)[0]) ?? c.text; }
+ else if (type === 0x45) c.executed = true;
+ else if (type === 0x51) c.pending.push({ sql: cstring(body, 0)[0], kind: 'simple', t: clock() });
+ else if (type === 0x53) { c.pending.push({ sql: c.text, kind: c.executed ? 'execute' : 'describe', t: clock() }); c.executed = false; }
+ else if (type === 0x48) c.pending.push({ sql: c.text, kind: 'describe', t: clock(), flush: true });
+ buf = buf.subarray(total);
+ }
+ if (!c.opaque && buf.length) c.out = Buffer.from(buf);
+}
+
+function message(c: TraceConnection, type: number, body: Buffer, file: string, label: string, pool: string): void {
+ if (type === 0x4b) c.backend = body.readInt32BE(0);
+ else if (type === 0x45 && c.pending[0]) {
+ for (let at = 0; at < body.length && body[at] !== 0;) {
+ const field = body[at]!; const [value, next] = cstring(body, at + 1); at = next;
+ if (field === 0x43) { c.pending[0].err = value; break; }
+ }
+ } else if (type === 0x5a || (type === 0x54 || type === 0x6e) && c.pending[0]?.flush) {
+ const done = c.pending.shift();
+ if (!done) return;
+ const end = clock();
+ emit(file, { t: Math.round(done.t * 1000) / 1000, ms: Math.round((end - done.t) * 1000) / 1000, pid: process.pid, label, pool,
+ conn: c.id, backend: c.backend, kind: done.kind, sql: done.sql.length > 2000 ? done.sql.slice(0, 2000) : done.sql, ...(done.err ? { err: done.err } : {}) });
+ }
+}
+
+function incoming(c: TraceConnection, chunk: Buffer, file: string, label: string, pool: string): void {
+ let at = 0;
+ while (at < chunk.length && !c.opaque) {
+ if (c.inLeft === 0) {
+ const take = Math.min(5 - c.inHeader.length, chunk.length - at);
+ c.inHeader = Buffer.concat([c.inHeader, chunk.subarray(at, at + take)]); at += take;
+ if (c.inHeader.length < 5) return;
+ c.inType = c.inHeader[0]!; c.inLeft = c.inHeader.readInt32BE(1) - 4; c.inHeader = Buffer.alloc(0);
+ c.inBody = KEEP_BODY.has(c.inType) ? [] : null;
+ if (c.inLeft === 0) { message(c, c.inType, Buffer.alloc(0), file, label, pool); continue; }
+ }
+ const take = Math.min(c.inLeft, chunk.length - at);
+ c.inBody?.push(chunk.subarray(at, at + take));
+ at += take; c.inLeft -= take;
+ if (c.inLeft === 0 && c.inBody) message(c, c.inType, Buffer.concat(c.inBody), file, label, pool);
+ }
+}
+
+async function tracedSocket(options: { host: string[]; port: number[]; path?: string | false }, file: string, label: string, pool: string): Promise<net.Socket> {
+ const opened = clock();
+ const socket = options.path ? net.connect(options.path) : net.connect(options.port[0]!, options.host[0]!);
+ await new Promise<void>((resolve, reject) => { socket.once('connect', resolve); socket.once('error', reject); });
+ const c: TraceConnection = { id: ++connections, backend: 0, prepared: new Map(), text: '', executed: false, pending: [{ sql: '<connect>', kind: 'connect', t: opened }], out: null,
+ startup: true, opaque: false, inHeader: Buffer.alloc(0), inType: 0, inLeft: 0, inBody: null };
+ const write = socket.write.bind(socket) as (chunk: unknown, ...rest: unknown[]) => boolean;
+ socket.write = ((chunk: unknown, ...rest: unknown[]) => {
+ if (!c.opaque && Buffer.isBuffer(chunk)) {
+ outgoing(c, chunk);
+ if (c.opaque) emit(file, { t: clock(), ms: 0, pid: process.pid, label, pool, conn: c.id, backend: 0, kind: 'tls_untraced', sql: '' });
+ }
+ return write(chunk, ...rest);
+ }) as typeof socket.write;
+ socket.on('data', (chunk: Buffer) => { if (!c.opaque) incoming(c, chunk, file, label, pool); });
+ return socket;
+}
+
+/** Returns `options` unchanged unless GBRAIN_SQL_TRACE names a file; then adds the tracing socket and a labelled application_name. */
+export function traceSqlOptions<T extends Record<string, unknown>>(options: T, pool: string): T {
+ const file = process.env.GBRAIN_SQL_TRACE;
+ if (!file) return options;
+ const label = process.env.GBRAIN_SQL_TRACE_LABEL || process.argv[2] || 'gbrain';
+ return {
+ ...options,
+ connection: { ...(options.connection as Record<string, unknown> | undefined), application_name: `gbrain:${label}:${process.pid}:${pool}`.slice(0, 63) },
+ socket: (o: { host: string[]; port: number[]; path?: string | false }) => tracedSocket(o, file, label, pool),
+ };
+}
diff --git a/test/e2e/sql-trace-postgres.test.ts b/test/e2e/sql-trace-postgres.test.ts
new file mode 100644
index 0000000000..a3b0eec4d8
--- /dev/null
+++ b/test/e2e/sql-trace-postgres.test.ts
@@ -0,0 +1,46 @@
+/**
+ * The env-gated SQL trace (src/core/sql-trace.ts, docs/eval/managed-sync-catchup.md)
+ * records one row per database round trip at the socket: tagged templates,
+ * `unsafe` with parameters (its unprepared describe round trip included),
+ * simple-protocol transaction control and the connection handshake, each
+ * attributed to the process label and the server backend pid.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+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-sql-trace-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+run('records each round trip with its statement, kind, label and backend pid', async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const file = join(dir, 'trace.jsonl');
+ await withEnv({ GBRAIN_SQL_TRACE: file, GBRAIN_SQL_TRACE_LABEL: 'e2e-trace' }, async () => {
+ const sql = postgres(url!, traceSqlOptions({ max: 1, onnotice: () => {} } as Record<string, unknown>, 'test') as Parameters<typeof postgres>[1]);
+ try {
+ const [{ pid }] = await sql`SELECT pg_backend_pid() AS pid`;
+ await sql.unsafe('SELECT $1::int AS n', [1]);
+ await sql.unsafe('SELECT $1::int AS n', [2]);
+ await sql.begin(tx => tx.unsafe('SELECT 1 AS one'));
+ const [{ app }] = await sql`SELECT current_setting('application_name') AS app`;
+ expect(app).toBe(`gbrain:e2e-trace:${process.pid}:test`);
+ await Bun.sleep(1200);
+ const rows = readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line) as { kind: string; sql: string; backend: number; label: string; pool: string; ms: number });
+ expect(rows.every(r => r.label === 'e2e-trace' && r.pool === 'test')).toBe(true);
+ 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']);
+ 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);
+ } finally { await sql.end(); }
+ });
+});
diff --git a/test/sql-trace.test.ts b/test/sql-trace.test.ts
new file mode 100644
index 0000000000..f675f89f79
--- /dev/null
+++ b/test/sql-trace.test.ts
@@ -0,0 +1,19 @@
+import { expect, test } from 'bun:test';
+import { traceSqlOptions } from '../src/core/sql-trace.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+test('the SQL trace is off by default and returns the pool options untouched', async () => {
+ await withEnv({ GBRAIN_SQL_TRACE: undefined }, async () => {
+ const options = { max: 2, connection: { statement_timeout: '5000' } };
+ expect(traceSqlOptions(options, 'read')).toBe(options);
+ });
+});
+
+test('GBRAIN_SQL_TRACE adds the tracing socket and labels application_name, keeping other connection parameters', async () => {
+ await withEnv({ GBRAIN_SQL_TRACE: '/tmp/gbrain-sql-trace-unit.jsonl', GBRAIN_SQL_TRACE_LABEL: 'cli-sync' }, async () => {
+ const traced = traceSqlOptions({ max: 2, connection: { statement_timeout: '5000' } } as Record<string, unknown>, 'direct');
+ expect(typeof traced.socket).toBe('function');
+ expect(traced.connection).toEqual({ statement_timeout: '5000', application_name: `gbrain:cli-sync:${process.pid}:direct` });
+ expect(traced.max).toBe(2);
+ });
+});