Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): keyword-mode pages read page and chunk rows after the limit (#7082)

garrytan07bd493292a7
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index e74f557274..c2e6581744 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
`fragment.ts` numbers placeholders at render time, so text is byte-identical to the tagged templates it replaced (`test/fixtures/goldens/sql-text/`). Capabilities (`maxBindParamsPerStatement`, `transactionAdvisoryLocks`, `probesEmbeddingCast`) carry the real engine differences; `docs/designs/refactor-wave-1/w1-inventory.md` classifies every method. Page-state orchestration stays in the engines: `putPage`'s transaction, page-key lock and revision check, and the `updateSlug` / `setPageAliases` transactions, call `pages.ts` on the transaction clone's executor; `getPage` / `readPageSnapshot` keep their SQL in `page-state/snapshot.ts`. Reads with an early return that must not open a scoped transaction (`listPrefixSampledPages`, `listCorpusSample`) take a `ScopedReadRunner`. Nothing here imports an engine façade (`check:layering`); SQL may splice only constant text (`check:engine-sql-dynamic`); brands are unforgeable (`check:engine-sql-brands`); engine SQL only shrinks (`check:engine-sql-ratchet`). Tests: docs/TESTING.md "Engine-sql".
- `src/core/engine-sql/facts.ts` `listFactsKeyset` + `src/core/engine-sql/pages.ts` keyset predicates — delta's two keyset reads. Both bind the cursor timestamp as `${value}::text::timestamptz`: a bare `::timestamptz` param is typed by the postgres.js driver, which serializes a string through a JS Date and truncates it to milliseconds (on Postgres that re-selected the whole last millisecond every wake and never drained a >limit cluster inside one millisecond). `listFactsKeyset` reads ascending `(created_at, id)` strictly after the keyset (`id: null` = strictly after the timestamp) and projects `created_at_iso` at column precision; recall's newest-first `listFactsSince` is unchanged. `test/engine-sql-facts-keyset.test.ts`, `test/delta-cursor-integrity.test.ts` (both engines).
-- `src/core/engine-sql/keyword-pages.ts` + `src/core/search/keyword-statement.ts` — the strict keyword count (`BrainEngine.countKeywordPages`) and the keyword-mode page query (`BrainEngine.searchKeywordPages`) for both engines. `buildKeywordMatch` is the ONE WHERE builder both statements read: `searchKeyword`'s strict match (websearch FTS on `content_chunks.search_vector`, or the CJK LIKE/ILIKE terms), never its OR retry, with the same page filters, hard excludes and `buildVisibilityClause` (private pages, safe chunks, so no private fence text). A query with slug handles (`search/keyword-handles.ts`) adds a second arm under the same filters, the chunks of the pages whose slug basename equals a handle (`idx_pages_slug_basename`), scored 1 + rank so they lead; the count is a `UNION` of both arms and `buildKeywordHandlePagesStatement` reads the handle arm alone for `searchKeyword`. The match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap) and orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips. Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.
+- `src/core/engine-sql/keyword-pages.ts` + `src/core/search/keyword-statement.ts` — the strict keyword count (`BrainEngine.countKeywordPages`) and the keyword-mode page query (`BrainEngine.searchKeywordPages`) for both engines. `buildKeywordMatch` is the ONE WHERE builder both statements read: `searchKeyword`'s strict match (websearch FTS on `content_chunks.search_vector`, or the CJK LIKE/ILIKE terms), never its OR retry, with the same page filters, hard excludes and `buildVisibilityClause` (private pages, safe chunks, so no private fence text). A query with slug handles (`search/keyword-handles.ts`) adds a second arm under the same filters, the chunks of the pages whose slug basename equals a handle (`idx_pages_slug_basename`), scored 1 + rank so they lead; the count is a `UNION` of both arms and `buildKeywordHandlePagesStatement` reads the handle arm alone for `searchKeyword`. The match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap), orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips, and pages those (page_id, chunk_id, score) rows before it reads the page and chunk rows it returns (#7082; `test/search/keyword-pages-limit-first.test.ts`, Postgres arm in `test/e2e/keyword-pages-limit-first-postgres.test.ts`). Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.
- `src/core/search/exact-scan.ts` + `src/core/ops/search-exact.ts` + `src/cli/search-exact-format.ts` — #7191: `search_exact` (CLI `gbrain search --exact`, routed in `cli/main.ts` before ranked-search flags parse): an unranked literal scan of `content_chunks.chunk_text` (words in order, any whitespace between, case-insensitive unless `case_sensitive`; the ARE comes from `phrasePattern`, with a LIKE prefilter on the longest word) in keyset batches of pages by id (`buildExactBatchStatement`), under ranked search's visibility (live page, unarchived source, quarantine, pinned questions, `chunkVisibleFilter`, source scope, private pages and the trust floor for untrusted callers, `safeChunksFilter` for remote) and the hard-excluded prefixes. `complete` is true only when the scope was scanned to the end with no `limit` or `deadline` stop and no unreadable page (`unchunked`, `projection_pending`, remote `unsealed`, `scan_timeout`); a Postgres statement timeout halves the batch, down to one page. `resume_after` continues a bounded scan. Registered `filtered` (`min_trust`, `stampPageTrust`), output redaction `retrieval`. Guide: [exact search](../../guides/exact-search.md). Tests: `test/search-exact.test.ts`, `test/e2e/search-exact-postgres.test.ts`.
- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers and every OR re-run match `ts_filter(search_vector, '{a}') @@ q` (weight A is the title alone) and rank on the same slice: served by the expression index `idx_pages_title_search` (GBRA-156, v267), which holds title lexemes only, so a term in timeline text never makes its page a candidate; title-only for negated and phrase terms, following the stored `search_vector` language. Postgres runs each attempt with the keyword statement's `work_mem` (`statementSettings`). Pages with a NULL `search_vector` are absent from the remote arm. #7471: a 2-4 word name query ORs in its given-name variants (`titleNameVariants`: "Matt Example" also matches the title "Matthew Example"), each its own bound websearch query; the OR fallback of a query of at most `RARITY_MAX_TERMS` words runs once per word in one scoped read and `rankByRarity` puts titles holding the rarest word first (ts_rank_cd knows no term rarity, so a surname's one title used to tie thousands of first-name titles and lose on page id). #7491: OR-retry titles holding every identifier the query names (`holdsIdentifiers`, search/keyword-identifier-probe.ts) lead untagged; the rest stay `keyword_relaxed`.
diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.ts
index f29713145e..f5fb9b2d8b 100644
--- a/src/core/search/keyword-statement.ts
+++ b/src/core/search/keyword-statement.ts
@@ -17,7 +17,11 @@
* (no global chunk cap: one page with hundreds of matching chunks cannot
* crowd the others out) and orders pages by (score DESC, page_id ASC), the
* keyset the cursor resumes from. Scores are float8 so a cursor's score
- * round-trips through JSON exactly.
+ * round-trips through JSON exactly. It pages those (page_id, chunk_id, score)
+ * rows first and only then reads the page and chunk rows it returns (#7082):
+ * the joins are inner primary-key lookups with no filter of their own, so the
+ * rows are the same, and a broad term no longer fetches a chunk row for every
+ * matching page.
*/
import type { SearchOpts } from '../types.ts';
import { escapeLikePattern, hasCJK, cjkMatchTerms } from '../cjk.ts';
@@ -144,15 +148,18 @@ function pagesStatement(m: KeywordMatch | null, page: KeywordPageWindow, handles
${arms.join('\n UNION ALL\n ')}
), best AS (
SELECT DISTINCT ON (page_id) page_id, chunk_id, score FROM matched ORDER BY page_id, score DESC, chunk_id ASC
+ ), kept AS (
+ SELECT b.page_id, b.chunk_id, b.score FROM best b
+ ${after}
+ ORDER BY b.score DESC, b.page_id ASC
+ LIMIT $${params.length - 1} OFFSET $${params.length}
)
SELECT p.slug, p.id AS page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source,
CASE WHEN ${messageId} THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
CASE WHEN ${messageId} THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
- cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, b.score, false AS stale
- FROM best b JOIN pages p ON p.id = b.page_id JOIN content_chunks cc ON cc.id = b.chunk_id -- chunk-visibility-ok: best holds only chunks the matched arms passed through keywordFilters (buildVisibilityClause with the chunk alias)
- ${after}
- ORDER BY b.score DESC, b.page_id ASC
- LIMIT $${params.length - 1} OFFSET $${params.length}`,
+ cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, k.score, false AS stale
+ FROM kept k JOIN pages p ON p.id = k.page_id JOIN content_chunks cc ON cc.id = k.chunk_id -- chunk-visibility-ok: kept holds only chunks the matched arms passed through keywordFilters (buildVisibilityClause with the chunk alias)
+ ORDER BY k.score DESC, k.page_id ASC`,
params,
};
}
diff --git a/test/e2e/keyword-pages-limit-first-postgres.test.ts b/test/e2e/keyword-pages-limit-first-postgres.test.ts
new file mode 100644
index 0000000000..42305780c2
--- /dev/null
+++ b/test/e2e/keyword-pages-limit-first-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../search/keyword-pages-limit-first.test.ts'));
diff --git a/test/search/keyword-pages-limit-first.test.ts b/test/search/keyword-pages-limit-first.test.ts
new file mode 100644
index 0000000000..410b5dc3bc
--- /dev/null
+++ b/test/search/keyword-pages-limit-first.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #7082: the keyword-mode page query pages each page's best (page_id,
+ * chunk_id, score) row first and reads the page and chunk rows only for the
+ * rows it returns. Before, it joined `pages` and `content_chunks` for every
+ * matching page and only then applied ORDER BY and LIMIT, so a broad term
+ * fetched one chunk row per matching page on every page of a cursor walk.
+ *
+ * Pinned on the executed plan on both engines (the Postgres arm runs through
+ * test/e2e/keyword-pages-limit-first-postgres.test.ts): the output's chunk
+ * read sits outside the statement's one Limit, and every join outside it
+ * handles at most `limit` rows (which access path reads them is the
+ * planner's choice on a fixture this small); and every offset and cursor
+ * window returns the rows of the unpaged ordering.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { buildKeywordPagesStatement } from '../../src/core/search/keyword-statement.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { TERM, seedKeywordCorpus } from '../helpers/keyword-paging-fixture.ts';
+
+type PlanNode = {
+ 'Node Type': string; 'Relation Name'?: string; Filter?: string; 'Index Cond'?: string; 'Recheck Cond'?: string;
+ 'Actual Rows'?: number; 'Actual Loops'?: number; Plans?: PlanNode[];
+};
+const planNodes = (node: PlanNode): PlanNode[] => [node, ...(node.Plans ?? []).flatMap(planNodes)];
+const LIMIT = 3;
+const shape = (rows: SearchResult[]) => rows.map(r => [r.slug, r.page_id, r.chunk_id, r.chunk_text, r.score]);
+
+for (const kind of testBackends()) {
+ describe(`keyword pages read page and chunk rows after the limit (${kind}, #7082)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let matching: string[];
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ matching = await seedKeywordCorpus(engine);
+ await engine.executeRaw('ANALYZE content_chunks');
+ await engine.executeRaw('ANALYZE pages');
+ }, 180_000);
+ afterAll(async () => { await close?.(); });
+
+ test('pages and content_chunks are joined for the output outside the Limit, on at most `limit` rows', async () => {
+ expect(matching.length).toBeGreaterThan(LIMIT * 5);
+ const stmt = buildKeywordPagesStatement(TERM, undefined, { limit: LIMIT })!;
+ const [row] = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: PlanNode }> }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${stmt.sql}`, stmt.params);
+ const plan = row!['QUERY PLAN'][0]!.Plan;
+ const limits = planNodes(plan).filter(node => node['Node Type'] === 'Limit');
+ expect(limits.length).toBe(1);
+ const limited = new Set(planNodes(limits[0]!));
+ const keyed = (node: PlanNode) => node['Relation Name'] === 'content_chunks'
+ && ![node.Filter, node['Index Cond'], node['Recheck Cond']].some(cond => cond?.includes('search_vector'));
+ const outside = planNodes(plan).filter(node => !limited.has(node));
+ expect(limits[0]!['Actual Rows']).toBe(LIMIT);
+ expect(outside.filter(keyed).length).toBe(1);
+ expect(planNodes(limits[0]!).filter(keyed)).toEqual([]);
+ const outputJoins = outside.filter(node => ['Nested Loop', 'Hash Join', 'Merge Join'].includes(node['Node Type']));
+ expect(outputJoins.length).toBeGreaterThan(0);
+ for (const join of outputJoins) expect((join['Actual Rows'] ?? 0) * (join['Actual Loops'] ?? 1)).toBeLessThanOrEqual(LIMIT);
+ });
+
+ test('every offset and cursor window returns the rows of the unpaged ordering', async () => {
+ const all = await engine.searchKeywordPages(TERM, undefined, { limit: 1000 });
+ expect(all.map(r => r.slug).sort()).toEqual([...matching].sort());
+ for (let offset = 0; offset < all.length; offset += LIMIT) {
+ expect(shape(await engine.searchKeywordPages(TERM, undefined, { limit: LIMIT, offset }))).toEqual(shape(all.slice(offset, offset + LIMIT)));
+ }
+ for (let at = 0; at + 1 < all.length; at += LIMIT) {
+ const after = { score: Number(all[at]!.score), page_id: Number(all[at]!.page_id) };
+ expect(shape(await engine.searchKeywordPages(TERM, undefined, { limit: LIMIT, after }))).toEqual(shape(all.slice(at + 1, at + 1 + LIMIT)));
+ }
+ });
+ });
+}