Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): the keyword count waits for the search, and its predicate keeps column stats (#6632)
time-attackf90ab8da605c
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 2080ec38cd..d14b5716b7 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -54,7 +54,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; shared guarded transport pins validated DNS answers and streams decoded bodies with a 2 MiB remote cap (10 MiB local cap). `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).-- `src/core/search/keyword-paging.ts` — honest keyword counts and keyword-mode paging for the `search` op. `parseSearchPaging` validates `match` (`hybrid` default, `keyword`), `cursor`, the 10,000 offset cap (`search_offset_over_cap`; hybrid `offset` keeps its ranked-list meaning) and refuses an agent-facing `mode` (`search_mode_local_only`) and a cursor outside keyword mode (`search_cursor_requires_keyword`), each with a fix naming `match: "keyword"`. `startKeywordCount` / `countKeywordMatches` run `engine.countKeywordPages` beside the search under a 2-second deadline; the result is `keyword_total` / `keyword_truncated` (`keyword_total_capped` past 10,000) or the `keyword_count_unavailable` degraded stage, never a guessed number. `readKeywordPage` reads `limit + 1` rows from `engine.searchKeywordPages` (so `truncated` and `next` never depend on the count) and builds `next`, a ready-to-send argument object whose `cursor` is a base64url keyset `(score, page_id, rows shown)` bound to the query, `types` and `source_id`. `keepEnumeratedRows` keeps every enumerated page after evidence delivery (`evidence_omitted: true`, empty text, when its text did not fit). `searchCountLine` renders the one model-visible line `src/mcp/dispatch.ts` appends after the rows on every search call. Tests: `test/search-keyword-paging.test.ts`, `test/search-keyword-cap.slow.test.ts`, `test/e2e/search-keyword-paging-parity.test.ts`.+- `src/core/search/keyword-paging.ts` — keyword counts and keyword-mode paging for `search`. `parseSearchPaging` validates `match` (`hybrid` default, `keyword`), `cursor`, the 10,000 offset cap (`search_offset_over_cap`; hybrid `offset` keeps its ranked-list meaning) and refuses an agent-facing `mode` (`search_mode_local_only`) and a cursor outside keyword mode (`search_cursor_requires_keyword`), each with a fix naming `match: "keyword"`. `startKeywordCount` / `countKeywordMatches` run `engine.countKeywordPages` beside the search until max(2 s, search end + `KEYWORD_COUNT_GRACE_MS`); the result is `keyword_total` / `keyword_truncated` (`keyword_total_capped` past 10,000) or the `keyword_count_unavailable` degraded stage, never a guess. `readKeywordPage` reads `limit + 1` rows from `engine.searchKeywordPages` (so `truncated` and `next` never depend on the count) and builds `next`, a ready-to-send argument object whose `cursor` is a base64url keyset `(score, page_id, rows shown)` bound to the query, `types` and `source_id`. `keepEnumeratedRows` keeps every enumerated page after evidence delivery (`evidence_omitted: true`, empty text, when its text did not fit). `searchCountLine` renders the one model-visible line `src/mcp/dispatch.ts` appends after the rows on every search call. Tests: `test/search-keyword-paging.test.ts`, `test/search-keyword-cap.slow.test.ts`, `test/e2e/search-keyword-paging-parity.test.ts`.- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex a95a2d8154..453798c191 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -758,8 +758,9 @@ const search: Operation = {if (hit && !text.includes(names[0]!.toLowerCase())) row.matched_alias = hit;}}- const keywordCount = page ? null : timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, undefined, keywordOpts));- const results = (page ? page.rows : dedupResults(await timings.stage('lexical', () => ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts })))).map(r => ({ ...r }));+ const lexicalDone = Promise.withResolvers<void>();+ const keywordCount = page ? null : timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, undefined, keywordOpts, lexicalDone.promise));+ const results = (page ? page.rows : dedupResults(await timings.stage('lexical', () => ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts })).finally(lexicalDone.resolve))).map(r => ({ ...r }));await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt, timings);// #3800: cap AFTER capture/meta so eval + cache see the real payload.return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap, timings,@@ -770,7 +771,8 @@ const search: Operation = {// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but// expansion OFF (no per-call LLM cost). `query` op is the full-control variant.let capturedMeta: HybridSearchMeta | null = null;- const keywordCount = timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, types, readOpts));+ const searchDone = Promise.withResolvers<void>();+ const keywordCount = timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, types, readOpts, searchDone.promise));const explainPrep = await setup(() => prepareExplainTarget(ctx, p, scope, excludePrivate, 'search'));const searchOpts = {limit,@@ -791,7 +793,7 @@ const search: Operation = {};const primary = await hybridSearchCached(ctx.engine, queryText, {...searchOpts, onMeta: (m) => { capturedMeta = m; }, explain: p.explain === true, explainTarget: explainPrep?.trace,- });+ }).finally(searchDone.resolve);const declarations = new DeclarationMemo();const fanned = offset === 0? await timings.stage('alias_fanout', () => withAliasFanOut(ctx.engine, primary, queryText, { ...scope, excludePrivate },diff --git a/src/core/search/keyword-paging.ts b/src/core/search/keyword-paging.tsindex 23bab7ff86..6290150d0f 100644--- a/src/core/search/keyword-paging.ts+++ b/src/core/search/keyword-paging.ts@@ -32,8 +32,16 @@ import { KEYWORD_COUNT_CAP, type KeywordPageAfter } from './keyword-statement.tsexport type SearchMatch = 'hybrid' | 'keyword';export const SEARCH_OFFSET_CAP = 10_000;-/** The count's deadline: it runs beside the search and never holds the response longer. */+/**+ * The count's deadline floor. The count runs beside the search and is given+ * up at whichever is later: this floor, or the search finishing plus+ * KEYWORD_COUNT_GRACE_MS (#6632), so a slow search no longer drops a count+ * that would have landed before the response. The statement itself runs+ * under the operator bound `search.keyword_statement_timeout_ms`.+ */export const KEYWORD_COUNT_TIMEOUT_MS = 2_000;+/** How long the response waits for the count after the search is done (when that is past the floor). */+export const KEYWORD_COUNT_GRACE_MS = 250;/** Params a keyword `next` carries over unchanged. */const CARRIED_PARAMS = ['limit', 'types', 'source_id', 'snippet_chars', 'return_unit', 'return_window', 'token_budget', 'fields'] as const;@@ -101,17 +109,23 @@ export type KeywordCount = { total: number; capped: boolean } | { unavailable: 'const isTimeout = (e: unknown) => /statement timeout|canceling statement/i.test(e instanceof Error ? e.message : String(e))|| (e as { code?: unknown } | null)?.code === '57014';-/** The strict keyword count under a deadline; a late or failed count is unavailable, never a number. */-export async function countKeywordMatches(engine: BrainEngine, query: string, opts: SearchOpts, timeoutMs = KEYWORD_COUNT_TIMEOUT_MS): Promise<KeywordCount> {- let timer: ReturnType<typeof setTimeout> | undefined;- const deadline = new Promise<KeywordCount>(resolve => { timer = setTimeout(() => resolve({ unavailable: 'timeout' }), timeoutMs); });- const count = engine.countKeywordPages(query, { ...opts, timeoutMs })+/**+ * The strict keyword count under a deadline; a late or failed count is+ * unavailable, never a number. The deadline is `floorMs`, or `searchDone`+ * settling plus KEYWORD_COUNT_GRACE_MS when that is later.+ */+export async function countKeywordMatches(engine: BrainEngine, query: string, opts: SearchOpts, floorMs = KEYWORD_COUNT_TIMEOUT_MS, searchDone?: Promise<unknown>): Promise<KeywordCount> {+ const timers: Array<ReturnType<typeof setTimeout>> = [];+ const sleep = (ms: number) => new Promise<void>(resolve => { timers.push(setTimeout(resolve, ms)); });+ const searchGrace = searchDone ? searchDone.then(() => {}, () => {}).then(() => sleep(KEYWORD_COUNT_GRACE_MS)) : undefined;+ const deadline = Promise.all([sleep(floorMs), searchGrace]).then((): KeywordCount => ({ unavailable: 'timeout' }));+ const count = engine.countKeywordPages(query, opts).then((n): KeywordCount => ({ total: Math.min(n, KEYWORD_COUNT_CAP), capped: n > KEYWORD_COUNT_CAP })).catch((e): KeywordCount => ({ unavailable: isTimeout(e) ? 'timeout' : 'error' }));try {return await Promise.race([count, deadline]);} finally {- clearTimeout(timer);+ for (const t of timers) clearTimeout(t);}}@@ -120,11 +134,11 @@ export async function countKeywordMatches(engine: BrainEngine, query: string, op* Types expand the way hybridSearch expands them; a filter that expands to* nothing matches nothing.*/-export function startKeywordCount(engine: BrainEngine, query: string, types: string[] | undefined, opts: SearchOpts): Promise<KeywordCount> {+export function startKeywordCount(engine: BrainEngine, query: string, types: string[] | undefined, opts: SearchOpts, searchDone?: Promise<unknown>): Promise<KeywordCount> {return (async (): Promise<KeywordCount> => {const expanded = types ? (await expandEngineTypeFilters(engine, { types, ...opts })).types : undefined;if (expanded?.length === 0) return { total: 0, capped: false };- return countKeywordMatches(engine, query, { ...opts, ...(expanded ? { types: expanded } : {}) });+ return countKeywordMatches(engine, query, { ...opts, ...(expanded ? { types: expanded } : {}) }, KEYWORD_COUNT_TIMEOUT_MS, searchDone);})().catch((): KeywordCount => ({ unavailable: 'error' }));}diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.tsindex 22bba5bc49..ce10d3cdb5 100644--- a/src/core/search/safe-chunks.ts+++ b/src/core/search/safe-chunks.ts@@ -43,9 +43,14 @@ export function belowSafeChunkFence(chunkerVersion: number | null | undefined):return (chunkerVersion ?? 0) < SAFE_FENCE_CHUNKER_VERSION;}-/** Older fragments lack trustworthy provenance, even if markers were removed later. */+/**+ * Older fragments lack trustworthy provenance, even if markers were removed+ * later. `pages.chunker_version` is `smallint NOT NULL` at head on both+ * engines (v054), so the bare column compares and keeps its statistics (#6632:+ * a COALESCE gets the default 1/3 selectivity and misleads the count plan).+ */export function safeChunksFilter(alias: string): string {- return `COALESCE(${alias}.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}`;+ return `${alias}.chunker_version >= ${SAFE_FENCE_CHUNKER_VERSION}`;}/**diff --git a/test/search-keyword-paging.test.ts b/test/search-keyword-paging.test.tsindex 8cc1dba9bc..17c98c1ebc 100644--- a/test/search-keyword-paging.test.ts+++ b/test/search-keyword-paging.test.ts@@ -27,6 +27,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';import { errorCodeRow } from '../src/core/error-docs.ts';import { countKeywordMatches, searchCountLine } from '../src/core/search/keyword-paging.ts';+import { safeChunksFilter } from '../src/core/search/safe-chunks.ts';import { withEnv } from './helpers/with-env.ts';import {DOMINANT_CHUNKS, DOMINANT_SLUG, MANY_PAGES, MIXED_TYPES, TERM, callSearch, seedKeywordCorpus, seedPage, walkKeyword,@@ -294,6 +295,44 @@ describe('count unavailable: a degraded stage, never a number', () => {expect(await countKeywordMatches(stalled(engine, 'timeout'), TERM, {}, 1000)).toEqual({ unavailable: 'timeout' });});+ const delayed = (base: BrainEngine, ms: number, seen: Array<Record<string, unknown> | undefined>): BrainEngine => new Proxy(base, {+ get(target, prop, receiver) {+ if (prop === 'countKeywordPages') {+ return async (q: string, o?: Record<string, unknown>) => { seen.push(o); await new Promise(r => setTimeout(r, ms)); return target.countKeywordPages(q, o as never); };+ }+ const v = Reflect.get(target, prop, receiver);+ return typeof v === 'function' ? v.bind(target) : v;+ },+ });+ const after = (ms: number) => new Promise<void>(r => setTimeout(r, ms));++ test('#6632: a count past the floor still lands while the search is running', async () => {+ const seen: Array<Record<string, unknown> | undefined> = [];+ const count = await countKeywordMatches(delayed(engine, 150, seen), TERM, {}, 50, after(400));+ expect('total' in count ? count.total : -1).toBeGreaterThan(0);+ });++ test('#6632: a count still running after the search and its grace is given up, not waited on', async () => {+ const started = Date.now();+ expect(await countKeywordMatches(stalled(engine, 'hang'), TERM, {}, 50, after(150))).toEqual({ unavailable: 'timeout' });+ const elapsed = Date.now() - started;+ expect(elapsed).toBeGreaterThanOrEqual(150);+ expect(elapsed).toBeLessThan(1500);+ });++ test('#6632: the count statement runs under the operator bound, not a narrower fixed deadline', async () => {+ const seen: Array<Record<string, unknown> | undefined> = [];+ await countKeywordMatches(delayed(engine, 0, seen), TERM, {}, 50);+ expect(seen).toHaveLength(1);+ expect(seen[0]?.timeoutMs).toBeUndefined();+ });++ test('#6632: the safe-chunk predicate compares the bare NOT NULL column, so the planner keeps its statistics', async () => {+ expect(await engine.executeRaw(`SELECT data_type, is_nullable FROM information_schema.columns WHERE table_name = 'pages' AND column_name = 'chunker_version'`))+ .toEqual([{ data_type: 'smallint', is_nullable: 'NO' }]);+ expect(safeChunksFilter('p')).toBe('p.chunker_version >= 4');+ });+test('over MCP: the line says unavailable, the stage is recorded, keyword paging still works', async () => {const e = stalled(engine, 'timeout');const hybrid = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(e, 'search', { query: TERM }, REMOTE));