Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keyword search finds the people behind a reworded relationship question again (GST-2899) (#9592)
Garry Tan4737c26e3c05
diff --git a/behavior-changes.d/title_retry_reads_timelines_gst2899.md b/behavior-changes.d/title_retry_reads_timelines_gst2899.mdnew file mode 100644index 0000000000..2a70a44b8b--- /dev/null+++ b/behavior-changes.d/title_retry_reads_timelines_gst2899.md@@ -0,0 +1,4 @@+---+kind: fix+---+Keyword search finds the people behind a reworded relationship question again. When no page holds every word of a question, the title step retries with any word; since v0.60.338.0 (#7135) that retry read page titles only, so a question that names a company in words its people's pages don't use ("Who is on the payroll at Acme?") lost the people whose timeline names the company. For a local caller the retry now reads titles and timelines while at most 5,000 pages match the question's words, and titles only past that, so a date or a very common word in a question still doesn't pull every dated timeline into ranking. Remote MCP callers still match titles only. Results for such questions can change order, and on a very large brain the retry adds one bounded statement (0.03 to 0.14 s measured at 1,000,000 pages).diff --git a/changelog.d/capy-keyword-reworded-recall.md b/changelog.d/capy-keyword-reworded-recall.mdnew file mode 100644index 0000000000..5480d6e80e--- /dev/null+++ b/changelog.d/capy-keyword-reworded-recall.md@@ -0,0 +1,8 @@+**Keyword search finds the people behind a reworded relationship question again.**++### Fixed+- On a brain with no embedding provider, a question that names a company in words its people's pages don't use ("Who is on the payroll at Acme?") returned the company page and little else. Since v0.60.338.0 (#7135) the title step's any-word retry read page titles only, so it no longer saw the people whose dated timeline names the company. For a local caller the retry now reads titles and timelines again while at most 5,000 pages match the question's words, and titles only past that, so a date or a very common word in a question still can't pull every dated timeline into ranking. Remote MCP callers are unchanged.+- On the public one-hop relationship set (870 keyless rows), recall at 5 for reworded questions went from 0.381 to 0.573 with relational retrieval off and from 0.512 to 0.661 with it on, on both PGLite and Postgres.+- On a 1,000,000-page Postgres brain the retry adds one bounded statement, 0.03 to 0.14 s in the cases measured.++<!-- behavior-change: title_retry_reads_timelines_gst2899 -->diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 70245b2c36..491de87f56 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`. #7082: a local caller's strict attempt matches the whole vector but ranks at most `titleWholeVectorCandidates()` (5,000) matching pages, the lowest page ids (the `candidates` CTE, ordered by id); a cut attempt reports `keyword_candidates_incomplete` (reason `candidate_budget`) and puts the title-only statement's rows first.+- `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 the title-only 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`. #7082: a local caller's strict attempt matches the whole vector but ranks at most `titleWholeVectorCandidates()` (5,000) matching pages, the lowest page ids (the `candidates` CTE, ordered by id); a cut attempt reports `keyword_candidates_incomplete` (reason `candidate_budget`) and puts the title-only statement's rows first. GST-2899: a local caller's OR re-run first runs the whole-vector statement with `completeOnly` (the same cap, an unordered count, rows only when every matching page fits, else one row marked `candidates_cut`), so a reworded question still reaches pages whose timeline names its subject; when the set does not fit (a date, a common word) it runs the title-only statement as before. Plan proof: `test/e2e/title-any-word-retry-postgres.test.ts`.- `src/core/engine-sql/page-lookup.ts` + `src/core/page-find.ts` + `src/core/page-counts.ts` + `src/core/ops/find-pages.ts` + `src/core/ops/stats-by.ts` + `src/cli/format-page-lookup.ts` — find-by-name and grouped counts (`gbrain find` / `find_pages`, `gbrain stats --by` / `get_stats` `by`, `since`, `collapse_aliases`). `parseFindPattern` turns a glob (`*`/`?`, whole slug or source path), a slug prefix (contains `/`) or a name (title or last slug segment substring) into one `escapeLikePattern`-escaped ILIKE pattern; names are served by `idx_pages_trgm` + `idx_pages_slug_trgm`, while globs and prefixes also match `source_path` (no trigram index). Rows sort by slug then source in the C collation, carry `count(*) OVER ()` as `total`, and the op reports `complete` (limit default 50, cap 500 local, 100 remote). Find hides the ranked-search hard excludes (`resolveHardExcludes` + `buildHardExcludeClause`) unless the pattern's literal lead is inside one, and names them in `hidden_prefixes`. `countPagesBy` returns per (source, type) counts plus raw and distinct-slug totals (per type group through an `unnest` mapping and GROUPING SETS), so cross-source twins are never silently double counted; `since` is the query effective-date bound (`resolveDateBoundary`). Every caller sees live pages in unarchived sources; a remote caller's `readPolicyOpts` policy adds `pageReadFilter(..., live)`. `collapseTypes` lets the active pack decide (declared stays, alias joins canonical), else normalizes (last segment, lower case, singular) and joins a `-<name>` suffix to an existing group; each group lists `member_types` with its rule (`exact`, `pack_alias`, `normalized`, `suffix`). Without the grouping params `get_stats` returns its unchanged counters. Tests: `test/page-find-pattern-7191.test.ts`, `test/page-lookup-7191.test.ts` (Postgres arm: `test/e2e/page-lookup-7191.test.ts`).- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin).diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex aab59575f6..61bd9ed4f8 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -540,7 +540,9 @@ carries `keyword_candidates_incomplete` when that bound applies). For a localcaller, hybrid search's title step ranks at most 5,000 of the pages whose titleor timeline matches (the lowest page ids) and reports the same`keyword_candidates_incomplete` when it cuts; a remote caller's title step-matches titles only. A local+matches titles only. When no page holds every word of the question, a local+caller's title step retries with any word: it reads titles and timelines while+at most 5,000 pages match, and titles only past that. A localcaller's keyword statement usually stops reading matches at the 50,000 bound. A remote MCPcaller's arm stops there when the call sets no type, frontmatter or date filterand no source scope narrower than every live source; with such a filter itdiff --git a/llms-full.txt b/llms-full.txtindex faed8c51cb..883419fa9d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9470,7 +9470,9 @@ carries `keyword_candidates_incomplete` when that bound applies). For a localcaller, hybrid search's title step ranks at most 5,000 of the pages whose titleor timeline matches (the lowest page ids) and reports the same`keyword_candidates_incomplete` when it cuts; a remote caller's title step-matches titles only. A local+matches titles only. When no page holds every word of the question, a local+caller's title step retries with any word: it reads titles and timelines while+at most 5,000 pages match, and titles only past that. A localcaller's keyword statement usually stops reading matches at the 50,000 bound. A remote MCPcaller's arm stops there when the call sets no type, frontmatter or date filterand no source scope narrower than every live source; with such a filter itdiff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.tsindex cf79026ab0..bb1e2e7756 100644--- a/src/core/engine-sql/titles.ts+++ b/src/core/engine-sql/titles.ts@@ -38,10 +38,13 @@* 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' 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). The strict attempt ranks at most+ * A dominates). Their any-word retry (the OR re-run) matches the whole vector+ * too while every matching page fits `titleWholeVectorCandidates()`, and+ * titles only, like remote callers, when the set does not fit. Unbounded, it+ * 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). Titles alone+ * lost the pages whose timeline names what a reworded question asks about+ * ("Who is on the payroll at Acme?", GST-2899). The strict attempt ranks at most* `titleWholeVectorCandidates()` matching pages (#7082: a very common word* otherwise read every matching vector until the statement timeout). The whole* vector is the only lexical path to timeline_entries rows no chunk holds, so a@@ -83,30 +86,31 @@ 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, relaxed = false) => buildSearchTitlesStatement(query, opts, { ...dialect, chunkManifest, relaxed });+ type Attempt = { text: string; kind: 'whole' | 'title' | 'complete' };+ const statementFor = (chunkManifest: boolean, kind: Attempt['kind'] = 'whole') => buildSearchTitlesStatement(query, opts, { ...dialect, chunkManifest, relaxed: kind === 'title', completeOnly: kind === 'complete' });const statement = statementFor(true);- /** One scoped read running the statement once per query text ($1), in order. */- const run = (queryTexts: string[], relaxed: boolean, top?: number) => {- const preferIndex = relaxed && dialect.relaxedPrefersIndex && !statement.safeChunks;+ /** One scoped read running one statement per attempt, in order; `top` replaces the caller's limit and offset. */+ const run = (attempts: Attempt[], anyWord: boolean, top?: number) => {+ const preferIndex = anyWord && dialect.relaxedPrefersIndex && !statement.safeChunks;const settings = {...(dialect.statementTimeout ? { statement_timeout: dialect.statementTimeout } : {}),...dialect.statementSettings,...(preferIndex ? { enable_seqscan: 'off' } : {}),};return scoped(async exec => {- const sql = statementFor(await dialect.chunkManifest?.(exec) ?? true, relaxed).sql;+ const manifest = await dialect.chunkManifest?.(exec) ?? true;const lists = [];- for (const text of queryTexts) lists.push((await exec.unsafe(sql, [text, statement.params[1], ...(top === undefined ? statement.params.slice(2, 4) : [top, 0]), ...statement.params.slice(4)])).rows);+ for (const a of attempts) lists.push((await exec.unsafe(statementFor(manifest, a.kind).sql, [a.text, statement.params[1], ...(top === undefined ? statement.params.slice(2, 4) : [top, 0]), ...statement.params.slice(4)])).rows);return lists;}, Object.keys(settings).length ? settings : undefined);};const strictQuery = statement.params[0] as string;const limit = statement.params[2] as number, offset = statement.params[3] as number;- const [rows] = await run([strictQuery], false, offset + limit);+ const [rows] = await run([{ text: strictQuery, kind: 'whole' }], false, offset + limit);if (rows.length > 0 && rows[0].candidates_cut === true) {opts?.onKeywordIncomplete?.('candidate_budget');- const [titleRows] = await run([strictQuery], true, offset + limit);+ const [titleRows] = await run([{ text: strictQuery, kind: 'title' }], true, offset + limit);const titled = new Set(titleRows.map(r => r.page_id));return [...titleRows, ...rows.filter(r => !titled.has(r.page_id))].slice(offset, offset + limit).map(rowToSearchResult);}@@ -115,8 +119,12 @@ export async function searchTitles(if (!orQuery) return [];const terms = orFallbackTokens(strictQuery);const rarity = terms.length <= RARITY_MAX_TERMS && !opts?.offset;- const [orRows, ...wordLists] = await run([boundWebsearchQuery(orQuery), ...(rarity ? terms : [])], true);- const relaxedRows = (rarity ? rankByRarity(orRows, wordLists, statement.params[2] as number) : orRows).map(rowToSearchResult);+ const anyWord = boundWebsearchQuery(orQuery);+ const wordAttempts: Attempt[] = rarity ? terms.map(text => ({ text, kind: 'title' })) : [];+ // A local caller's retry matches timelines too while every matching page fits the cap; otherwise, and for remote callers, titles alone.+ let [orRows, ...wordLists] = await run([{ text: anyWord, kind: statement.safeChunks ? 'title' : 'complete' }, ...wordAttempts], true);+ if (orRows[0]?.candidates_cut === true && !statement.safeChunks) [orRows] = await run([{ text: anyWord, kind: 'title' }], true);+ const relaxedRows = (rarity ? rankByRarity(orRows, wordLists, limit) : orRows).map(rowToSearchResult);// 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's fusion can// demote them (SearchResult.keyword_relaxed). #7491: a title holding every// identifier the query names (search/keyword-identifier-probe.ts) is thediff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.tsindex 9f9921282e..7afc7b925c 100644--- a/src/core/search/title-statement.ts+++ b/src/core/search/title-statement.ts@@ -31,8 +31,15 @@ export interface SearchTitlesDialect {staleProbe: boolean;/** chunkManifestReads; unset reads the manifest. */chunkManifest?: boolean;- /** Match and rank title lexemes only, for local callers too: the OR re-run (#7135) and the cut strict attempt (#7082). */+ /** Match and rank title lexemes only, for local callers too: the OR re-run whose whole-vector matches do not fit the cap (#7135) and the cut strict attempt (#7082). */relaxed?: boolean;+ /**+ * A local caller's OR re-run (GST-2899): rank the whole-vector matches only when all of them fit+ * `titleWholeVectorCandidates()`; a set that does not fit returns one row of nulls marked `candidates_cut`, and only then+ * does the caller run the title-only statement. The candidate count has no ORDER BY, since nothing is cut from it: ordered by page id it walked+ * pages_pkey for a word on a few percent of pages (about 0.8 s at 1,000,000 pages against 40 ms from idx_pages_search).+ */+ completeOnly?: boolean;}/**@@ -134,7 +141,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undJOIN sources s ON s.id = p.source_idWHERE ${matchSql}${pageFilters}- ORDER BY p.id+ ${dialect.completeOnly ? '' : 'ORDER BY p.id'}LIMIT ${wholeVectorCandidates + 1}),` : ''}top_pages AS (@@ -144,7 +151,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und${rankSql} * ${sourceFactorCase} AS scoreFROM ${capped ? `(SELECT id FROM candidates ORDER BY id LIMIT ${wholeVectorCandidates}) c JOIN pages p ON p.id = c.id` : 'pages p'}JOIN sources s ON s.id = p.source_id- WHERE ${capped ? 'true' : `${matchSql}+ WHERE ${capped ? (dialect.completeOnly ? `(SELECT count(*) FROM candidates) <= ${wholeVectorCandidates}` : 'true') : `${matchSql}${pageFilters}`}ORDER BY exact_title DESC, score DESC, p.id ASCLIMIT $3 OFFSET $4@@ -158,7 +165,8 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undtp.score,${staleSql} AS stale,${capped ? `(SELECT count(*) FROM candidates) > ${wholeVectorCandidates}` : 'false'} AS candidates_cut- FROM top_pages tp+ FROM ${dialect.completeOnly ? `(SELECT (SELECT count(*) FROM candidates) > ${wholeVectorCandidates} AS cut) k+ LEFT JOIN top_pages tp ON true` : 'top_pages tp'}LEFT JOIN LATERAL (SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks cc@@ -168,6 +176,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASCLIMIT 1) rep ON true+ ${dialect.completeOnly ? 'WHERE tp.page_id IS NOT NULL OR k.cut' : ''}ORDER BY tp.exact_title DESC, tp.score DESC, tp.page_id ASC`;return { sql, params, safeChunks };diff --git a/test/e2e/title-any-word-retry-postgres.test.ts b/test/e2e/title-any-word-retry-postgres.test.tsnew file mode 100644index 0000000000..6408663aa7--- /dev/null+++ b/test/e2e/title-any-word-retry-postgres.test.ts@@ -0,0 +1,111 @@+/**+ * The any-word retry's whole-vector statement on PostgreSQL (GST-2899). A local+ * caller's retry matches titles and timelines while every matching page fits the+ * title cap (search/title-statement.ts `completeOnly`), and otherwise falls back+ * to the title-only statement. Its candidate count has no ORDER BY: nothing is cut+ * from a set that must fit whole, and an ordered count walked pages_pkey for a+ * word on a few percent of a large brain (13 ms to about 800 ms at 1,000,000+ * pages). These tests EXPLAIN the statement the engine runs, with statistics from+ * ANALYZE on a 12,000-page fixture, and require the candidates to come from the+ * GIN index `idx_pages_search`, never from a walk of `pages_pkey`: once with no+ * planner setting changed, and once with the `enable_seqscan = off` the engine+ * sets for a local any-word retry. Pages carry 14 timeline lines so the table is+ * large enough for the planner to price the index against a scan.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS } from '../../src/core/postgres-engine/keyword-statement-timeout.ts';+import { boundWebsearchQuery, buildOrFallbackWebsearchQuery } from '../../src/core/search/sql-ranking.ts';+import { __setTitleWholeVectorCandidatesForTests, buildSearchTitlesStatement, titleWholeVectorCandidates } from '../../src/core/search/title-statement.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';++const POSTGRES_DIALECT = { statementTimeout: `${KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS}ms`, relaxedPrefersIndex: true, staleProbe: false };+const DEFAULT_CAP = titleWholeVectorCandidates();+/** Pages whose timeline names each fixture word: 4 of 12,000 (rare) and 600 of 12,000 (5%). */+const RARE = 4, FEW_PERCENT = 600;++describe('local any-word title retry (postgres)', () => {+ let engine: PostgresEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ ({ engine, close } = await isolatedPersistencePostgres(requirePostgresTestDatabase()));+ // No title holds either word: only the timeline (search_vector weight C) does.+ await engine.executeRaw(+ `INSERT INTO pages (slug, type, title, compiled_truth, timeline)+ SELECT 'notes/filler-' || g, 'note', 'Filler page ' || g, 'Common body ' || g,+ (SELECT string_agg('- 2026-01-' || lpad(j::text, 2, '0') || ': ' || substr(md5((g * 31 + j)::text), 1, 8) || ' ' || substr(md5((g * 17 + j * 3)::text), 1, 8)+ || ' ' || substr(md5((g + j * 101)::text), 1, 8) || ' ' || substr(md5((g * 3 + j * 7)::text), 1, 8), E'\\n') FROM generate_series(1, 14) j)+ || CASE WHEN g % 3000 = 0 THEN E'\\n- 2026-02-06: zorbex visit' ELSE '' END+ || CASE WHEN g % 20 = 0 THEN E'\\n- 2026-03-07: tarsik call' ELSE '' END+ FROM generate_series(1, 12000) g`);+ // A page is searchable once its text projection matches its knowledge revision, as the projection worker leaves it.+ await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision');+ await engine.executeRaw('VACUUM (ANALYZE) pages');+ }, 180_000);++ afterAll(async () => {+ __setTitleWholeVectorCandidatesForTests(DEFAULT_CAP);+ await close?.();+ });++ /** The plan of a statement's candidates CTE for a question, bound as the retry binds it (the any-word text as $1). */+ async function candidatesPlan(question: string, completeOnly: boolean, seqscan: 'on' | 'off'): Promise<string> {+ const statement = buildSearchTitlesStatement(question, { limit: 50 }, { ...POSTGRES_DIALECT, completeOnly });+ const candidates = statement.sql.slice(statement.sql.indexOf('candidates AS MATERIALIZED'), statement.sql.indexOf('top_pages AS'));+ expect(candidates).toContain(`LIMIT ${titleWholeVectorCandidates() + 1}`);+ expect(candidates.includes('ORDER BY p.id')).toBe(!completeOnly);+ const anyWord = boundWebsearchQuery(buildOrFallbackWebsearchQuery(statement.params[0] as string)!);+ const rows = await engine.transaction(async (tx) => {+ await tx.executeRaw(`SET LOCAL enable_seqscan = ${seqscan}`);+ return tx.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${statement.sql}`, [anyWord, ...statement.params.slice(1)]);+ });+ const lines = rows.map((r) => r['QUERY PLAN']);+ const start = lines.findIndex((l) => /CTE candidates/.test(l));+ expect(start).toBeGreaterThanOrEqual(0);+ const indent = lines[start].search(/\S/);+ const end = lines.findIndex((l, i) => i > start && l.search(/\S/) <= indent && !/^\s*->/.test(l) && /\S/.test(l));+ return lines.slice(start, end < 0 ? undefined : end).join('\n');+ }++ /** The retry's count reads idx_pages_search and never walks pages_pkey, under the default planner settings and the engine's. */+ async function expectIndexedCount(question: string): Promise<void> {+ for (const seqscan of ['on', 'off'] as const) {+ const plan = await candidatesPlan(question, true, seqscan);+ expect({ seqscan, plan }).toEqual({ seqscan, plan: expect.stringContaining('idx_pages_search') });+ expect({ seqscan, plan }).toEqual({ seqscan, plan: expect.not.stringContaining('pages_pkey') });+ }+ }++ test('a rare word in timelines is found by the retry, from idx_pages_search', async () => {+ const rows = await engine.searchTitles('zorbex nomatchword', { limit: 50 });+ expect(rows.length).toBe(RARE);+ expect(rows.map(r => r.slug).sort()).toEqual(['notes/filler-12000', 'notes/filler-3000', 'notes/filler-6000', 'notes/filler-9000']);+ await expectIndexedCount('zorbex nomatchword');+ });++ test('a word on a few percent of pages that fits the cap is found, from idx_pages_search', async () => {+ expect(FEW_PERCENT).toBeLessThanOrEqual(titleWholeVectorCandidates());+ const rows = await engine.searchTitles('tarsik nomatchword', { limit: 50 });+ expect(rows.length).toBe(50);+ expect(rows.every(r => Number(r.slug.split('-')[1]) % 20 === 0)).toBe(true);+ await expectIndexedCount('tarsik nomatchword');+ });++ test('a word on a few percent of pages that does not fit the cap is counted from idx_pages_search, and the retry falls back to titles', async () => {+ __setTitleWholeVectorCandidatesForTests(100);+ try {+ expect(FEW_PERCENT).toBeGreaterThan(titleWholeVectorCandidates());+ const cut: string[] = [];+ // No title holds the word, so the title-only fallback has nothing to return.+ expect(await engine.searchTitles('tarsik nomatchword', { limit: 50, onKeywordIncomplete: r => { cut.push(r); } })).toEqual([]);+ expect(cut).toEqual([]);+ await expectIndexedCount('tarsik nomatchword');+ // The fixture reaches the case this pins: the same count ordered by page id walks pages_pkey here.+ expect(await candidatesPlan('tarsik nomatchword', false, 'on')).toContain('pages_pkey');+ } finally {+ __setTitleWholeVectorCandidatesForTests(DEFAULT_CAP);+ }+ });+});diff --git a/test/fixtures/retrieval-quality/reworded-relations/corpus.ts b/test/fixtures/retrieval-quality/reworded-relations/corpus.tsnew file mode 100644index 0000000000..3b617352c0--- /dev/null+++ b/test/fixtures/retrieval-quality/reworded-relations/corpus.ts@@ -0,0 +1,133 @@+/**+ * A small relationship world for reworded one-hop questions (GST-2899). Ten+ * companies, each with a founder, an engineer, an investor, an adviser and+ * two people who only crossed its path, a board meeting and a few concept+ * pages that hold the relation words in their titles. Every name is a+ * placeholder. Each person's page links the company in its dated timeline,+ * the way people pages do, so a question that names the company in words the+ * pages never use ("Who is on the payroll at Quorvex?") is answered only by a+ * search step that matches timelines on any of the question's words.+ * Data only: the tests seed it.+ */+export interface RelationPage {+ slug: string;+ type: string;+ title: string;+ compiled_truth: string;+ timeline: string;+}++export interface RelationQuestion {+ id: string;+ relation: 'works_at' | 'invested_in' | 'advises';+ wording: 'template' | 'reworded';+ text: string;+ /** Pages that answer it. */+ relevant: string[];+}++const COMPANIES = ['Quorvex', 'Nastel', 'Kelmit', 'Riulten', 'Velmora', 'Tarsik', 'Ombrel', 'Juniva', 'Halcet', 'Zirella'];+const SECTORS = ['data infrastructure', 'payments', 'robotics', 'climate software', 'developer tools', 'logistics', 'health records', 'security', 'education software', 'energy storage'];+const FIRST_NAMES = [+ 'Alice', 'Bob', 'Carol', 'Dan', 'Erin', 'Frank', 'Grace', 'Heidi', 'Ivan', 'Judy',+ 'Kevin', 'Laura', 'Mallory', 'Niaj', 'Olivia', 'Peggy', 'Quentin', 'Rupert', 'Sybil', 'Trent',+ 'Uma', 'Victor', 'Wendy', 'Xavier', 'Yolanda', 'Zane', 'Amara', 'Boris', 'Celia', 'Dmitri',+ 'Elena', 'Farid', 'Gita', 'Hugo', 'Ines', 'Jorge', 'Keiko', 'Lars', 'Mina', 'Nolan',+ 'Oksana', 'Pablo', 'Qiana', 'Rafael', 'Selma', 'Tariq', 'Ulla', 'Vikram', 'Willa', 'Xiomara',+ 'Yusuf', 'Zelda', 'Anika', 'Bram', 'Chiara', 'Darius', 'Esme', 'Felix', 'Greta', 'Hamid',+];++const slugOf = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-');++function buildWorld(): { pages: RelationPage[]; questions: RelationQuestion[] } {+ const pages: RelationPage[] = [];+ const questions: RelationQuestion[] = [];+ COMPANIES.forEach((co, i) => {+ const sector = SECTORS[i]!;+ const person = (k: number) => {+ const name = `${FIRST_NAMES[i * 6 + k]!} Example`;+ return { name, slug: `people/${slugOf(name)}-${i * 6 + k}` };+ };+ const [founder, engineer, investor, adviser, customer, writer] = [0, 1, 2, 3, 4, 5].map(person) as [ReturnType<typeof person>, ReturnType<typeof person>, ReturnType<typeof person>, ReturnType<typeof person>, ReturnType<typeof person>, ReturnType<typeof person>];+ const year = 2019 + (i % 4);+ const coLink = `[${co}](companies/${slugOf(co)})`;+ const link = (p: { name: string; slug: string }) => `[${p.name}](${p.slug})`;+ pages.push({+ slug: `companies/${slugOf(co)}`, type: 'company', title: co,+ compiled_truth: `${co} is a ${sector} company started in ${year} by ${link(founder)}. The team is about ${30 + i * 4} people, mostly engineers, and its investors include ${link(investor)}. ${link(adviser)} sits on its advisory board.`,+ timeline: `- ${year}-03-0${1 + (i % 9)}: Company formed\n- ${year + 1}-04-12: Seed round closes\n- ${year + 3}-02-14: Series A announced`,+ });+ pages.push({+ slug: `meetings/${slugOf(co)}-board-q${1 + (i % 4)}-2025`, type: 'meeting', title: `${co} Board Meeting Q${1 + (i % 4)} 2025`,+ compiled_truth: `Minutes of the board meeting: runway, the hiring plan, and which people the team wants to add to its staff next quarter.`,+ timeline: `- 2025-0${1 + (i % 9)}-15: Meeting held`,+ });+ pages.push({+ slug: founder.slug, type: 'person', title: founder.name,+ compiled_truth: `${founder.name} is the founder and chief executive of ${coLink}. Earlier ${founder.name.split(' ')[0]} spent four years on a platform group at a large payments firm and writes a widely read engineering blog.`,+ timeline: `- ${year - 1}-09-01: Left the platform group to start ${coLink}\n- ${year}-11-28: Shipped the first ${coLink} release to three design partners\n- ${year + 3}-02-14: ${coLink} announces its Series A`,+ });+ pages.push({+ slug: engineer.slug, type: 'person', title: engineer.name,+ compiled_truth: `${engineer.name} is a senior engineer who works on the ingestion pipeline at ${coLink}. Colleagues describe ${engineer.name.split(' ')[0]} as the person who unblocks everyone else.`,+ timeline: `- ${year + 1}-01-10: Joins ${coLink} as a senior engineer\n- ${year + 2}-02-22: Promoted to tech lead at ${coLink}\n- ${year + 3}-11-01: Leads the internal audit ahead of recertification`,+ });+ pages.push({+ slug: investor.slug, type: 'person', title: investor.name,+ compiled_truth: `${investor.name} is an angel who invested in ${coLink} at the seed stage and backs early ${sector} companies. Founders say the check comes with unusually direct feedback.`,+ timeline: `- ${year + 1}-04-12: Wires a seed check to ${coLink}\n- ${year + 3}-02-14: Takes a pro rata share of the ${coLink} Series A`,+ });+ pages.push({+ slug: adviser.slug, type: 'person', title: adviser.name,+ compiled_truth: `${adviser.name} advises ${coLink} on architecture reviews and is a researcher who has published on ${sector}.`,+ timeline: `- ${year + 1}-06-15: Formalizes an advisory role with ${coLink}\n- ${year + 2}-03-09: Gives a talk on implementation patterns`,+ });+ pages.push({+ slug: customer.slug, type: 'person', title: customer.name,+ compiled_truth: `${customer.name} runs operations at a regional freight firm and is known for careful vendor reviews.`,+ timeline: `- ${year + 2}-05-02: Signed a pilot with ${coLink}\n- ${year + 3}-01-20: Renewed the freight firm's main carrier contract`,+ });+ pages.push({+ slug: writer.slug, type: 'person', title: writer.name,+ compiled_truth: `${writer.name} is a reporter covering ${sector} and early-stage companies.`,+ timeline: `- ${year + 2}-08-19: Published a profile of ${coLink}\n- ${year + 3}-06-03: Moderated a conference panel`,+ });++ const ask = (relation: RelationQuestion['relation'], relevant: string[], template: string, reworded: string[]) => {+ questions.push({ id: `${relation}-${slugOf(co)}-t`, relation, wording: 'template', text: template, relevant });+ reworded.forEach((text, n) => questions.push({ id: `${relation}-${slugOf(co)}-r${n + 1}`, relation, wording: 'reworded', text, relevant }));+ };+ // Half of the rewordings share their words with the company page alone ("team", "investors",+ // "advisory board"), so the all-words match finds that one page and nothing asks for more.+ ask('works_at', [founder.slug, engineer.slug], `Who works at ${co}?`, [+ `Which people are on the ${co} team?`,+ `Who are the engineers at ${co}?`,+ `Who is on the payroll at ${co}?`,+ `Who is employed by ${co}?`,+ ]);+ ask('invested_in', [investor.slug], `Who invested in ${co}?`, [+ `Who are the investors in ${co}?`,+ `Who put money into ${co}?`,+ `Who holds a stake in ${co}?`,+ ]);+ ask('advises', [adviser.slug], `Who advises ${co}?`, [+ `Who is on the advisory board of ${co}?`,+ `Who counsels ${co}?`,+ `Name the advisers of ${co}.`,+ ]);+ });+ const concepts: Array<[string, string, string]> = [+ ['Hiring Playbook', 'How a team hires people and grows its staff without lowering the bar.', '- 2024-01-08: First version written'],+ ['Advisory Boards', 'What an advisory board is for, and how advisers are paid in equity.', '- 2024-02-19: Notes from three founders added'],+ ['Seed Investors', 'How seed investors decide where to put money, and what backers expect in return.', '- 2024-03-04: Updated after the spring rounds'],+ ['Payroll Basics', 'Running payroll for a small team: who is employed, who is a contractor.', '- 2024-04-22: Checklist added'],+ ['Team Offsites', 'Planning an offsite the whole team belongs at.', '- 2024-05-13: Venue list added'],+ ['Cap Tables', 'Who owns a piece of the company after each round.', '- 2024-06-10: Worked example added'],+ ];+ for (const [title, compiled_truth, timeline] of concepts) pages.push({ slug: `concepts/${slugOf(title)}`, type: 'concept', title, compiled_truth, timeline });+ return { pages, questions };+}++const world = buildWorld();+export const RELATION_PAGES: RelationPage[] = world.pages;+export const RELATION_QUESTIONS: RelationQuestion[] = world.questions;diff --git a/test/search/reworded-relation-recall-gst2899.test.ts b/test/search/reworded-relation-recall-gst2899.test.tsnew file mode 100644index 0000000000..06aaba4220--- /dev/null+++ b/test/search/reworded-relation-recall-gst2899.test.ts@@ -0,0 +1,95 @@+/**+ * GST-2899: a question that names a company in words its people's pages never+ * use ("Which people are on the Quorvex team?") is answered by the pages whose+ * dated timeline names the company. On a brain with no embedding provider the+ * only step that reads timelines by any one word of the question is the title+ * step's any-word retry, for local callers. When that retry read titles alone+ * (#7135), these questions returned the company page and little else.+ *+ * Hermetic PGLite with an empty gateway env, so hybridSearch never embeds.+ * Pages are imported the way a keyless brain imports them. Synthetic fixture.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { RELATION_PAGES, RELATION_QUESTIONS, type RelationQuestion } from '../fixtures/retrieval-quality/reworded-relations/corpus.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const p of RELATION_PAGES) {+ const body = ['---', `type: ${p.type}`, `title: ${JSON.stringify(p.title)}`, '---', '', `# ${p.title}`, '', p.compiled_truth, '', '## Timeline', '', p.timeline].join('\n');+ await importFromContent(engine, p.slug, body, { noEmbed: true });+ }+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+ resetGateway();+});++const K = 5;+/** The distinct pages of the first K rows, the way a caller reads a five-row answer. */+const topPages = async (text: string) => {+ const rows = await hybridSearch(engine, text, { limit: K, relationalRetrieval: false, expansion: false, autocut: false, adaptiveReturn: false });+ return [...new Set(rows.map(r => r.slug))];+};+const recallAt5 = async (questions: RelationQuestion[]) => {+ let sum = 0;+ for (const q of questions) {+ const got = await topPages(q.text);+ sum += q.relevant.filter(s => got.includes(s)).length / q.relevant.length;+ }+ return sum / questions.length;+};+const titleSlugs = async (text: string, remote: boolean) =>+ (await engine.searchTitles(text, { limit: 20, ...(remote ? { excludePrivate: true } : {}) })).map(r => r.slug);++describe('reworded one-hop relationship questions on a keyless brain (GST-2899)', () => {+ test('the fixture has the shape: ten companies, template and reworded wordings', () => {+ expect(RELATION_PAGES.length).toBe(86);+ expect(RELATION_QUESTIONS.filter(q => q.wording === 'template').length).toBe(30);+ expect(RELATION_QUESTIONS.filter(q => q.wording === 'reworded').length).toBe(100);+ });++ test("a local caller's title step finds the people whose timeline names the company", async () => {+ const slugs = await titleSlugs('Who works at Quorvex?', false);+ expect(slugs).toContain('companies/quorvex');+ // The founder's page never says "works": only the timeline ("Left the platform group to start Quorvex") names the company.+ expect(slugs).toContain('people/alice-example-0');+ expect(slugs).toContain('people/bob-example-1');+ });++ test('a remote caller keeps the title-only match', async () => {+ const slugs = await titleSlugs('Who works at Quorvex?', true);+ expect(slugs).toContain('companies/quorvex');+ expect(slugs.filter(s => s.startsWith('people/'))).toEqual([]);+ });++ test('"Who works at <company>?" returns the founder as well as the engineer', async () => {+ const got = await topPages('Who works at Quorvex?');+ expect(got).toContain('people/alice-example-0');+ expect(got).toContain('people/bob-example-1');+ });++ test('a rewording whose words sit together only on the company page still returns the people', async () => {+ const got = await topPages('Which people are on the Quorvex team?');+ expect(got).toContain('companies/quorvex');+ expect(got.filter(s => ['people/alice-example-0', 'people/bob-example-1'].includes(s)).length).toBeGreaterThanOrEqual(1);+ });++ test('recall at 5 over the whole fixture', async () => {+ const template = await recallAt5(RELATION_QUESTIONS.filter(q => q.wording === 'template'));+ const reworded = await recallAt5(RELATION_QUESTIONS.filter(q => q.wording === 'reworded'));+ console.log(`[reworded-relations] recall@5 template=${template.toFixed(3)} reworded=${reworded.toFixed(3)}`);+ expect(template).toBeGreaterThanOrEqual(0.95);+ // Measured 0.650 with the retry reading timelines and 0.400 with titles alone; the run is deterministic.+ expect(reworded).toBeGreaterThanOrEqual(0.6);+ }, 120_000);+});diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex a0d0e3e8af..1be8a758db 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -28,6 +28,7 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { __setTitleWholeVectorCandidatesForTests, titleWholeVectorCandidates } from '../../src/core/search/title-statement.ts';import {MAX_WEBSEARCH_QUERY_CHARS,MAX_WEBSEARCH_QUERY_TERMS,@@ -154,7 +155,10 @@ describe('searchTitles — D1 title candidate arm', () => {expect(tlHit.chunk_index).toBe(2); // lowest index when no compiled_truth chunk});- test('a local OR re-run matches the title only: a timeline word is not a relaxed title hit (#7135)', async () => {+ // #7135 made the local OR re-run title-only so a date in a question could not pull every dated timeline into+ // ranking. GST-2899 keeps that bound by size instead: the re-run reads timelines while every matching page fits+ // the title cap, and titles only past it.+ test('a local OR re-run reads timelines only while the matches fit the cap: past it a timeline word is not a relaxed title hit (#7135, GST-2899)', async () => {await engine.putPage('people/dated-entity', {type: 'person',title: 'Cobalt Meridian Atlas',@@ -169,9 +173,23 @@ describe('searchTitles — D1 title candidate arm', () => {);expect(inVector.rows[0].hit).toBe(true);+ for (const n of [1, 2]) {+ await engine.putPage('notes/dated-' + n, { type: 'note', title: 'Dated note ' + n, compiled_truth: 'unrelated body', timeline: '- 2026-10-07: zircon quarry visit' });+ await installFixtureChunks(engine, 'notes/dated-' + n, [{ chunk_index: 0, chunk_text: 'unrelated body', chunk_source: 'compiled_truth' }]);+ }const slugs = async (q: string) => (await engine.searchTitles(q, { limit: 10 })).map(r => r.slug);- expect(await slugs('zircon nebulith')).not.toContain('people/dated-entity');- expect(await slugs('quarry nebulith')).not.toContain('people/dated-entity');+ // Three pages hold the timeline words: under the cap the re-run returns them.+ expect((await slugs('zircon nebulith')).sort()).toEqual(['notes/dated-1', 'notes/dated-2', 'people/dated-entity']);+ const cap = titleWholeVectorCandidates();+ __setTitleWholeVectorCandidatesForTests(2);+ try {+ // Three matches do not fit a cap of two, so the re-run matches titles only, as #7135 left it.+ expect(await slugs('zircon nebulith')).toEqual([]);+ expect(await slugs('quarry nebulith')).toEqual([]);+ expect(await slugs('Cobalt nebulith')).toEqual(['people/dated-entity']);+ } finally {+ __setTitleWholeVectorCandidatesForTests(cap);+ }expect(await slugs('Cobalt Meridian')).toContain('people/dated-entity');expect(await slugs('Cobalt zircon')).toContain('people/dated-entity');});