Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): CJK keyword count binds only its WHERE params; log count SQLSTATE once
time-attack485c2d578251
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex b6d28beef5..1cf3c7017a 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). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; 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). 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/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 match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.diff --git a/src/core/search/keyword-paging.ts b/src/core/search/keyword-paging.tsindex 23bab7ff86..161ce0fbb3 100644--- a/src/core/search/keyword-paging.ts+++ b/src/core/search/keyword-paging.ts@@ -101,13 +101,24 @@ 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';+/** A non-timeout count failure is a bug, not load: its SQLSTATE is logged once per process. */+let countErrorLogged = false;+/** 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 }).then((n): KeywordCount => ({ total: Math.min(n, KEYWORD_COUNT_CAP), capped: n > KEYWORD_COUNT_CAP }))- .catch((e): KeywordCount => ({ unavailable: isTimeout(e) ? 'timeout' : 'error' }));+ .catch((e): KeywordCount => {+ if (isTimeout(e)) return { unavailable: 'timeout' };+ if (!countErrorLogged) {+ countErrorLogged = true;+ const code = (e as { code?: unknown } | null)?.code;+ console.warn(`[search] Keyword match count failed (SQLSTATE ${typeof code === 'string' ? code : 'unknown'}); search reports keyword_count_unavailable instead of a total. This is a bug: report it with the SQLSTATE.`);+ }+ return { unavailable: 'error' };+ });try {return await Promise.race([count, deadline]);} finally {diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.tsindex 8d690900a5..eca801795b 100644--- a/src/core/search/keyword-statement.ts+++ b/src/core/search/keyword-statement.ts@@ -33,7 +33,8 @@ export interface KeywordPageAfter { score: number; page_id: number }export interface KeywordPageWindow { limit: number; offset?: number; after?: KeywordPageAfter }-interface KeywordMatch { where: string; score: string; params: unknown[] }+/** `params[0..whereParamCount)` are the ones `where` reads; the rank params follow, read only by `score`. */+interface KeywordMatch { where: string; score: string; params: unknown[]; whereParamCount: number }const FROM = `content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id`;@@ -41,7 +42,7 @@ const FROM = `content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources sexport function buildKeywordMatch(query: string, opts: SearchOpts | undefined): KeywordMatch | null {const params: unknown[] = [];let predicate: string;- let rank: string;+ let rank: () => string;if (hasCJK(query)) {const terms = splitCJKQueryTerms(query);if (terms.length === 0) return null;@@ -49,18 +50,17 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):params.push(`%${escapeLikePattern(term)}%`);return `cc.chunk_text ${term.toLowerCase() === term.toUpperCase() ? 'LIKE' : 'ILIKE'} $${params.length} ESCAPE '\\'`;});- const freq = terms.map(term => {+ predicate = likes.join(' AND ');+ rank = () => terms.map(term => {params.push(term);return `((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${params.length}, ''))) / NULLIF(LENGTH($${params.length}), 0)::real)`;- });- predicate = likes.join(' AND ');- rank = freq.join(' + ');+ }).join(' + ');} else {if (query.trim() === '') return null;params.push(query);const tsq = `websearch_to_tsquery('${getFtsLanguage()}', $${params.length})`;predicate = `cc.search_vector @@ ${tsq}`;- rank = `ts_rank(cc.search_vector, ${tsq})`;+ rank = () => `ts_rank(cc.search_vector, ${tsq})`;}const add = (value: unknown, clause: (n: string) => string): string => { params.push(value); return ` AND ${clause(`$${params.length}`)}`; };let filters = '';@@ -77,11 +77,9 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):else if (opts?.sourceId) filters += add(opts.sourceId, n => `p.source_id = ${n}`);const hardExclude = buildHardExcludeClause('p.slug', resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes));const factor = buildSourceFactorCase('p.slug', opts?.source_boosts ?? resolveBoostMap(), opts?.detail);- return {- where: `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', opts)} AND cc.modality = 'text'`,- score: `((${rank}) * ${factor})::float8`,- params,- };+ const where = `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', opts)} AND cc.modality = 'text'`;+ const whereParamCount = params.length;+ return { where, score: `((${rank()}) * ${factor})::float8`, params, whereParamCount };}/** Distinct matching pages, capped at KEYWORD_COUNT_CAP + 1. */@@ -90,7 +88,7 @@ export function buildKeywordCountStatement(query: string, opts: SearchOpts | undif (!m) return null;return {sql: `SELECT count(*)::int AS n FROM (SELECT DISTINCT cc.page_id FROM ${FROM} WHERE ${m.where} LIMIT ${KEYWORD_COUNT_CAP + 1}) matched`,- params: m.params,+ params: m.params.slice(0, m.whereParamCount),};}diff --git a/test/e2e/search-keyword-paging-parity.test.ts b/test/e2e/search-keyword-paging-parity.test.tsindex 28d59f13a4..c3c43fa3cb 100644--- a/test/e2e/search-keyword-paging-parity.test.ts+++ b/test/e2e/search-keyword-paging-parity.test.ts@@ -100,6 +100,23 @@ for (const backend of backends) {}});+ test('a CJK count equals its rows, with type and source filters renumbering the placeholders', async () => {+ const e = arm().engine;+ await seedPage(e, 'notes/cjk-glucose-a', '오늘 혈당 기록을 정리했다.');+ await seedPage(e, 'meetings/cjk-glucose-b', '회의에서 혈당 관리 방안을 논의했다.', { type: 'meeting' });+ try {+ expect(await e.countKeywordPages('혈당', { types: ['meeting'], sourceId: 'default' })).toBe(1);+ const hybrid = await callSearch(e, { query: '혈당', source_id: 'default' });+ expect(hybrid.retrieval.keyword_total).toBe(2);+ expect(hybrid.retrieval.degraded ?? []).not.toContainEqual(expect.objectContaining({ stage: 'keyword_count_unavailable' }));+ const typed = await walkKeyword(e, { query: '혈당', types: ['meeting'], limit: 5 });+ expect(typed.pages[0].retrieval.total).toBe(1);+ expect(typed.slugs).toEqual(['meetings/cjk-glucose-b']);+ } finally {+ await e.executeRaw(`DELETE FROM pages WHERE slug LIKE '%/cjk-glucose-%'`);+ }+ });+test('private fence text is not counted for remote callers', async () => {const e = arm().engine;await seedPage(e, 'notes/fenced', 'Public body.\n<!--- gbrain:takes:begin -->\nThe marmoset deal is risky.\n<!--- gbrain:takes:end -->');diff --git a/test/search-keyword-paging.test.ts b/test/search-keyword-paging.test.tsindex 8cc1dba9bc..8ad2eba986 100644--- a/test/search-keyword-paging.test.ts+++ b/test/search-keyword-paging.test.ts@@ -21,7 +21,7 @@* keyword counts or keyword-mode paging (new surface); (4) no new seam: the* unavailable-count tests wrap the real engine.*/-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';@@ -75,6 +75,24 @@ describe('engine: strict keyword pages', () => {expect(await engine.countKeywordPages('zephyrine obsidianite')).toBe(0);expect(await engine.searchKeywordPages('zephyrine obsidianite', undefined, { limit: 10 })).toEqual([]);});++ test('a CJK count binds only the parameters its WHERE reads and equals the rows, under filters', async () => {+ await seedPage(engine, 'notes/cjk-glucose-a', '오늘 혈당 기록을 정리했다.');+ await seedPage(engine, 'meetings/cjk-glucose-b', '회의에서 혈당 관리 방안을 논의했다.', { type: 'meeting' });+ await seedPage(engine, 'notes/cjk-other', '오늘 날씨가 맑았다.');+ try {+ expect(await engine.countKeywordPages('혈당')).toBe(2);+ expect(await engine.countKeywordPages('혈당', { types: ['meeting'], sourceId: 'default' })).toBe(1);+ expect(await countKeywordMatches(engine, '혈당', {})).toEqual({ total: 2, capped: false });+ const rows = await engine.searchKeywordPages('혈당', undefined, { limit: 10 });+ expect(rows.map(r => r.slug).sort()).toEqual(['meetings/cjk-glucose-b', 'notes/cjk-glucose-a']);+ const hybrid = await callSearch(engine, { query: '혈당' });+ expect(hybrid.retrieval.keyword_total).toBe(2);+ expect(hybrid.retrieval.degraded ?? []).not.toContainEqual(expect.objectContaining({ stage: 'keyword_count_unavailable' }));+ } finally {+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE '%/cjk-%'`);+ }+ });});describe('match: "keyword" walk', () => {@@ -304,6 +322,26 @@ describe('count unavailable: a degraded stage, never a number', () => {expect(nextFromLine(countLine(keyword))).toBeDefined();});+ test('a failed (non-timeout) count is unavailable with its SQLSTATE logged once per process', async () => {+ const failing = new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'countKeywordPages') return async () => { throw Object.assign(new Error('bind message supplies 2 parameters'), { code: '08P01' }); };+ const v = Reflect.get(target, prop, receiver);+ return typeof v === 'function' ? v.bind(target) : v;+ },+ }) as BrainEngine;+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ expect(await countKeywordMatches(failing, TERM, {}, 1000)).toEqual({ unavailable: 'error' });+ expect(await countKeywordMatches(failing, TERM, {}, 1000)).toEqual({ unavailable: 'error' });+ const logged = warn.mock.calls.map(c => String(c[0])).filter(l => l.includes('Keyword match count failed'));+ expect(logged).toEqual([expect.stringContaining('SQLSTATE 08P01')]);+ expect(logged[0]).not.toContain(TERM);+ } finally {+ warn.mockRestore();+ }+ });+test('the line renderer never invents a number', () => {expect(searchCountLine([], { keyword_total: null, degraded: [{ stage: 'keyword_count_unavailable' }] })).toContain('Keyword match count unavailable (failed; not a count of zero)');diff --git a/test/sql-bind-placeholders.test.ts b/test/sql-bind-placeholders.test.tsindex a5fab232d9..eec1469c5a 100644--- a/test/sql-bind-placeholders.test.ts+++ b/test/sql-bind-placeholders.test.ts@@ -1,5 +1,5 @@/**- * One guard for the bind-placeholder bug class (#6659):+ * One guard for the bind-placeholder bug class (#6659, the CJK keyword count):* Postgres and PGLite refuse a statement that binds a parameter it never* references (42P18 "could not determine data type", or 08P01 "bind message* supplies N parameters"). Each exported `{ sql, params }` builder runs over@@ -7,7 +7,9 @@* must be exactly `1..params.length`.*/import { describe, expect, test } from 'bun:test';+import type { SearchOpts } from '../src/core/types.ts';import { fileClaimCandidatesQuery } from '../src/core/persistence/file-claims.ts';+import { buildKeywordCountStatement, buildKeywordPagesStatement } from '../src/core/search/keyword-statement.ts';function referenced(sql: string): number[] {return [...new Set([...sql.matchAll(/\$(\d+)(?!\d)/g)].map(m => Number(m[1])))].sort((a, b) => a - b);@@ -26,3 +28,25 @@ describe('file-claim census', () => {});}});++describe('keyword statements', () => {+ const filterSets: Array<[string, SearchOpts | undefined]> = [+ ['no options', undefined],+ ['types + source', { types: ['meeting', 'note'], sourceId: 'default' }],+ ['every filter', {+ detail: 'low', language: 'typescript', symbolKind: 'function', type: 'note', types: ['note'], exclude_slugs: ['a/b'],+ afterDate: '2026-01-01', beforeDate: '2026-12-31', sourceIds: ['default', 'other'],+ }],+ ];+ for (const query of ['quasar budget', '혈당', '혈당 관리']) {+ for (const [label, opts] of filterSets) {+ test(`count: ${JSON.stringify(query)} with ${label}`, () => {+ expectEveryBindReferenced(buildKeywordCountStatement(query, opts));+ });+ test(`pages: ${JSON.stringify(query)} with ${label}, first page and after a cursor`, () => {+ expectEveryBindReferenced(buildKeywordPagesStatement(query, opts, { limit: 10 }));+ expectEveryBindReferenced(buildKeywordPagesStatement(query, opts, { limit: 10, offset: 5, after: { score: 0.5, page_id: 7 } }));+ });+ }+ }+});