Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(schema): apply the configured FTS language to the schema template — initSchema replay reverts non-English brains to 'english' (#3774)

Garry Tanf7d4f19124fe
diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.md
index 10488f424c..1bf3178c83 100644
--- a/docs/guides/multi-language-fts.md
+++ b/docs/guides/multi-language-fts.md
@@ -53,6 +53,11 @@ gbrain reindex-search-vector --dry-run # preview: language + row counts
gbrain reindex-search-vector --yes # recreate triggers + backfill
```
+The stamp survives later schema work: `initSchema()` — including the replay
+behind `gbrain init --migrate-only` on every upgrade — applies the schema
+template under the configured language, so it re-creates the trigger
+functions as they already are instead of reverting them to `english`.
+
The command recreates both trigger functions under the new language and
backfills every existing `pages` and `content_chunks` row in batches,
streaming progress to stderr. It is idempotent: re-running with the same
diff --git a/src/core/fts-language.ts b/src/core/fts-language.ts
index 569c0410f4..5b8cf1e399 100644
--- a/src/core/fts-language.ts
+++ b/src/core/fts-language.ts
@@ -67,3 +67,32 @@ export function getFtsLanguage(): string {
export function resetFtsLanguageCache(): void {
cachedLanguage = null;
}
+
+/**
+ * Rewrites a schema template's hardcoded `to_tsvector('english', ...)` calls
+ * to the configured text search configuration.
+ *
+ * Why this exists: migration v123 (`configurable_fts_language`) stamps the
+ * two search_vector trigger functions with `getFtsLanguage()` at apply time,
+ * but the schema templates that `initSchema()` replays still carry the
+ * literal 'english'. Those templates are applied with `CREATE OR REPLACE
+ * FUNCTION`, so every `initSchema()` — including the one behind
+ * `gbrain init --migrate-only`, which reports "Schema up to date" — silently
+ * reverts a non-English brain's trigger functions to english. The write side
+ * then tokenizes under a different configuration than the read side, and
+ * nothing warns: rows keep being indexed, just unreachable by the queries
+ * that were supposed to find them.
+ *
+ * Mirrors `applyChunkEmbeddingIndexPolicy()`: a runtime-config-driven rewrite
+ * of the static schema template, applied at the same seam in both engines.
+ *
+ * No-op for the default configuration, so English installs get a
+ * byte-identical schema string.
+ */
+export function applyFtsLanguagePolicy(sql: string): string {
+ const lang = getFtsLanguage();
+ if (lang === DEFAULT_LANGUAGE) return sql;
+ // getFtsLanguage() validates against VALID_CONFIG_NAME, so the value is
+ // safe to interpolate as a SQL string literal.
+ return sql.replaceAll(`to_tsvector('${DEFAULT_LANGUAGE}',`, `to_tsvector('${lang}',`);
+}
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index e92744448e..3e782359a5 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -22,6 +22,7 @@
*/
import { applyChunkEmbeddingIndexPolicy } from './vector-index.ts';
+import { applyFtsLanguagePolicy } from './fts-language.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
const PGLITE_SCHEMA_SQL_TEMPLATE = `
@@ -1128,7 +1129,7 @@ export function getPGLiteSchema(
throw new Error(`Invalid embedding dimensions: ${dims}`);
}
const sanitizedModel = String(model).replace(/'/g, "''");
- return applyChunkEmbeddingIndexPolicy(PGLITE_SCHEMA_SQL_TEMPLATE, parsedDims)
+ return applyFtsLanguagePolicy(applyChunkEmbeddingIndexPolicy(PGLITE_SCHEMA_SQL_TEMPLATE, parsedDims))
.replace(/__EMBEDDING_DIMS__/g, String(parsedDims))
.replace(/__EMBEDDING_MODEL__/g, sanitizedModel);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af00c7b832..4ba0cf765c 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -56,7 +56,7 @@ import {
COLUMN_NAME_REGEX,
EmbeddingColumnNotRegisteredError,
} from './search/embedding-column.ts';
-import { getFtsLanguage } from './fts-language.ts';
+import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
import type {
Page, PageInput, PageFilters, PageType,
@@ -107,7 +107,7 @@ export function getPostgresSchema(
throw new Error(`Invalid embedding dimensions: ${dims}`);
}
const sanitizedModel = escapeSqlStringLiteral(String(model));
- return applyChunkEmbeddingIndexPolicy(SCHEMA_SQL, parsedDims)
+ return applyFtsLanguagePolicy(applyChunkEmbeddingIndexPolicy(SCHEMA_SQL, parsedDims))
.replace(/vector\(1536\)/g, `vector(${parsedDims})`)
.replace(/'text-embedding-3-large'/g, `'${sanitizedModel}'`)
.replace(/\('embedding_dimensions', '1536'\)/g, `('embedding_dimensions', '${parsedDims}')`);
diff --git a/test/fts-language-schema-replay.serial.test.ts b/test/fts-language-schema-replay.serial.test.ts
new file mode 100644
index 0000000000..d6990afe73
--- /dev/null
+++ b/test/fts-language-schema-replay.serial.test.ts
@@ -0,0 +1,153 @@
+/**
+ * `initSchema()` must not revert a non-English brain's search_vector trigger
+ * functions to 'english'.
+ *
+ * Migration v123 (`configurable_fts_language`) stamps
+ * `update_page_search_vector` / `update_chunk_search_vector` with
+ * `getFtsLanguage()` when it applies. But the schema templates that
+ * `initSchema()` replays — `src/schema.sql` and `PGLITE_SCHEMA_SQL_TEMPLATE` —
+ * still carried the literal `to_tsvector('english', …)`, and they are applied
+ * with `CREATE OR REPLACE FUNCTION`. So the SECOND `initSchema()` clobbers
+ * what v123 stamped on the first: v123 is already recorded as applied, so the
+ * migration runner skips it and nothing puts the language back.
+ *
+ * That second call is not hypothetical — it is what `gbrain init
+ * --migrate-only` does on every upgrade, and it prints "Schema up to date"
+ * while doing it. The write side then tokenizes under a different
+ * configuration than `searchKeyword`/`searchTitles`/`searchKeywordChunks`
+ * read under, with no warning: rows keep being indexed, just unreachable by
+ * the queries meant to find them.
+ *
+ * The replay test below is the discriminating one — a single `initSchema()`
+ * on a fresh brain passes either way, because v123 runs and stamps the
+ * correct language. Only the replay separates fixed from broken.
+ *
+ * `simple` is used as the non-default configuration because it ships with
+ * every Postgres build (no extension needed) and is not the default, so a
+ * clobber back to 'english' is unambiguous.
+ *
+ * Serial: mutates process.env (isolation guard R2).
+ */
+
+import { describe, test, expect, beforeEach, afterEach, afterAll } from 'bun:test';
+import { applyFtsLanguagePolicy, resetFtsLanguageCache } from '../src/core/fts-language.ts';
+import { getPostgresSchema } from '../src/core/postgres-engine.ts';
+import { getPGLiteSchema } from '../src/core/pglite-schema.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+const ENV_KEY = 'GBRAIN_FTS_LANGUAGE';
+const originalLang = process.env[ENV_KEY];
+
+const TSVECTOR_EN = /to_tsvector\('english',/g;
+const TSVECTOR_SIMPLE = /to_tsvector\('simple',/g;
+
+function count(haystack: string, re: RegExp): number {
+ return (haystack.match(re) ?? []).length;
+}
+
+beforeEach(() => {
+ delete process.env[ENV_KEY];
+ resetFtsLanguageCache();
+});
+
+afterEach(() => {
+ delete process.env[ENV_KEY];
+ resetFtsLanguageCache();
+});
+
+afterAll(() => {
+ if (originalLang !== undefined) process.env[ENV_KEY] = originalLang;
+ resetFtsLanguageCache();
+});
+
+describe('applyFtsLanguagePolicy', () => {
+ test('is identity for the default configuration (English installs unchanged)', () => {
+ const sql = "setweight(to_tsvector('english', COALESCE(NEW.chunk_text, '')), 'B')";
+ expect(applyFtsLanguagePolicy(sql)).toBe(sql);
+ });
+
+ test('rewrites every to_tsvector call when a configuration is set', () => {
+ process.env[ENV_KEY] = 'simple';
+ const sql = "to_tsvector('english', a) || to_tsvector('english', b)";
+ expect(applyFtsLanguagePolicy(sql)).toBe("to_tsvector('simple', a) || to_tsvector('simple', b)");
+ });
+
+ test('leaves an invalid configuration on the default (validation is upstream)', () => {
+ process.env[ENV_KEY] = 'Robert; DROP TABLE pages';
+ const sql = "to_tsvector('english', a)";
+ expect(applyFtsLanguagePolicy(sql)).toBe(sql);
+ });
+});
+
+describe('schema templates carry the configured FTS language', () => {
+ test('postgres: default leaves english in place', () => {
+ const sql = getPostgresSchema();
+ expect(count(sql, TSVECTOR_EN)).toBeGreaterThan(0);
+ expect(count(sql, TSVECTOR_SIMPLE)).toBe(0);
+ });
+
+ test('postgres: configured language replaces every english tsvector', () => {
+ const before = count(getPostgresSchema(), TSVECTOR_EN);
+ resetFtsLanguageCache();
+ process.env[ENV_KEY] = 'simple';
+ const sql = getPostgresSchema();
+ expect(count(sql, TSVECTOR_EN)).toBe(0);
+ expect(count(sql, TSVECTOR_SIMPLE)).toBe(before);
+ });
+
+ test('pglite: default leaves english in place', () => {
+ const sql = getPGLiteSchema();
+ expect(count(sql, TSVECTOR_EN)).toBeGreaterThan(0);
+ expect(count(sql, TSVECTOR_SIMPLE)).toBe(0);
+ });
+
+ test('pglite: configured language replaces every english tsvector', () => {
+ const before = count(getPGLiteSchema(), TSVECTOR_EN);
+ resetFtsLanguageCache();
+ process.env[ENV_KEY] = 'simple';
+ const sql = getPGLiteSchema();
+ expect(count(sql, TSVECTOR_EN)).toBe(0);
+ expect(count(sql, TSVECTOR_SIMPLE)).toBe(before);
+ });
+});
+
+describe('initSchema replay preserves the configured FTS language (the upgrade path)', () => {
+ test('a second initSchema() does not revert the trigger functions to english', async () => {
+ process.env[ENV_KEY] = 'simple';
+ resetFtsLanguageCache();
+ // A loaded snapshot short-circuits initSchema() entirely (`_snapshotLoaded`),
+ // which would make the replay vacuous. Force the real path.
+ const savedSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;
+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
+ const engine = new PGLiteEngine();
+ try {
+ await engine.connect({ database_url: '' });
+
+ // First apply: schema template + migrations. v123 stamps the trigger
+ // functions with the configured language.
+ await engine.initSchema();
+
+ const afterFirst = await engine.executeRaw<{ prosrc: string }>(
+ `SELECT prosrc FROM pg_proc WHERE proname = 'update_page_search_vector'`,
+ );
+ expect(afterFirst.length).toBe(1);
+ expect(afterFirst[0]!.prosrc).toContain("'simple'");
+
+ // Replay — what `gbrain init --migrate-only` does on every upgrade.
+ // v123 is already recorded as applied, so nothing re-stamps the
+ // functions; only the schema template runs, via CREATE OR REPLACE.
+ await engine.initSchema();
+
+ const afterReplay = await engine.executeRaw<{ prosrc: string }>(
+ `SELECT prosrc FROM pg_proc WHERE proname = 'update_page_search_vector'`,
+ );
+ expect(afterReplay.length).toBe(1);
+ expect(afterReplay[0]!.prosrc).toContain("'simple'");
+ expect(afterReplay[0]!.prosrc).not.toContain("'english'");
+ } finally {
+ await engine.disconnect();
+ if (savedSnapshot !== undefined) process.env.GBRAIN_PGLITE_SNAPSHOT = savedSnapshot;
+ }
+ });
+});