Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): bind the keyword rank query once, narrowing helper out of the engine; cold CLI round-trip budget e2e; bench slowest-sample report

garrytanc13e798e077d
diff --git a/scripts/bench/retrieval-scale/run.ts b/scripts/bench/retrieval-scale/run.ts
index 0a7d76efa9..fccbc2930c 100644
--- a/scripts/bench/retrieval-scale/run.ts
+++ b/scripts/bench/retrieval-scale/run.ts
@@ -129,7 +129,7 @@ async function main() {
const stageNames = new Set(ok.flatMap(x => Object.keys(x.stages ?? {})));
if (stageNames.size) row.stages_p50_ms = Object.fromEntries([...stageNames].map(k => [k, r0(pct(ok.map(x => x.stages?.[k] ?? 0), 0.5))]));
const worst = s.reduce((w, x, i) => (x.ok && x.ms > s[w]!.ms ? i : w), 0);
- if (s[worst]) row.slowest = { i: worst, ms: r0(s[worst]!.ms), ...(s[worst]!.stages ? { stages: s[worst]!.stages } : {}) };
+ if (s[worst]) row.slowest = { i: worst, ms: r0(s[worst]!.ms), target: op === 'get' ? pk(worst).slug : q(worst + opBase(op)), ...(s[worst]!.stages ? { stages: s[worst]!.stages } : {}) };
rows.push(row);
if (s[worst]?.stages) log(op + ' [' + mode + '] slowest i=' + worst + ' ' + JSON.stringify(row.slowest));
log(op + ' [' + mode + '] n=' + row.n + ' p50=' + row.p50_ms + ' p95=' + row.p95_ms + ' err=' + row.errors + (row.round_trips_p50 !== undefined ? ' trips=' + row.round_trips_p50 : '') + (row.startup_p50_ms !== undefined ? ' startup=' + row.startup_p50_ms + ' db=' + row.db_p50_ms + ' tail=' + row.tail_p50_ms : '') + (row.stages_p50_ms ? ' ' + JSON.stringify(row.stages_p50_ms) : ''));
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 25d04e51e8..5fe8a6cb58 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -114,8 +114,8 @@ import { logConnectionEvent } from './connection-audit.ts';
import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
-import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns, orFallbackTokens } from './search/sql-ranking.ts';
-import { narrowOrFallbackTokens, orTokenSharesSql } from './search/keyword-or-narrow.ts';
+import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';
+import { narrowedOrFallbackQuery } from './search/keyword-or-narrow.ts';
import { buildKeywordChunkMatch } from './search/keyword-chunk-match.ts';
import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
@@ -1097,9 +1097,7 @@ export class PostgresEngine implements BrainEngine {
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
- // An OR retry may match fewer terms than it ranks with (keyword-or-narrow.ts), so a caller that relaxes binds the rank query on its own.
const rankIdx = opts?.rankQuery ? params.push(opts.rankQuery) - 1 : opts?.orFallback ? params.push(params[0]) - 1 : 0;
- const rankParam = `$${rankIdx + 1}`;
const chunk = buildKeywordChunkMatch(ftsLang, opts?.excludePrivate);
const rawQuery = `
@@ -1112,7 +1110,7 @@ export class PostgresEngine implements BrainEngine {
CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
- ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', ${rankParam})) * ${sourceFactorCase} AS score
+ ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $${rankIdx + 1})) * ${sourceFactorCase} AS score
FROM ${chunk.from}
JOIN pages p ON p.id = cc.page_id
JOIN sources s ON s.id = p.source_id
@@ -1154,9 +1152,7 @@ export class PostgresEngine implements BrainEngine {
const runKeyword = (queryText: string, relaxed = false, rankText = queryText) => this.keywordTimeouts.run(opts?.keywordTimeoutCache === true, this,
[statementTimeout, relaxed, rawQuery, collapseWebsearchDashRuns(queryText), collapseWebsearchDashRuns(rankText), params.slice(1), opts?.sourceIds ?? null, opts?.sourceId ?? null], () =>
this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, (tx) => {
- const boundParams = [...params];
- boundParams[0] = collapseWebsearchDashRuns(queryText);
- if (rankIdx > 0 && !opts?.rankQuery) boundParams[rankIdx] = collapseWebsearchDashRuns(rankText);
+ const boundParams = params.map((v, i) => i === 0 ? collapseWebsearchDashRuns(queryText) : i === rankIdx && !opts?.rankQuery ? collapseWebsearchDashRuns(rankText) : v);
return tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);
}, { alwaysTransaction: true, jitOff: true, settings: relaxed ? { statement_timeout: statementTimeout, enable_seqscan: 'off' } : { statement_timeout: statementTimeout } }));
let rows = await runKeyword(query);
@@ -1172,12 +1168,7 @@ export class PostgresEngine implements BrainEngine {
if (rows.length === 0 && opts?.orFallback) {
const orQuery = buildOrFallbackWebsearchQuery(query);
if (orQuery) {
- // Match only the rarest terms within the cap (search/keyword-or-narrow.ts); a failed statistics read keeps them all.
- const shares = await this.executeRaw<{ token: string; lexemes: number; share: number | null; rows: number; analyzed: boolean }>(orTokenSharesSql(ftsLang), [orFallbackTokens(query)]).catch(() => []);
- const narrowed = shares[0]?.analyzed
- ? narrowOrFallbackTokens(shares.map(r => ({ token: r.token, lexemes: Number(r.lexemes), share: r.share === null ? null : Number(r.share) })), Number(shares[0].rows))
- : null;
- rows = await runKeyword(narrowed ? narrowed.join(' OR ') : orQuery, true, orQuery);
+ rows = await runKeyword(await narrowedOrFallbackQuery((sql, p) => this.executeRaw(sql, p), query, ftsLang) ?? orQuery, true, orQuery);
// 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's
// fusion can demote them — an OR-of-common-terms match must not
// outvote a healthy vector arm (SearchResult.keyword_relaxed doc).
diff --git a/src/core/search/keyword-or-narrow.ts b/src/core/search/keyword-or-narrow.ts
index a29399e874..4f087f1ee1 100644
--- a/src/core/search/keyword-or-narrow.ts
+++ b/src/core/search/keyword-or-narrow.ts
@@ -11,12 +11,15 @@
* (rare, so cheap to match, or absent), then adds the tracked terms rarest
* first while their estimated matches stay within OR_FALLBACK_MATCH_CAP, and
* always the rarest tracked one, so a retry never rests on terms that may
- * match nothing. It still ranks with the full OR query, so a retained chunk
+ * match nothing. It still ranks with the full OR query (searchKeyword binds
+ * the rank query as its own parameter whenever it may relax), so a retained chunk
* scores exactly as before; a chunk that holds only the dropped, most common
* terms is no longer a candidate. Without statistics (never analyzed), or
* when every term fits, the retry is unchanged.
*/
+import { orFallbackTokens } from './sql-ranking.ts';
+
/** Estimated chunk matches the tracked terms of an OR retry may add: about 0.2 s of ts_rank on the 2M-chunk bench. */
export const OR_FALLBACK_MATCH_CAP = 20_000;
@@ -66,3 +69,19 @@ export function narrowOrFallbackTokens(tokens: OrTokenShare[], rows: number, cap
if (kept.length === 0 || kept.length === words.length) return null;
return kept;
}
+
+/**
+ * The websearch text an OR retry of `query` should match, or null to match
+ * the full OR query. `read` runs one statement; a failed statistics read
+ * keeps every term.
+ */
+export async function narrowedOrFallbackQuery(
+ read: (sql: string, params: unknown[]) => Promise<Array<{ token: string; lexemes: number; share: number | null; rows: number; analyzed: boolean }>>,
+ query: string,
+ ftsLang: string,
+): Promise<string | null> {
+ const shares = await read(orTokenSharesSql(ftsLang), [orFallbackTokens(query)]).catch(() => []);
+ if (!shares[0]?.analyzed) return null;
+ const kept = narrowOrFallbackTokens(shares.map(r => ({ token: r.token, lexemes: Number(r.lexemes), share: r.share === null ? null : Number(r.share) })), Number(shares[0].rows));
+ return kept ? kept.join(' OR ') : null;
+}
diff --git a/test/e2e/retrieval-round-trip-budget.test.ts b/test/e2e/retrieval-round-trip-budget.test.ts
new file mode 100644
index 0000000000..a2c2244c7d
--- /dev/null
+++ b/test/e2e/retrieval-round-trip-budget.test.ts
@@ -0,0 +1,80 @@
+/**
+ * GBRA-156: round trips one cold CLI read pays on Postgres, counted at the
+ * socket by the env-gated wire trace (src/core/sql-trace.ts). On a pooled
+ * brain every round trip costs the pooler RTT, so the count is the cold-path
+ * latency that a CI runner can measure without noise: at 40 ms RTT, a cold
+ * search on v0.60.328.0 paid about 113 round trips (4.3 s) against 55 for the
+ * same search in a running `gbrain serve`
+ * (scripts/bench/retrieval-scale/run.ts --trace).
+ *
+ * Counted: `execute` and `simple` records (statements) and `connect`
+ * records. `describe` records are the extra round trip a statement pays the
+ * first time a connection prepares it; which connection runs a statement is
+ * not deterministic, so they are reported, not budgeted.
+ *
+ * Budgets sit about 10% above the counts measured when they were set. Lower
+ * one in the change that removes round trips; raising one is a reviewer-
+ * visible act that names what the new round trips buy.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { readSqlTrace } from '../helpers/statement-counter.ts';
+import { seedPage } from '../helpers/keyword-paging-fixture.ts';
+
+const CLI = join(import.meta.dir, '../../src/cli.ts');
+/** Measured on v0.60.328.0 with no provider keys (keyword search): search 100, get 25, recall 35. */
+const BUDGET: Record<string, number> = { search: 110, get: 28, recall: 39 };
+
+const run = process.env.DATABASE_URL ? describe : describe.skip;
+let home = '';
+let close: () => Promise<void> = async () => {};
+
+async function coldRoundTrips(args: string[]): Promise<{ trips: number; describes: number; code: number; stderr: string }> {
+ const trace = join(home, `trace-${args[0]}-${Date.now()}.jsonl`);
+ const env: Record<string, string> = { ...process.env as Record<string, string>, GBRAIN_HOME: home, GBRAIN_SQL_TRACE: trace, GBRAIN_NO_UPDATE_CHECK: '1', GBRAIN_TELEMETRY: '0' };
+ for (const key of ['OPENAI_API_KEY', 'VOYAGE_API_KEY', 'ANTHROPIC_API_KEY', 'GEMINI_API_KEY', 'DATABASE_URL', 'GBRAIN_DATABASE_URL']) delete env[key];
+ const proc = Bun.spawn([process.execPath, CLI, ...args], { env, stdout: 'ignore', stderr: 'pipe' });
+ const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
+ const records = readSqlTrace(trace);
+ return {
+ trips: records.filter(r => r.kind === 'execute' || r.kind === 'simple' || r.kind === 'connect').length,
+ describes: records.filter(r => r.kind === 'describe').length,
+ code,
+ stderr,
+ };
+}
+
+run('cold CLI read round trips on Postgres', () => {
+ beforeAll(async () => {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ close = isolated.close;
+ for (let i = 0; i < 12; i++) await seedPage(isolated.engine, `notes/orbital-ledger-${i}`, `Orbital ledger entry ${i}: the quasar survey moved to week ${i}.`, { title: `Orbital Ledger ${i}` });
+ await isolated.engine.disconnect();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-rt-budget-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: isolated.databaseUrl }));
+ }, 300_000);
+
+ afterAll(async () => {
+ await close();
+ if (home) rmSync(home, { recursive: true, force: true });
+ });
+
+ for (const [verb, args] of [
+ ['search', ['search', 'quasar survey', '--json']],
+ ['get', ['get', 'notes/orbital-ledger-3']],
+ ['recall', ['recall', 'quasar survey', '--json']],
+ ] as const) {
+ test(`${verb} stays within its round-trip budget`, async () => {
+ await coldRoundTrips([...args]);
+ const measured = await coldRoundTrips([...args]);
+ console.log(`[round-trips] ${verb}: ${measured.trips} (+${measured.describes} describe)`);
+ expect(measured.code, measured.stderr.slice(-2000)).toBe(0);
+ expect(measured.trips).toBeGreaterThan(0);
+ expect(measured.trips).toBeLessThanOrEqual(BUDGET[verb]!);
+ }, 120_000);
+ }
+});