Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): title-only matching on the title arm's OR re-run only (strict local query unchanged, frozen goldens hold); keyword settings tests carry work_mem; vector walk change left for a follow-up
garrytanfaade57c772e
diff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.tsindex 85c38add6d..14e4bc6a39 100644--- a/src/core/engine-sql/titles.ts+++ b/src/core/engine-sql/titles.ts@@ -25,21 +25,23 @@* stays authoritative, so a mismatch can only miss, never promote.** Title predicate (title FTS; diagnosis credited to PR #5853 by morven-ai):- * the arm matches the title alone, which used to mean a per-row+ * remote callers and every OR re-run match the title alone, which used to mean a per-row* `to_tsvector(title)` that no index serves (a scan of every page in scope).* `pages.search_vector` carries the title, and only the title, at weight A* (schema trigger, `reindex-search-vector`, page-state projection), so the* arm matches `search_vector @@ q_a`, where `q_a` is the websearch query* with every lexeme labeled `:A`. That is served by `idx_pages_search`, and* negated or phrase terms are evaluated on title lexemes only, so timeline- * text (weight C) never changes which titles a caller sees. Ranking uses the+ * text (weight C) never changes which titles they see. Ranking uses the* weight-A slice (`ts_filter(..., '{a}')`). Matching follows the language* `search_vector` was built with; `gbrain reindex-search-vector` rebuilds it* after an FTS language change. A page with a NULL `search_vector` is absent* from the arm (the BEFORE INSERT/UPDATE trigger keeps it non-NULL). Local- * callers used to match the whole vector, so a date in a question pulled every- * dated timeline into `ts_rank_cd` on the OR fallback: 3-5 s on a large brain- * (#7135, diagnosed by @veltri-23 in #7136).+ * callers' strict query still matches and ranks the whole vector (title weight+ * A dominates); their OR re-run matches titles only, like remote callers,+ * because matching the whole vector let a date in a question pull every dated+ * timeline into `ts_rank_cd`: 3-5 s on a large brain (#7135, diagnosed by+ * @veltri-23 in #7136).*/import type { SearchOpts, SearchResult } from '../types.ts';import { searchLimitCap } from '../search/eval-pool-depth.ts';@@ -71,7 +73,7 @@ export async function searchTitles(if (opts?.limit && opts.limit > searchLimitCap()) {console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);}- const statementFor = (chunkManifest: boolean) => buildSearchTitlesStatement(query, opts, { ...dialect, chunkManifest });+ const statementFor = (chunkManifest: boolean, relaxed = false) => buildSearchTitlesStatement(query, opts, { ...dialect, chunkManifest, relaxed });const statement = statementFor(true);const run = (queryText: string, relaxed: boolean) => {const preferIndex = relaxed && dialect.relaxedPrefersIndex && !statement.safeChunks;@@ -81,7 +83,7 @@ export async function searchTitles(};const params = [...statement.params];params[0] = queryText;- return scoped(async exec => (await exec.unsafe(statementFor(await dialect.chunkManifest?.(exec) ?? true).sql, params)).rows,+ return scoped(async exec => (await exec.unsafe(statementFor(await dialect.chunkManifest?.(exec) ?? true, relaxed).sql, params)).rows,Object.keys(settings).length ? settings : undefined);};diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.tsindex 4bd0388a06..76148326e0 100644--- a/src/core/search/title-statement.ts+++ b/src/core/search/title-statement.ts@@ -29,6 +29,8 @@ export interface SearchTitlesDialect {staleProbe: boolean;/** chunkManifestReads; unset reads the manifest. */chunkManifest?: boolean;+ /** The relaxed (OR) re-run: match and rank title lexemes only, for local callers too (#7135). */+ relaxed?: boolean;}export interface SearchTitlesStatement {@@ -60,8 +62,9 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();const tsq = `websearch_to_tsquery('${ftsLang}', gbrain_fts_input($1))`;- const matchSql = `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}`;- const rankSql = `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})`;+ const titleOnly = safeChunks || dialect.relaxed === true;+ const matchSql = titleOnly ? `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}` : `p.search_vector @@ ${tsq}`;+ const rankSql = titleOnly ? `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})` : `ts_rank_cd(p.search_vector, ${tsq})`;const params: unknown[] = [boundWebsearchQuery(query), normalizeAlias(query), limit, offset];let filters = '';diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.tsindex f8fd6b4940..ed294f22b5 100644--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@ -25,35 +25,26 @@ export interface VectorPoolAttempt {* Runs the statement's index walk, then its scope scan (each when present),* before the pool. Walk rows answer the search when its window is full and* they fill the limit; scope-scan rows when they fill the limit or the scope- * ran out of eligible chunks (a short window). A full walk window that holds- * fewer pages than the limit (pages with many chunks) widens the walk the way- * the pool escalates (`nextInnerLimit`), so it returns the set the pool's- * widened attempt would, through the index, instead of handing a large brain- * to the joined statement, whose plan there is a full scan (GBRA-156).- * Otherwise, or past an attempt's 2 s budget, this returns null and the- * caller runs the pool. The walk may visit its whole over-fetched window, so- * its tuple budget covers it.+ * ran out of eligible chunks (a short window). Otherwise, or past an+ * attempt's 2 s budget, this returns null and the caller runs the pool. The+ * walk may visit its whole over-fetched window, so its tuple budget covers it.*/export async function searchIndexWalk(stmt: Pick<VectorSearchStatement, 'indexWalkSql' | 'scopeScanSql' | 'innerLimit' | 'indexWalkOverfetch'>,limit: number,run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,): Promise<Record<string, unknown>[] | null> {- const attempt = async (kind: { indexWalk: true } | { scopeScan: true }, innerLimit = stmt.innerLimit) => {+ const attempt = async (kind: { indexWalk: true } | { scopeScan: true }) => {try {- return await run({ innerLimit, maxScanTuples: Math.max(2_000, innerLimit * stmt.indexWalkOverfetch), remainingMs: 2_000, exact: false, ...kind });+ return await run({ innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch), remainingMs: 2_000, exact: false, ...kind });} catch (error) {if ((error as { code?: string }).code === '57014') return null;throw error;}};if (stmt.indexWalkSql) {- for (let innerLimit = stmt.innerLimit, escalations = 0; ; innerLimit = nextInnerLimit(innerLimit, stmt.innerLimit), escalations++) {- const batch = await attempt({ indexWalk: true }, innerLimit);- if (!batch || batch.candidatePool < innerLimit) break;- if (batch.rows.length >= limit) return batch.rows;- if (escalations >= MAX_POOL_ESCALATIONS) break;- }+ const batch = await attempt({ indexWalk: true });+ if (batch && batch.candidatePool >= stmt.innerLimit && batch.rows.length >= limit) return batch.rows;}if (stmt.scopeScanSql) {const batch = await attempt({ scopeScan: true });@@ -77,14 +68,6 @@ export async function searchIndexWalk(*/export const POOL_MAX_SCAN_TUPLES = 20_000;-/** How many times a short pool (and a walk whose full window holds too few pages) widens its window. */-const MAX_POOL_ESCALATIONS = 3;--/** The next, wider candidate window: four times the last, capped at 20,000 chunks (or the first window when that is larger). */-function nextInnerLimit(innerLimit: number, initialLimit: number): number {- return Math.min(innerLimit * 4, Math.max(initialLimit, 20_000));-}-export function remainingVectorBudget(deadline: number): number {const remaining = Math.floor(deadline - performance.now());if (remaining <= 0) throw Object.assign(new Error('Vector candidate deadline exhausted'), { code: '57014' });@@ -119,8 +102,8 @@ export async function searchVectorPool(if (remaining() === 0) { reason = 'deadline'; break; }if (!(await hasMore(batch.eligiblePool ?? batch.candidatePool, remaining()))) return batch.rows;}- if (escalations >= MAX_POOL_ESCALATIONS || (indexed && !iterative)) break;- innerLimit = nextInnerLimit(innerLimit, initialLimit);+ if (escalations >= 3 || (indexed && !iterative)) break;+ innerLimit = Math.min(innerLimit * 4, Math.max(initialLimit, 20_000));escalations++;}if (engine === 'postgres' && indexed && remaining() > 0) {diff --git a/test/postgres-engine.test.ts b/test/postgres-engine.test.tsindex a1fd3d9a2f..c1cea8ce8c 100644--- a/test/postgres-engine.test.ts+++ b/test/postgres-engine.test.ts@@ -82,7 +82,7 @@ describe('postgres-engine / search path timeout isolation', () => {test('both search methods bind a transaction-local timeout through the transaction settings', () => {const keyword = stripComments(extractMethod(SRC, 'searchKeyword'));const attempt = stripComments(SRC).split('private runVectorAttempt(')[1]!.split('async getEmbeddingsByChunkIds(')[0]!;- expect(keyword).toMatch(/settings: relaxed \? \{ statement_timeout: statementTimeout, enable_seqscan: 'off' \} : \{ statement_timeout: statementTimeout \}/);+ expect(keyword).toMatch(/settings: relaxed \? \{ statement_timeout: statementTimeout, enable_seqscan: 'off', \.\.\.KEYWORD_STATEMENT_SETTINGS \} : \{ statement_timeout: statementTimeout, \.\.\.KEYWORD_STATEMENT_SETTINGS \}/);// A thunk: the deadline's remaining budget is read after BEGIN, one round trip before the query.expect(attempt).toMatch(/settings: \(\) => vectorScanSettings\(iterative, innerLimit, maxScanTuples, deadline,/);});diff --git a/test/search-settings-one-statement.test.ts b/test/search-settings-one-statement.test.tsindex 8764b21889..a256f1ba7a 100644--- a/test/search-settings-one-statement.test.ts+++ b/test/search-settings-one-statement.test.ts@@ -119,15 +119,16 @@ describe('PostgresEngine.searchKeyword: statements per search transaction', () =return { engine, transactions };}- test('strict attempt: settings then query; OR fallback: the same two, with enable_seqscan off in the one settings statement', async () => {+ test('strict attempt: settings then query; OR fallback: the same two, with enable_seqscan off in the one settings statement (work_mem in both, GBRA-156)', async () => {const { engine, transactions } = recordingEngine();expect(await engine.searchKeyword('alpha beta', { orFallback: true })).toEqual([]);expect(transactions).toHaveLength(2);const [strict, relaxed] = transactions.map(statements => statements.map(s => s.sql.trim().split('\n')[0]!.slice(0, 60)));expect(strict).toEqual(["SELECT set_config('jit', $1, true), set_config('statement_ti", 'WITH ranked_chunks AS (']);expect(relaxed).toEqual(["SELECT set_config('jit', $1, true), set_config('statement_ti", 'WITH ranked_chunks AS (']);- expect(transactions[0]![0]!.params).toEqual(['off', '8000ms']);- expect(transactions[1]![0]!.sql).toBe("SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true), set_config('enable_seqscan', $3, true)");- expect(transactions[1]![0]!.params).toEqual(['off', '8000ms', 'off']);+ expect(transactions[0]![0]!.sql).toBe("SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true), set_config('work_mem', $3, true)");+ expect(transactions[0]![0]!.params).toEqual(['off', '8000ms', '32MB']);+ expect(transactions[1]![0]!.sql).toBe("SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true), set_config('enable_seqscan', $3, true), set_config('work_mem', $4, true)");+ expect(transactions[1]![0]!.params).toEqual(['off', '8000ms', 'off', '32MB']);});});diff --git a/test/search/title-arm-exact.test.ts b/test/search/title-arm-exact.test.tsindex 3bff3a0296..2298dbbc11 100644--- a/test/search/title-arm-exact.test.ts+++ b/test/search/title-arm-exact.test.ts@@ -7,10 +7,10 @@* so an identity page titled exactly "Acme" (created last) was buried under* 60+ "Acme weekly sync N" pages for local and remote callers.*- * Title predicate: every caller matches weight-A (title) lexemes of+ * Remote predicate: safe-chunks callers match weight-A (title) lexemes of* pages.search_vector. Parity cases compare against the previous title-only* predicate (`to_tsvector(lang, title) @@ websearch_to_tsquery(lang, q)`),- * so timeline text can never change which titles a caller sees.+ * so timeline text can never change which titles a remote caller sees.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../../src/core/engine.ts';diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex 171122fb0d..900bb4aa06 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -154,7 +154,7 @@ describe('searchTitles — D1 title candidate arm', () => {expect(tlHit.chunk_index).toBe(2); // lowest index when no compiled_truth chunk});- test('local callers match the title only: a timeline word is not a title hit, on the strict query or the OR fallback (#7135)', async () => {+ test('a local OR re-run matches the title only: a timeline word is not a relaxed title hit (#7135)', async () => {await engine.putPage('people/dated-entity', {type: 'person',title: 'Cobalt Meridian Atlas',@@ -170,8 +170,8 @@ describe('searchTitles — D1 title candidate arm', () => {expect(inVector.rows[0].hit).toBe(true);const slugs = async (q: string) => (await engine.searchTitles(q, { limit: 10 })).map(r => r.slug);- expect(await slugs('zircon quarry')).not.toContain('people/dated-entity');expect(await slugs('zircon nebulith')).not.toContain('people/dated-entity');+ expect(await slugs('quarry nebulith')).not.toContain('people/dated-entity');expect(await slugs('Cobalt Meridian')).toContain('people/dated-entity');expect(await slugs('Cobalt zircon')).toContain('people/dated-entity');});diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.tsindex c9a99f949e..8e562e5f48 100644--- a/test/search/vector-pool.test.ts+++ b/test/search/vector-pool.test.ts@@ -177,33 +177,6 @@ describe('first attempts: index walk, then scope scan', () => {expect(exhausted.attempts[0]).toMatchObject({ scopeScan: true, exact: false });});- test('a full walk window holding fewer pages than the limit widens the walk the way the pool escalates, before any joined statement', async () => {- // Many chunks per page: a full 100-chunk window covers 4 pages, 400 chunks cover 16.- const attempts: VectorPoolAttempt[] = [];- const result = await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 100, indexWalkOverfetch: 2 }, 10, async attempt => {- attempts.push(attempt);- return { rows: rows(Math.floor(attempt.innerLimit / 25)), candidatePool: attempt.innerLimit };- });- expect(result).toHaveLength(16);- expect(attempts.map(a => [a.indexWalk, a.innerLimit, a.maxScanTuples])).toEqual([[true, 100, 2000], [true, 400, 2000]]);- });-- test('a widened walk stops at the pool escalation cap and leaves the rest to the pool', async () => {- const attempts: number[] = [];- const result = await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 100, indexWalkOverfetch: 2 }, 10, async attempt => {- attempts.push(attempt.innerLimit);- return { rows: rows(2), candidatePool: attempt.innerLimit };- });- expect(result).toBeNull();- expect(attempts).toEqual([100, 400, 1600, 6400]);- const dry: number[] = [];- expect(await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 100, indexWalkOverfetch: 2 }, 10, async attempt => {- dry.push(attempt.innerLimit);- return { rows: rows(2), candidatePool: attempt.innerLimit === 100 ? 100 : 150 };- })).toBeNull();- expect(dry).toEqual([100, 400]);- });-test('a full scan window that stale rows left short, or a timed-out attempt, falls back to the pool', async () => {expect((await run({ scopeScanSql: 's' }, { scan: { rows: rows(8), candidatePool: 100, eligiblePool: 90 } })).result).toBeNull();expect((await run({ indexWalkSql: 'w' }, { walk: { rows: rows(4), candidatePool: 40 } })).result).toBeNull();