Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): fold the FTS configuration name into knobs_hash — stop stale rows surviving a reindex-search-vector language switch (#3677)

paul-0320b4a9c7683d9c
diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.md
index 1e5a2fe034..10488f424c 100644
--- a/docs/guides/multi-language-fts.md
+++ b/docs/guides/multi-language-fts.md
@@ -59,6 +59,12 @@ streaming progress to stderr. It is idempotent: re-running with the same
language produces identical vectors. `--json` prints a machine-readable
result envelope but still requires `--yes` (or an interactive confirm).
+No cache purge is needed. The resolved language is part of the query-cache
+key, so rows written under the previous language are unreachable after the
+switch — searches read the retokenized index immediately instead of being
+served pre-switch results for up to `search.cache.ttl_seconds`. Switching
+back reaches the original rows rather than rebuilding them.
+
## Recipe: accent-insensitive Portuguese (`pt_br`)
Brazilian Portuguese content often mixes accented and unaccented spellings
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index d86d038c4b..638945f1ba 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -25,6 +25,7 @@
import { createHash } from 'crypto';
import { CR_MODES, type CRMode } from '../types.ts';
+import { getFtsLanguage } from '../fts-language.ts';
import { getRecipe } from '../ai/recipes/index.ts';
/**
@@ -766,7 +767,19 @@ export function attributeKnob<K extends keyof ModeBundle>(
// written between the #3391 stale-fix (which changes which chunks count as
// current) and the operator's migration run. Same one-time global cold-miss
// pattern as the bumps above.
-export const KNOBS_HASH_VERSION = 14;
+//
+// bump 14→15: the FTS configuration name (GBRAIN_FTS_LANGUAGE, resolved by
+// getFtsLanguage()) folds into the key via the `fts=` part. It reaches BOTH
+// engines' keyword SQL (websearch_to_tsquery/to_tsvector in postgres-engine
+// and pglite-engine) and the two search_vector trigger functions, so it
+// changes which rows the keyword arm returns — but it only applied at
+// DB-query build time (cache miss). Switching language and running
+// `gbrain reindex-search-vector` therefore left every pre-switch query_cache
+// row reachable: the freshly retokenized index was silently bypassed for up
+// to cache.ttl_seconds, with no warning and no way for an operator to tell.
+// Same one-time global cold-miss pattern as the bumps above; refills within
+// cache.ttl_seconds (3600s default).
+export const KNOBS_HASH_VERSION = 15;
/**
* v0.36 (D8 / CDX-2) — second-arg context for the cache key. The
@@ -898,6 +911,16 @@ export function knobsHash(
// across processes. Sorted copy so ['a/','b/'] and ['b/','a/'] hash
// identically; undefined falls back to 'none' for legacy callers.
`hx=${ctx?.hardExcludes ? [...ctx.hardExcludes].sort().join(',') : 'none'}`,
+ // v=15 addition (append-only): the resolved FTS configuration name. Read
+ // from getFtsLanguage() rather than threaded through KnobsHashContext on
+ // purpose — the language is a process-global env read with no per-call
+ // dimension, and the `prov=` bump note above records what threading costs:
+ // a ctx field only isolates callers that pass it, so legacy callers keep
+ // hashing the fallback literal on both sides of a switch. Reading it here
+ // covers every knobsHash() caller, present and future. getFtsLanguage()
+ // memoizes and validates against /^[a-z][a-z0-9_]*$/, so this stays a
+ // cheap, bounded string.
+ `fts=${getFtsLanguage()}`,
];
const h = createHash('sha256');
h.update(parts.join('|'));
diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.ts
index c536a742be..62b850136b 100644
--- a/test/cross-modal-phase1.test.ts
+++ b/test/cross-modal-phase1.test.ts
@@ -136,7 +136,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {
return resolveSearchMode({ mode: 'balanced' });
}
- test('KNOBS_HASH_VERSION is 14 (cross-modal still appended; 13→14 compiled_truth boost scope #3430)', () => {
+ test('KNOBS_HASH_VERSION is 15 (cross-modal still appended; 14→15 FTS language fold)', () => {
// v0.35 ladder: 1→2 reranker, 2→3 floor_ratio. v0.36 piggybacks on v=3
// with 7 cross-modal knobs + column/provider context. v0.40.4 (salem) +
// v0.39 T21 (master) bump to v=4 for graph_signals + schema-pack fields.
@@ -147,7 +147,9 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {
// finally reaches asymmetric providers — pre-fix rows were keyed on
// document-side query vectors. #2825: 11→12 hard-exclude fold (hx=).
// #3430: 13→14 compiled_truth boost no longer applies at detail=medium.
- expect(KNOBS_HASH_VERSION).toBe(14);
+ // 14→15: the resolved FTS configuration name (fts=) — a language switch
+ // plus `reindex-search-vector` must not keep serving pre-switch rows.
+ expect(KNOBS_HASH_VERSION).toBe(15);
});
test('flipping unified_multimodal changes the hash', () => {
diff --git a/test/fts-language-cache-isolation.serial.test.ts b/test/fts-language-cache-isolation.serial.test.ts
new file mode 100644
index 0000000000..f6a4ae464e
--- /dev/null
+++ b/test/fts-language-cache-isolation.serial.test.ts
@@ -0,0 +1,173 @@
+/**
+ * GBRAIN_FTS_LANGUAGE must isolate query_cache rows.
+ *
+ * getFtsLanguage() reaches both sides of the lexical arms — the
+ * `update_page_search_vector` / `update_chunk_search_vector` triggers that
+ * build the tsvector, and the `websearch_to_tsquery(<lang>, …)` inside
+ * searchKeyword / searchTitles / searchKeywordChunks on BOTH engines — but it
+ * only applied at DB-query build time, i.e. on a cache MISS. So the
+ * documented language-switch procedure
+ * (`GBRAIN_FTS_LANGUAGE=… gbrain reindex-search-vector --yes`) left every
+ * pre-switch cache row reachable: the freshly retokenized index was silently
+ * bypassed for up to cache.ttl_seconds.
+ *
+ * This drives the real production path (`hybridSearchCached` over a PGLite
+ * brain) rather than the hash in isolation: a run under `english` populates a
+ * row from an english-stemmed index, then the same query under a different
+ * configuration must NOT be served that row. The fixture makes the difference
+ * observable — "builders" stems to "builder" under english and matches the
+ * seeded pages; under `simple` it stays "builders" and matches nothing, so a
+ * stale hit is a visibly wrong answer, not just a wrong key.
+ *
+ * Serial: mock.module + process.env mutation (isolation guards R1 + R2).
+ */
+
+import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as realEmbedding from '../src/core/embedding.ts';
+
+/** Deterministic 1536d unit vector — identical for every call, so a cache
+ * consult matches a prior write at cosine 1.0 whenever the knobs hash
+ * agrees. That isolates the assertion to the key, not the similarity gate. */
+function fixedEmbedding(): Float32Array {
+ const arr = new Float32Array(1536);
+ for (let i = 0; i < 1536; i++) arr[i] = Math.sin(1 + i * 0.001);
+ let norm = 0;
+ for (let i = 0; i < 1536; i++) norm += arr[i] * arr[i];
+ norm = Math.sqrt(norm);
+ if (norm > 0) for (let i = 0; i < 1536; i++) arr[i] /= norm;
+ return arr;
+}
+
+// Mock BEFORE importing hybrid.ts (spread keeps every other export live).
+mock.module('../src/core/embedding.ts', () => ({
+ ...realEmbedding,
+ embed: async () => fixedEmbedding(),
+ embedQuery: async () => fixedEmbedding(),
+}));
+
+// Import AFTER mocking.
+const { hybridSearchCached, awaitPendingSearchCacheWrites } =
+ await import('../src/core/search/hybrid.ts');
+const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');
+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+const { resetFtsLanguageCache } = await import('../src/core/fts-language.ts');
+
+type Meta = import('../src/core/types.ts').HybridSearchMeta;
+
+let engine: InstanceType<typeof PGLiteEngine>;
+let tmpHome: string;
+const savedGbrainHome = process.env.GBRAIN_HOME;
+const savedFtsLanguage = process.env.GBRAIN_FTS_LANGUAGE;
+
+/** Pin the process FTS language (undefined = unset → the 'english' default).
+ * getFtsLanguage() memoizes, so the cache is reset on every change. */
+function setFtsLanguage(language: string | undefined): void {
+ if (language === undefined) delete process.env.GBRAIN_FTS_LANGUAGE;
+ else process.env.GBRAIN_FTS_LANGUAGE = language;
+ resetFtsLanguageCache();
+}
+
+/** One cached search; returns the results plus the published cache status. */
+async function search(query: string): Promise<{
+ results: Awaited<ReturnType<typeof hybridSearchCached>>;
+ status: NonNullable<Meta['cache']>['status'] | undefined;
+}> {
+ let meta: Meta | undefined;
+ const results = await hybridSearchCached(engine, query, {
+ limit: 10,
+ onMeta: (m) => { meta = m; },
+ });
+ await awaitPendingSearchCacheWrites();
+ return { results, status: meta?.cache?.status };
+}
+
+beforeAll(async () => {
+ // Hermetic config home so a developer's real ~/.gbrain/config.json can't
+ // leak an embedding_model that flips the consult to 'disabled' via
+ // isCacheSafe (same rationale as hybrid-cached-hit-budget-meta).
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-fts-cache-key-'));
+ process.env.GBRAIN_HOME = tmpHome;
+
+ // The brain is built and indexed under the default language, exactly like
+ // an install that has not run a language switch yet.
+ setFtsLanguage(undefined);
+
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-fake' },
+ });
+
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ // Keyword-findable pages. putPage never chunks and searchKeyword joins
+ // content_chunks, so the chunks are explicit. The chunk trigger stamps
+ // search_vector with the language in force at initSchema time (english).
+ const fixtures: Array<[string, string, string]> = [
+ ['alice-foo', 'Alice Foo', 'person'],
+ ['bob-bar', 'Bob Bar', 'company'],
+ ['carol-baz', 'Carol Baz', 'note'],
+ ];
+ for (const [slug, title, type] of fixtures) {
+ const truth = `${title} is a builder. ${'x'.repeat(400)}`;
+ await engine.putPage(slug, { type, title, compiled_truth: truth });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },
+ ]);
+ }
+});
+
+afterAll(async () => {
+ if (savedGbrainHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = savedGbrainHome;
+ if (savedFtsLanguage === undefined) delete process.env.GBRAIN_FTS_LANGUAGE;
+ else process.env.GBRAIN_FTS_LANGUAGE = savedFtsLanguage;
+ resetFtsLanguageCache();
+ try { await engine.disconnect(); } catch { /* ignore */ }
+ resetGateway();
+ try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }
+});
+
+describe('query_cache isolation across an FTS language switch', () => {
+ test('an english-tokenized row is not served to a differently configured process', async () => {
+ // 1. Default (english) install: 'builders' stems to 'builder' and finds
+ // the seeded pages. The row lands in query_cache.
+ setFtsLanguage(undefined);
+ const englishRun = await search('builders');
+ expect(englishRun.status).toBe('miss');
+ expect(englishRun.results.length).toBeGreaterThan(0);
+
+ // Same process, same language → the row is reachable (the cache still
+ // works; this pins that the fix isolates rather than disables).
+ const englishRepeat = await search('builders');
+ expect(englishRepeat.status).toBe('hit');
+ expect(englishRepeat.results.length).toBe(englishRun.results.length);
+
+ // 2. Operator switches the language. Only the query side moves here (the
+ // seeded search_vector stays english-stemmed), which is what makes the
+ // divergence observable in-process: 'builders' no longer reaches
+ // 'builder', so this process cannot reproduce the english answer from
+ // the index it is now querying. A real switch also retokenizes the
+ // write side via `reindex-search-vector`; either way the cached rows
+ // describe a corpus view the new configuration does not have.
+ setFtsLanguage('simple');
+ const switched = await search('builders');
+
+ // Pre-fix this was a HIT serving englishRun.results (3 pages).
+ expect(switched.status).toBe('miss');
+ expect(switched.results.length).toBeLessThan(englishRun.results.length);
+
+ // 3. Switching back reaches the original row, not a rebuilt one — the
+ // two languages occupy distinct rows rather than overwriting.
+ setFtsLanguage(undefined);
+ const back = await search('builders');
+ expect(back.status).toBe('hit');
+ expect(back.results.map((r) => r.slug)).toEqual(englishRun.results.map((r) => r.slug));
+ });
+});
diff --git a/test/query-cache-knobs-hash.serial.test.ts b/test/query-cache-knobs-hash.serial.test.ts
index d11d42ef3a..e4896d3f5b 100644
--- a/test/query-cache-knobs-hash.serial.test.ts
+++ b/test/query-cache-knobs-hash.serial.test.ts
@@ -20,10 +20,33 @@ import { SemanticQueryCache, cacheRowId } from '../src/core/search/query-cache.t
import type { SearchResult } from '../src/core/types.ts';
import { knobsHash, resolveSearchMode } from '../src/core/search/mode.ts';
import { resolveHardExcludes } from '../src/core/search/source-boost.ts';
+import { resetFtsLanguageCache } from '../src/core/fts-language.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
let engine: PGLiteEngine;
+/**
+ * Run `fn` with GBRAIN_FTS_LANGUAGE pinned, then restore this process's
+ * original value. getFtsLanguage() memoizes, so the cache is reset on both
+ * edges — otherwise the pin would leak into the mode hashes computed below
+ * (and, for an operator who runs the suite with the env set, flip them).
+ * Serial file: direct process.env mutation is the sanctioned pattern here
+ * (isolation guard R1).
+ */
+function withFtsLanguage<T>(language: string | undefined, fn: () => T): T {
+ const saved = process.env.GBRAIN_FTS_LANGUAGE;
+ if (language === undefined) delete process.env.GBRAIN_FTS_LANGUAGE;
+ else process.env.GBRAIN_FTS_LANGUAGE = language;
+ resetFtsLanguageCache();
+ try {
+ return fn();
+ } finally {
+ if (saved === undefined) delete process.env.GBRAIN_FTS_LANGUAGE;
+ else process.env.GBRAIN_FTS_LANGUAGE = saved;
+ resetFtsLanguageCache();
+ }
+}
+
const conservativeHash = knobsHash(resolveSearchMode({ mode: 'conservative' }));
const balancedHash = knobsHash(resolveSearchMode({ mode: 'balanced' }));
const tokenmaxHash = knobsHash(resolveSearchMode({ mode: 'tokenmax' }));
@@ -277,3 +300,55 @@ describe('hard-exclude cache isolation (#2825)', () => {
expect((await cache.lookup(emb, { knobsHash: envExcludeHash })).hit).toBe(true);
});
});
+
+describe('FTS language cache isolation', () => {
+ // GBRAIN_FTS_LANGUAGE retokenizes BOTH sides of the keyword arm (the
+ // trigger-built search_vector and the query-side websearch_to_tsquery), so
+ // rows written under one language describe a different index than the one a
+ // post-`reindex-search-vector` process queries. knobsHash folds the resolved
+ // language in (`fts=`) so those rows can never be served across the switch.
+ const englishHash = withFtsLanguage(undefined, () =>
+ knobsHash(resolveSearchMode({ mode: 'balanced' })));
+ const portugueseHash = withFtsLanguage('portuguese', () =>
+ knobsHash(resolveSearchMode({ mode: 'balanced' })));
+
+ test('the resolved language changes the hash', () => {
+ expect(englishHash).not.toBe(portugueseHash);
+ // An invalid value falls back to english inside getFtsLanguage(), so it
+ // must land on the english row rather than minting an unreachable one.
+ expect(withFtsLanguage('NOT A CONFIG', () =>
+ knobsHash(resolveSearchMode({ mode: 'balanced' })))).toBe(englishHash);
+ });
+
+ test('a row written under english is NOT served after switching to portuguese', async () => {
+ const cache = new SemanticQueryCache(engine);
+ const emb = makeEmbedding(8);
+
+ // English-tokenized run: 'running' stems to 'run', so these rows reflect
+ // an index the portuguese-configured process no longer has.
+ await cache.store('running', emb, makeResults('english-stemmed', 4), {
+ vector_enabled: true, detail_resolved: null, expansion_applied: false,
+ }, { knobsHash: englishHash });
+
+ // Post-reindex process → MISS (falls through to a fresh keyword query
+ // against the retokenized index).
+ expect((await cache.lookup(emb, { knobsHash: portugueseHash })).hit).toBe(false);
+
+ // Same-language process still hits its own row.
+ const same = await cache.lookup(emb, { knobsHash: englishHash });
+ expect(same.hit).toBe(true);
+ expect(same.results?.length).toBe(4);
+ });
+
+ test('switching back does not resurrect the other language rows', async () => {
+ const cache = new SemanticQueryCache(engine);
+ const emb = makeEmbedding(9);
+
+ await cache.store('running', emb, makeResults('portuguese-stemmed', 2), {
+ vector_enabled: true, detail_resolved: null, expansion_applied: false,
+ }, { knobsHash: portugueseHash });
+
+ expect((await cache.lookup(emb, { knobsHash: englishHash })).hit).toBe(false);
+ expect((await cache.lookup(emb, { knobsHash: portugueseHash })).hit).toBe(true);
+ });
+});
diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.ts
index 2adb8877c9..10e532201a 100644
--- a/test/search-alias-resolved-boost.test.ts
+++ b/test/search-alias-resolved-boost.test.ts
@@ -89,7 +89,7 @@ describe('alias_resolved boost stage', () => {
});
describe('KNOBS_HASH_VERSION', () => {
- it('is 14 (13→14 compiled_truth boost no longer applies at detail=medium, so pre-fix rankings must be unreachable, #3430)', () => {
- expect(KNOBS_HASH_VERSION).toBe(14);
+ it('is 15 (14→15 folds the resolved FTS configuration name, so rows written before a reindex-search-vector language switch become unreachable)', () => {
+ expect(KNOBS_HASH_VERSION).toBe(15);
});
});
diff --git a/test/search-mode.test.ts b/test/search-mode.test.ts
index c8f1f067aa..01f159e5cc 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -416,7 +416,11 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {
// v0.42.67.x bumped 13→14: the compiled_truth boost no longer applies at
// detail=medium (#3430). Cached rows were ranked under the old semantics,
// so they must become unreachable rather than be served under the new ones.
- expect(KNOBS_HASH_VERSION).toBe(14);
+ // Bumped 14→15 to fold the resolved FTS configuration name (fts=) —
+ // GBRAIN_FTS_LANGUAGE retokenizes both the trigger-built search_vector and
+ // the query-side tsquery, so rows written under the previous language must
+ // not survive a `reindex-search-vector` switch.
+ expect(KNOBS_HASH_VERSION).toBe(15);
});
test('T1 (codex): floor_ratio set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {
@@ -581,8 +585,8 @@ describe('v0.40.4 — graph_signals knob', () => {
});
describe('v0.42.3.0 — autocut knobs', () => {
- test('KNOBS_HASH_VERSION is 14 (13→14 compiled_truth boost scope fix, #3430)', () => {
- expect(KNOBS_HASH_VERSION).toBe(14);
+ test('KNOBS_HASH_VERSION is 15 (14→15 FTS language fold)', () => {
+ expect(KNOBS_HASH_VERSION).toBe(15);
});
test('bundle defaults: conservative off, balanced/tokenmax on @0.20', () => {
diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.ts
index 8478864e0d..cc14678a63 100644
--- a/test/search/knobs-hash-reranker.test.ts
+++ b/test/search/knobs-hash-reranker.test.ts
@@ -44,7 +44,7 @@ function baseKnobs(): ResolvedSearchKnobs {
}
describe('KNOBS_HASH_VERSION + version invariants', () => {
- test('version is 13 (…; 10→11 asymmetric input_type #1400; 11→12 hard-excludes #2825; 12→13 embedding-provider migration #3390)', () => {
+ test('version is 15 (…; 11→12 hard-excludes #2825; 12→13 embedding-provider migration #3390; 14→15 FTS language)', () => {
// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold
// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs
// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).
@@ -67,7 +67,11 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {
// #3430: 13→14 — the compiled_truth boost no longer applies at
// detail=medium. Results are cached after fusion, so rows ranked under
// the old boost semantics must not be served under the new ones.
- expect(KNOBS_HASH_VERSION).toBe(14);
+ // FTS language: 14→15 to fold the resolved GBRAIN_FTS_LANGUAGE config
+ // name (fts=). It retokenizes both the trigger-built search_vector and
+ // the query-side tsquery, so rows written under the previous language
+ // must not survive a `reindex-search-vector` language switch.
+ expect(KNOBS_HASH_VERSION).toBe(15);
});
test('hash is 16 hex chars regardless of reranker config', () => {