Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): title arm ranks pages before attaching the representative chunk (#5655)
garrytan5e2d5f90438b
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex da51ea5fcc..bc8deb9061 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1524,43 +1524,43 @@ export class PGLiteEngine implements BrainEngine {extraFilter += ` AND p.source_id = $${params.length}`;}- // Page grain — one row per page by construction, so no best_per_page- // pooling CTE is needed. The LEFT JOIN LATERAL picks the representative- // chunk (compiled_truth first, then lowest chunk_index); COALESCEs keep- // chunkless pages retrievable (the extreme D1 case: a title with no- // body) with the alias-hop row shape (chunk_id 0, empty chunk_text).+ // Page grain: one row per page, so no best_per_page pool. top_pages ranks+ // and limits first; the representative-chunk LATERAL (compiled_truth+ // first, then lowest chunk_index) and the stale probe then run per OUTPUT+ // row, not per matched page. Neither affects order, so rows are unchanged.+ // COALESCEs keep chunkless pages retrievable (chunk_id 0, empty text).// Accepted limitations (Reviewer F5/F6): the synthetic chunkless row// dedups on empty chunk_text (fusion's compiledTruthBoost skips it since- // #3695 — chunk_id 0 + empty chunk_text never gains chunk authority);- // and detail='low' filters only the REPRESENTATIVE — pages without a- // compiled_truth chunk still surface (unlike the keyword arm's filter).+ // #3695); detail='low' filters only the representative.const titlesSql =- `SELECT- p.slug, p.id as page_id, p.title, p.type, p.source_id,- p.effective_date, p.effective_date_source,+ `WITH top_pages AS (+ SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id,+ p.effective_date, p.effective_date_source, p.updated_at,+ ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score+ FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)+ ${extraFilter} ${hardExcludeClause} ${visibilityClause}+ ORDER BY score DESC, p.id ASC+ LIMIT $2 OFFSET $3+ )+ SELECT tp.slug, tp.page_id, tp.title, tp.type, tp.source_id,+ tp.effective_date, tp.effective_date_source,COALESCE(rep.id, 0) as chunk_id,COALESCE(rep.chunk_index, 0) as chunk_index,COALESCE(rep.chunk_text, '') as chunk_text,- COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,- ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,- CASE WHEN p.updated_at < (- SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id- ) THEN true ELSE false END AS stale- FROM pages p- JOIN sources s ON s.id = p.source_id+ COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source, tp.score,+ CASE WHEN tp.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te+ WHERE te.page_id = tp.page_id) THEN true ELSE false END AS stale+ FROM top_pages tpLEFT JOIN LATERAL (SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks cc- WHERE cc.page_id = p.id- AND cc.modality = 'text'+ WHERE cc.page_id = tp.page_id AND cc.modality = 'text'${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASCLIMIT 1) rep ON true- WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)- ${extraFilter} ${hardExcludeClause} ${visibilityClause}- ORDER BY score DESC, p.id ASC- LIMIT $2 OFFSET $3`;+ ORDER BY tp.score DESC, tp.page_id ASC`;let { rows } = await this.db.query(titlesSql, params);if (rows.length === 0) {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 8abd7b1091..db444ac93a 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1163,49 +1163,49 @@ export class PostgresEngine implements BrainEngine {params.push(offset);const offsetParam = `$${params.length}`;- // Page grain — one row per page by construction, so no best_per_page- // pooling CTE is needed. The LEFT JOIN LATERAL picks the representative- // chunk (compiled_truth first, then lowest chunk_index); COALESCEs keep- // chunkless pages retrievable (the extreme D1 case: a title with no- // body) with the alias-hop row shape (chunk_id 0, empty chunk_text).+ // Page grain: one row per page, so no best_per_page pool. top_pages ranks+ // and limits first; the representative-chunk LATERAL (compiled_truth+ // first, then lowest chunk_index) then runs per OUTPUT row, not per+ // matched page. It never affects order, so rows are unchanged.+ // COALESCEs keep chunkless pages retrievable (chunk_id 0, empty text).// Accepted limitations (Reviewer F5/F6): the synthetic chunkless row// dedups on empty chunk_text (fusion's compiledTruthBoost skips it since- // #3695 — chunk_id 0 + empty chunk_text never gains chunk authority);- // and detail='low' filters only the REPRESENTATIVE — pages without a- // compiled_truth chunk still surface (unlike the keyword arm's filter).+ // #3695); detail='low' filters only the representative.const rawQuery = `- SELECT- p.slug, p.id as page_id, p.title, p.type, p.source_id,- p.effective_date, p.effective_date_source,+ WITH top_pages AS (+ SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id,+ p.effective_date, p.effective_date_source,+ ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score+ FROM pages p+ JOIN sources s ON s.id = p.source_id+ WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)+ ${typeClause} ${typesClause} ${excludeSlugsClause}+ ${afterDateClause} ${beforeDateClause} ${sourceClause}+ ${hardExcludeClause}+ ${visibilityClause}+ ORDER BY score DESC, p.id ASC+ LIMIT ${limitParam}+ OFFSET ${offsetParam}+ )+ SELECT tp.slug, tp.page_id, tp.title, tp.type, tp.source_id,+ tp.effective_date, tp.effective_date_source,COALESCE(rep.id, 0) as chunk_id,COALESCE(rep.chunk_index, 0) as chunk_index,COALESCE(rep.chunk_text, '') as chunk_text,COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,- ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,+ tp.score,false AS stale- FROM pages p- JOIN sources s ON s.id = p.source_id+ FROM top_pages tpLEFT JOIN LATERAL (SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks cc- WHERE cc.page_id = p.id+ WHERE cc.page_id = tp.page_idAND cc.modality = 'text'${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASCLIMIT 1) rep ON true- WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)- ${typeClause}- ${typesClause}- ${excludeSlugsClause}- ${afterDateClause}- ${beforeDateClause}- ${sourceClause}- ${hardExcludeClause}- ${visibilityClause}- ORDER BY score DESC, p.id ASC- LIMIT ${limitParam}- OFFSET ${offsetParam}+ ORDER BY tp.score DESC, tp.page_id ASC`;// Same RLS scope-binding wrapper as searchKeyword (alwaysTransaction:diff --git a/test/search-titles-top-n.test.ts b/test/search-titles-top-n.test.tsnew file mode 100644index 0000000000..2f9b899f47--- /dev/null+++ b/test/search-titles-top-n.test.ts@@ -0,0 +1,95 @@+/**+ * Title arm: rank and limit pages BEFORE attaching the representative chunk.+ *+ * searchTitles returns at most `limit` page-grain rows, each decorated with a+ * representative chunk (LEFT JOIN LATERAL) and, on PGLite, a stale probe+ * over timeline_entries. Both decorations must run per OUTPUT row, not per+ * title-matched page: on a broad title match the per-page form did hundreds+ * of chunk lookups to serve a handful of rows.+ *+ * Pins (real PGLite):+ * - the executed statement's content_chunks / timeline_entries probes loop+ * at most `limit` times (EXPLAIN ANALYZE on the captured statement)+ * - rows, order, representative chunk, offset paging and the stale flag+ * are unchanged+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';++let engine: PGLiteEngine;+const PAGES = 30;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (let i = 0; i < PAGES; i++) {+ const slug = `notes/zephyr-${String(i).padStart(2, '0')}`;+ // Title term frequency varies so ranks differ; ties break on page id.+ const title = i % 3 === 0 ? `Zephyr zephyr report ${i}` : `Zephyr report ${i}`;+ await engine.putPage(slug, { type: 'note', title, compiled_truth: `body ${i}`, timeline: '' });+ await installFixtureChunks(engine, slug, [+ { chunk_index: 0, chunk_text: `timeline line ${i}`, chunk_source: 'timeline', token_count: 3 },+ { chunk_index: 1, chunk_text: `compiled body ${i}`, chunk_source: 'compiled_truth', token_count: 3 },+ ]);+ }+ await engine.executeRaw(+ `INSERT INTO timeline_entries (page_id, date, summary, created_at)+ SELECT id, '2026-01-01', 'later event', now() + interval '1 day' FROM pages WHERE slug = 'notes/zephyr-00'`,+ );+}, 120_000);++afterAll(async () => { await engine.disconnect(); }, 30_000);++function maxLoops(plan: Record<string, unknown>, relation: string): number {+ let max = 0;+ const walk = (node: Record<string, unknown>) => {+ if (node['Relation Name'] === relation) max = Math.max(max, Number(node['Actual Loops'] ?? 0));+ for (const child of (node.Plans as Record<string, unknown>[] | undefined) ?? []) walk(child);+ };+ walk(plan);+ return max;+}++describe('searchTitles decorates only the returned page rows', () => {+ test('chunk and timeline probes run at most `limit` times', async () => {+ const db = (engine as unknown as { db: { query: (sql: string, params?: unknown[]) => Promise<unknown> } }).db;+ const original = db.query.bind(db);+ let captured: { sql: string; params: unknown[] } | undefined;+ db.query = async (sql: string, params?: unknown[]) => {+ if (!captured && /websearch_to_tsquery/.test(sql)) captured = { sql, params: params ?? [] };+ return original(sql, params);+ };+ try {+ const rows = await engine.searchTitles('zephyr', { limit: 5 });+ expect(rows).toHaveLength(5);+ } finally {+ db.query = original;+ }+ expect(captured).toBeDefined();+ const explained = await original(`EXPLAIN (ANALYZE, FORMAT JSON) ${captured!.sql}`, captured!.params) as {+ rows: Array<Record<string, unknown>>;+ };+ const plan = (explained.rows[0]!['QUERY PLAN'] as Array<{ Plan: Record<string, unknown> }>)[0]!.Plan;+ expect(maxLoops(plan, 'content_chunks')).toBeLessThanOrEqual(5);+ expect(maxLoops(plan, 'timeline_entries')).toBeLessThanOrEqual(5);+ });++ test('rows, order, representative chunk, paging and stale are preserved', async () => {+ const all = await engine.searchTitles('zephyr', { limit: 50 });+ expect(all).toHaveLength(PAGES);+ for (let i = 1; i < all.length; i++) {+ const a = all[i - 1]!, b = all[i]!;+ expect(a.score > b.score || (a.score === b.score && a.page_id < b.page_id)).toBe(true);+ }+ for (const r of all) {+ expect(r.chunk_source).toBe('compiled_truth');+ expect(r.chunk_text).toBe(`compiled body ${Number(r.slug.slice(-2))}`);+ expect(r.stale).toBe(r.slug === 'notes/zephyr-00');+ }+ const page2 = await engine.searchTitles('zephyr', { limit: 5, offset: 5 });+ expect(page2.map(r => r.slug)).toEqual(all.slice(5, 10).map(r => r.slug));+ });+});