Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migration): facts question-recall indexes build CONCURRENTLY; idx_facts_fts swaps in with no gap
garrytan4deb81dd2c7d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 6382e20a1b..a29d71675e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex d6fbe051ea..84f9b95790 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 4d986d4141..dd9d0d157b 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.167.0 -->+<!-- gbrain-runbook-stamp: 0.60.166.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c2d70e4a3a..975b2b64d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,15 +10,15 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).-## [0.60.167.0] - 2026-10-11+## [Unreleased]**`recall` can rank saved facts by a question.** Pass `question` and recall returns the facts most relevant to it, each with a `relevance` score, instead of the newest ones. Facts below the match threshold are left out, so an empty list means nothing saved matches.Calls without `question` behave as before and return the newest facts; every response now says which order it used in `facts_order`. A call that passes only `query` carries a `recall_hint` notice naming `question` and the exact retry call. `gbrain recall --question "<q>"` works from the CLI, locally or against a remote brain. Ranking uses the same read policy as every other recall: the trust floor, quarantine and rederive hiding, remote world-only facts and the private-page filter all apply. Restart a resident `gbrain serve` after upgrading so agents see the new parameter.-## To take advantage of v0.60.167.0+## To take advantage of [Unreleased]-`gbrain upgrade` applies the facts index migration (v236) automatically. If `gbrain doctor` warns about a partial migration, run `gbrain apply-migrations --yes`, then restart a resident `gbrain serve`.+`gbrain upgrade` applies the facts index migration (numbered at stamp time; v236 on this branch) automatically. If `gbrain doctor` warns about a partial migration, run `gbrain apply-migrations --yes`, then restart a resident `gbrain serve`.### Itemized changes@@ -26,7 +26,7 @@ Calls without `question` behave as before and return the newest facts; every res- **Admission rule** (`recall.question_admission`). `reserve` (default) keeps a fact at cosine 0.5 or a third of the question's words; `facts_arm` uses the stricter facts-arm rule.- **Shared fact scorer** (`search/fact-relevance.ts`). Recall's `question`, the temporal fact reserve and the facts arm now read one candidate pool and one scorer. Word matches are whole-word, and a very long fact's matches count for less. In `query`, facts of an entity the question names come only from that entity page's own source.- **`gbrain recall --question`** reads its value as the question; before, it was taken as an entity name.-- **Fast on large brains.** On a 100k-fact brain a ranked recall takes 51 ms at p95 on Postgres (65 ms for a remote caller, 10 ms with `entity`) and 152 ms on PGLite (139 ms remote, 54 ms with `entity`). The facts index migration (v236) adds a keyword index over active facts (built under `GBRAIN_FTS_LANGUAGE`; `gbrain reindex-search-vector` rebuilds it when the language changes) and two small indexes for the unembedded count; the vector, keyword and entity lookups run concurrently, the vector lookup now uses the facts HNSW index, and the keyword lookup is planned per call. Building the indexes reads each fact once (about 2 seconds per 100k facts) and rewrites none.+- **Fast on large brains.** On a 100k-fact brain a ranked recall takes 51 ms at p95 on Postgres (65 ms for a remote caller, 10 ms with `entity`) and 152 ms on PGLite (139 ms remote, 54 ms with `entity`). The facts index migration (numbered at stamp time; v236 on this branch) adds a keyword index over active facts (built under `GBRAIN_FTS_LANGUAGE`; `gbrain reindex-search-vector` replaces it when the language changes) and two small indexes for the unembedded count. On Postgres every index is built `CONCURRENTLY`, so writes to facts never wait on the build, and the keyword index is built under a temporary name and renamed into place, so search keeps an index throughout; an interrupted migration or reindex finishes on its next run. The vector, keyword and entity lookups run concurrently, the vector lookup now uses the facts HNSW index, and the keyword lookup is planned per call. Building the indexes reads each fact once (about 2 seconds per 100k facts) and rewrites none.- **Embedding model switches keep fact indexes.** A dimension change rebuilds `facts.embedding` and now re-creates the btree indexes that read it instead of dropping them.### For contributorsdiff --git a/VERSION b/VERSIONindex 3fb9c41e0a..56a9d40d77 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.167.0+0.60.166.0diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex b57fa98512..f6d7f4a096 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding; each rebuild runs inside `withHnswBuildMemory` (vector-index.ts), which sizes PGLite's `maintenance_work_mem` to the graph or refuses with `pglite_vector_index_too_large`. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.-- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language through `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (`fts-language.ts`; they KEEP the `SET search_path = pg_catalog, public` hardening, which CREATE OR REPLACE resets) — then backfills `pages` and `content_chunks` through `src/core/search-vector-backfill.ts` in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000). Pages: an UPDATE-to-self of `id` reads each batch (`RETURNING id, timeline, knowledge_revision`; row locks only for that statement), the timeline is sanitized with `sanitizeRemoteBody` as the seal does, and one `UPDATE … FROM unnest(…)` writes `search_vector` through `pageSearchVectorSql` (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`. It then rebuilds `idx_facts_fts` (v236) under the language (an index build, no row rewrite). Both stream phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts` and `test/reindex-search-vector-pages.serial.test.ts`.+- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language through `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (`fts-language.ts`; they KEEP the `SET search_path = pg_catalog, public` hardening, which CREATE OR REPLACE resets) — then backfills `pages` and `content_chunks` through `src/core/search-vector-backfill.ts` in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000). Pages: an UPDATE-to-self of `id` reads each batch (`RETURNING id, timeline, knowledge_revision`; row locks only for that statement), the timeline is sanitized with `sanitizeRemoteBody` as the seal does, and one `UPDATE … FROM unnest(…)` writes `search_vector` through `pageSearchVectorSql` (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`. It then replaces `idx_facts_fts` (v236) under the language through `ensureFactsFtsIndex` (`src/core/facts/fts-index.ts`): the new index is built beside the old one (CONCURRENTLY on Postgres) and renamed into place, so writes never wait and search keeps an index (no row rewrite). Both stream phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts` and `test/reindex-search-vector-pages.serial.test.ts`.- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 0d0afdfb58..5c159a1b9e 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -44,7 +44,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json` — Check 6 of `check-resolvable`. Parses `writes_pages:` / `writes_to:` frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). Internal `parseFrontmatter` is a thin wrapper over the shared `src/core/skill-frontmatter.ts` parser so both filing-audit and skill-brain-first read the same shape (`tools?`, `triggers?`, `brain_first?: 'exempt'`, typed `brain_first_typo`) from one source of truth.-- `src/core/fts-language.ts` — Single source for the FTS configuration name (write side, #6370: `engines-2.md`). `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). `factsFtsDocument`/`factsFtsIndexSql` build the facts keyword document and `idx_facts_fts` (v236). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).+- `src/core/fts-language.ts` — Single source for the FTS configuration name (write side, #6370: `engines-2.md`). `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). `factsFtsDocument`/`factsFtsIndexSql` build the facts keyword document and the `idx_facts_fts` definition (v236); `src/core/facts/fts-index.ts` `ensureFactsFtsIndex` builds it under `idx_facts_fts_next` (CONCURRENTLY on Postgres, via `buildIndexOnline`) and swaps it in with one rename transaction, dropping the old index last; every interrupted step converges on a rerun. Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).- `src/core/latin-fold.ts` — leaf text primitive (no engine/graph imports): `NON_DECOMPOSING_LATIN`, the lowercase-keyed table of the eleven Latin stroke/bar/ligature letters Unicode gives no decomposition (đ ð ø ł ħ ŧ ı ß æ œ þ), + `foldNonDecomposingLatin(s)`. Call it AFTER lowercasing and AFTER the combining-mark strip so composed forms reduce in one pass (ǿ → ø → o). Consumers: `entities/resolve.ts:slugify` (entity fallback slugs — pre-fold `Đăng Example` collided onto `ang-example` and an all-stroke name slugged to empty) and `link-extraction.ts:normalizeBasename` (basename-index keys + dir-hint candidates). Deliberately NOT applied to `sync.ts:slugifySegment` — the page-slug grammar keeps these letters (#3417) — so the dir-hint candidate step in `makeResolver` / the FS resolver tries both forms.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 14d819da36..067b030a44 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex b47024465b..3d85824290 100644--- a/package.json+++ b/package.json@@ -231,7 +231,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.167.0",+ "version": "0.60.166.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 3a01d547d0..a5f0f2b23e 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 8038e89d3a..dcd53da1c1 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 85df832419..146bf1d0be 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.167.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.166.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 67e357439d..9a750b14c1 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 547f6a8a01..033e19486c 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.167.0",+ "version": "0.60.166.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex ac8a5ec64f..3a6ad07675 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.167.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.166.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 73ea726746..ffb40830e0 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.167.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.166.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/src/commands/reindex-search-vector.ts b/src/commands/reindex-search-vector.tsindex 8cd1ef31f1..24974631f8 100644--- a/src/commands/reindex-search-vector.ts+++ b/src/commands/reindex-search-vector.ts@@ -1,6 +1,6 @@/*** `gbrain reindex-search-vector` — recreate FTS trigger functions,- * backfill existing rows and rebuild the facts keyword index+ * backfill existing rows and replace the facts keyword index* (`idx_facts_fts`, migration v236) under the language configured via* GBRAIN_FTS_LANGUAGE.*@@ -47,8 +47,9 @@*/import type { BrainEngine } from '../core/engine.ts';-import { getFtsLanguage, factsFtsIndexSql, FTS_REINDEX_MARKER_KEY, pageSearchVectorTriggerFnSql, chunkSearchVectorTriggerFnSql } from '../core/fts-language.ts';+import { getFtsLanguage, FTS_REINDEX_MARKER_KEY, pageSearchVectorTriggerFnSql, chunkSearchVectorTriggerFnSql } from '../core/fts-language.ts';import { checkpointKey } from '../core/backfill-base.ts';+import { ensureFactsFtsIndex } from '../core/facts/fts-index.ts';import { consentGate } from '../core/consent-cli.ts';import type { ConsentEnv } from '../core/consent.ts';import { createProgress } from '../core/progress.ts';@@ -194,8 +195,8 @@ export async function runReindexSearchVector(await backfillChunkVectors(engine, { lang, checkpoint: CHECKPOINT_NAME.content_chunks, tick: n => progress.tick(n) });progress.finish();- // The facts keyword index is an expression index under a literal language: rebuild it (no row rewrite).- for (const sql of factsFtsIndexSql(lang)) await engine.executeRaw(sql);+ // The facts keyword index is an expression index under a literal language: build the new one beside it and swap (no row rewrite, no gap).+ await ensureFactsFtsIndex(engine, { lang, version: 0, notice: line => process.stderr.write(line) });// Both backfills returned: the index is whole again under `lang`.await engine.unsetConfig(checkpointKey(CHECKPOINT_NAME.pages));diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 1053c6cb86..df34199a6a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -405,8 +405,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Fix wave 13 PR2 (GBRA-57).{ since: '0.60.165.0', text: 'Managed sync: a Postgres publish still running 30 s past `persistence.publication_ceiling_ms` (default 5 min) is cancelled (its connection is discarded, nothing commits, and the write is queued again); one that still does not settle makes its owner report `restart_required`. `gbrain sync` stops `drain_stalled` (`publication_overdue`, or `no_admission` after 5 minutes with nothing admitted) instead of waiting forever, and a source more than 100,000 changes behind catches up in bounded stages instead of refusing. `gbrain migrate` with the legacy copier now forwards each page\'s origin path, kind, provenance, `ingested_at` and aliases, and rebuilds the text projections of pages the source had sealed before it switches the engine; a failed rebuild keeps the old engine active and exits 1.' },{ since: '0.60.165.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs permission to write pages); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },- // Memory proof wave 2 W1 (question-ranked recall).- { since: '0.60.167.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },+ // Memory proof wave 2 W1 (question-ranked recall); `since` is a placeholder equal to the branch's VERSION (it must not exceed it) until the merge-slot stamp.+ { since: '0.60.166.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/fts-index.ts b/src/core/facts/fts-index.tsnew file mode 100644index 0000000000..ecc016619b--- /dev/null+++ b/src/core/facts/fts-index.ts@@ -0,0 +1,60 @@+/**+ * `idx_facts_fts`, the facts keyword index (`factsFtsDocument` under a literal+ * text search configuration), built and replaced without blocking writers or+ * leaving search without an index. The facts-index migration and+ * `gbrain reindex-search-vector` both call `ensureFactsFtsIndex`.+ *+ * The new definition is built as `idx_facts_fts_next` (CONCURRENTLY on+ * Postgres through `buildIndexOnline`), then one short transaction renames the+ * live index to `idx_facts_fts_old` and the new one into place; renaming an+ * index takes no lock that blocks reads or writes. The old index is dropped+ * last (CONCURRENTLY on Postgres). Every interrupted state converges on a+ * rerun: a current `idx_facts_fts` clears the leftovers, an invalid or stale+ * `_next` is dropped and rebuilt, and a stray `_old` is dropped before the swap.+ */++import type { BrainEngine } from '../engine.ts';+import { factsFtsIndexSql } from '../fts-language.ts';+import { buildIndexOnline } from '../schema-migrations/helpers.ts';++export const FACTS_FTS_INDEX = 'idx_facts_fts';+const NEXT = 'idx_facts_fts_next';+const OLD = 'idx_facts_fts_old';++export type FactsFtsSwapStep = 'built' | 'renamed';++async function indexState(engine: BrainEngine, name: string, lang: string): Promise<'missing' | 'current' | 'stale'> {+ const [row] = await engine.executeRaw<{ valid: boolean; def: string }>(+ 'SELECT i.indisvalid AS valid, pg_get_indexdef(i.indexrelid) AS def FROM pg_index i WHERE i.indexrelid = to_regclass($1)', [name]);+ if (!row) return 'missing';+ return row.valid && row.def.includes(`to_tsvector('${lang}'::regconfig`) && row.def.includes('entity_slug') ? 'current' : 'stale';+}++async function dropIndex(engine: BrainEngine, version: number, name: string): Promise<void> {+ await engine.runMigration(version, engine.kind === 'postgres' ? `DROP INDEX CONCURRENTLY IF EXISTS ${name}` : `DROP INDEX IF EXISTS ${name}`);+}++/** Leaves a valid `idx_facts_fts` under `lang`; `swapped` when it built and swapped in a new one. */+export async function ensureFactsFtsIndex(+ engine: BrainEngine,+ opts: { lang: string; version: number; notice?: (line: string) => void; onStep?: (step: FactsFtsSwapStep) => Promise<void> },+): Promise<'present' | 'swapped'> {+ const { lang, version } = opts;+ if (await indexState(engine, FACTS_FTS_INDEX, lang) === 'current') {+ await dropIndex(engine, version, NEXT);+ await dropIndex(engine, version, OLD);+ return 'present';+ }+ if (await indexState(engine, NEXT, lang) === 'stale') await dropIndex(engine, version, NEXT);+ const built = await buildIndexOnline(engine, version, { name: NEXT, table: 'facts', sql: factsFtsIndexSql(NEXT, lang) }, { notice: opts.notice });+ if (built === 'building') throw new Error(`${NEXT} is being built by another session; rerun once it finishes`);+ await opts.onStep?.('built');+ await dropIndex(engine, version, OLD);+ await engine.transaction(async tx => {+ await tx.executeRaw(`ALTER INDEX IF EXISTS ${FACTS_FTS_INDEX} RENAME TO ${OLD}`);+ await tx.executeRaw(`ALTER INDEX ${NEXT} RENAME TO ${FACTS_FTS_INDEX}`);+ });+ await opts.onStep?.('renamed');+ await dropIndex(engine, version, OLD);+ return 'swapped';+}diff --git a/src/core/fts-language.ts b/src/core/fts-language.tsindex 6247d40e91..385be39de2 100644--- a/src/core/fts-language.ts+++ b/src/core/fts-language.ts@@ -113,20 +113,17 @@ export function applyFtsLanguagePolicy(sql: string): string {* The facts keyword document: fact text plus the entity slug's words, under* a literal text search configuration so `idx_facts_fts` can serve it (an* expression index matches only the same literal configuration, never a- * bound parameter). The migration, `gbrain reindex-search-vector` and the- * question-recall keyword arm all build it here.+ * bound parameter). The index (facts/fts-index.ts) and the question-recall+ * keyword arm both build it here.*/export function factsFtsDocument(alias: string | null, lang: string = getFtsLanguage()): string {const col = (c: string) => alias ? `${alias}.${c}` : c;return `to_tsvector('${lang}'::regconfig, ${col('fact')} || ' ' || replace(COALESCE(${col('entity_slug')}, ''), '-', ' '))`;}-/** Recreate `idx_facts_fts` (GIN over active facts) under `lang`; an index build, no row rewrite. */-export function factsFtsIndexSql(lang: string = getFtsLanguage()): string[] {- return [- 'DROP INDEX IF EXISTS idx_facts_fts',- `CREATE INDEX idx_facts_fts ON facts USING gin (${factsFtsDocument(null, lang)}) WHERE expired_at IS NULL`,- ];+/** The facts keyword GIN index over active facts under `lang`, named `name` (facts/fts-index.ts builds and swaps it). */+export function factsFtsIndexSql(name: string, lang: string): string {+ return `CREATE INDEX IF NOT EXISTS ${name} ON facts USING gin (${factsFtsDocument(null, lang)}) WHERE expired_at IS NULL`;}const CJK_CLASS = `[${CJK_SLUG_CHARS}]`;diff --git a/src/core/schema-migrations/v236-facts-question-recall-indexes.ts b/src/core/schema-migrations/v236-facts-question-recall-indexes.tsindex daa5819a11..339e7df840 100644--- a/src/core/schema-migrations/v236-facts-question-recall-indexes.ts+++ b/src/core/schema-migrations/v236-facts-question-recall-indexes.ts@@ -1,5 +1,7 @@import type { Migration } from './types.ts';-import { factsFtsIndexSql, getFtsLanguage } from '../fts-language.ts';+import { getFtsLanguage } from '../fts-language.ts';+import { ensureFactsFtsIndex } from '../facts/fts-index.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.@@ -13,7 +15,7 @@ export const v236: Migration = {// (about 450 ms at 100k facts on Postgres). The text search configuration// must be a literal for the planner to match an expression index, so the// handler builds it under GBRAIN_FTS_LANGUAGE, as v123 does for the trigger- // functions, and `gbrain reindex-search-vector` rebuilds it when the+ // functions, and `gbrain reindex-search-vector` replaces it when the// language changes. An expression index, not a stored tsvector column: a// column backfill rewrites every fact row and its HNSW entry (about 7// minutes at 100k facts); the index build reads the rows once (about 2 s).@@ -23,13 +25,18 @@ export const v236: Migration = {// stale text hash; another embedding model) on every call; unindexed it is// an md5 scan of the whole source (about 130 ms at 100k facts).//- // Re-running drops and rebuilds idx_facts_fts and skips the others: safe.+ // Postgres builds every index CONCURRENTLY, one at a time, outside the+ // migration transaction (a handler); idx_facts_fts is built under a+ // temporary name and swapped in (facts/fts-index.ts), so writes never wait+ // on a build and search always has an index. PGLite builds inline. A rerun+ // after an interruption drops invalid leftovers and finishes the swap.idempotent: true,sql: '',handler: async (engine) => {- for (const sql of factsFtsIndexSql(getFtsLanguage())) await engine.executeRaw(sql);- await engine.executeRaw(`CREATE INDEX IF NOT EXISTS idx_facts_unembedded ON facts (source_id)- WHERE expired_at IS NULL AND (embedding IS NULL OR embedded_text_hash IS DISTINCT FROM md5(fact))`);- await engine.executeRaw(`CREATE INDEX IF NOT EXISTS idx_facts_embedding_model ON facts (source_id, embedding_model) WHERE expired_at IS NULL`);+ await ensureFactsFtsIndex(engine, { lang: getFtsLanguage(), version: 236, notice: migrationNotice });+ await buildIndexOnline(engine, 236, { name: 'idx_facts_unembedded', table: 'facts', sql: `CREATE INDEX IF NOT EXISTS idx_facts_unembedded ON facts (source_id)+ WHERE expired_at IS NULL AND (embedding IS NULL OR embedded_text_hash IS DISTINCT FROM md5(fact))` }, { notice: migrationNotice });+ await buildIndexOnline(engine, 236, { name: 'idx_facts_embedding_model', table: 'facts',+ sql: 'CREATE INDEX IF NOT EXISTS idx_facts_embedding_model ON facts (source_id, embedding_model) WHERE expired_at IS NULL' }, { notice: migrationNotice });},};diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 325d9ac27a..1ec23e5112 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.167.0 -->+<!-- gbrain-template-stamp: 0.60.166.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/e2e/facts-fts-index-postgres.test.ts b/test/e2e/facts-fts-index-postgres.test.tsnew file mode 100644index 0000000000..c0b3261249--- /dev/null+++ b/test/e2e/facts-fts-index-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../facts-fts-index.test.ts'));diff --git a/test/facts-fts-index.test.ts b/test/facts-fts-index.test.tsnew file mode 100644index 0000000000..99ef4aa017--- /dev/null+++ b/test/facts-fts-index.test.ts@@ -0,0 +1,162 @@+/**+ * The facts keyword index (`idx_facts_fts`) is built and replaced without+ * blocking writers or leaving search without an index (facts/fts-index.ts,+ * the facts question-recall index migration, `gbrain reindex-search-vector`).+ * Postgres builds CONCURRENTLY; PGLite inline. Every interrupted state (an+ * invalid or stale `_next`, a stray `_old`, a failed build) converges on a+ * rerun, and keyword search finds the facts at every step of the swap.+ * Postgres arm: test/e2e/facts-fts-index-postgres.test.ts.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { factsFtsDocument, factsFtsIndexSql, getFtsLanguage } from '../src/core/fts-language.ts';+import { ensureFactsFtsIndex, type FactsFtsSwapStep } from '../src/core/facts/fts-index.ts';+import { v236 } from '../src/core/schema-migrations/v236-facts-question-recall-indexes.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const LANG = getFtsLanguage();+const NAMES = ['idx_facts_fts', 'idx_facts_fts_next', 'idx_facts_fts_old'];++for (const kind of testBackends()) {+ describe(`facts keyword index swap (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ for (const [i, text] of ['KAYAK Alice Example paddles a Wavecraft kayak', 'OFFSITE The quarterly offsite moved to Denver'].entries()) {+ await engine.executeRaw(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, source) VALUES ('default', $1, $2, 'fact', 'world', now(), 'test')`,+ [i === 0 ? 'people/alice-example' : null, text]);+ }+ }, 180_000);+ afterAll(async () => { await close?.(); });++ /** name → missing | valid | invalid, plus each present index's language. */+ const states = async (): Promise<Record<string, string>> => Object.fromEntries(await Promise.all(NAMES.map(async name => {+ const [row] = await engine.executeRaw<{ valid: boolean; def: string }>(+ 'SELECT i.indisvalid AS valid, pg_get_indexdef(i.indexrelid) AS def FROM pg_index i WHERE i.indexrelid = to_regclass($1)', [name]);+ return [name, row ? `${row.valid ? 'valid' : 'invalid'}:${/to_tsvector\('(\w+)'/.exec(row.def)?.[1]}` : 'missing'];+ })));+ const keywordHits = async () => (await engine.executeRaw<{ fact: string }>(+ `SELECT f.fact FROM facts f WHERE f.expired_at IS NULL AND ${factsFtsDocument('f', LANG)} @@ plainto_tsquery('${LANG}'::regconfig, 'kayak wavecraft')`)).map(r => r.fact.split(' ')[0]);+ /** Search works and a valid keyword index stays on facts at this step. */+ const expectServing = async (label: string) => {+ expect(await keywordHits(), label).toEqual(['KAYAK']);+ const valid = Object.entries(await states()).filter(([, s]) => s.startsWith('valid:'));+ expect(valid.length, `${label}: a valid keyword index exists`).toBeGreaterThan(0);+ };+ const dropAll = async () => { for (const name of NAMES) await engine.executeRaw(`DROP INDEX IF EXISTS ${name}`); };+ const createAs = (name: string, lang: string) => engine.executeRaw(factsFtsIndexSql(name, lang));+ const ensure = (onStep?: (step: FactsFtsSwapStep) => Promise<void>) => ensureFactsFtsIndex(engine, { lang: LANG, version: 236, onStep });++ beforeEach(async () => { await dropAll(); });++ test('the migration leaves the three indexes valid and no swap leftovers; a rerun changes nothing', async () => {+ await v236.handler!(engine);+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ const others = await engine.executeRaw<{ valid: boolean }>(+ `SELECT i.indisvalid AS valid FROM pg_index i WHERE i.indexrelid IN (to_regclass('idx_facts_unembedded'), to_regclass('idx_facts_embedding_model'))`);+ expect(others.map(r => r.valid)).toEqual([true, true]);+ expect(await ensure()).toBe('present');+ await expectServing('after the migration');+ });++ test('a language change builds the new index beside the old one and swaps it in; search works at every step', async () => {+ await createAs('idx_facts_fts', 'simple');+ const seen: Record<string, Record<string, string>> = {};+ await expectServing('before');+ expect(await ensure(async step => { seen[step] = await states(); await expectServing(step); })).toBe('swapped');+ expect(seen.built).toEqual({ idx_facts_fts: 'valid:simple', idx_facts_fts_next: `valid:${LANG}`, idx_facts_fts_old: 'missing' });+ expect(seen.renamed).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'valid:simple' });+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ await expectServing('after');+ });++ test('an INVALID _next leftover of an interrupted build is dropped and rebuilt', async () => {+ await createAs('idx_facts_fts', 'simple');+ await createAs('idx_facts_fts_next', LANG);+ await engine.executeRaw(`UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'idx_facts_fts_next'::regclass`);+ expect((await states()).idx_facts_fts_next).toBe(`invalid:${LANG}`);+ expect(await ensure()).toBe('swapped');+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ await expectServing('after');+ });++ test('a valid _next under another language (a reindex interrupted before a second language change) is replaced', async () => {+ await createAs('idx_facts_fts_next', 'simple');+ expect(await ensure()).toBe('swapped');+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ });++ test('half-swapped: a current index with _old and _next leftovers clears both and keeps the index', async () => {+ await createAs('idx_facts_fts', LANG);+ await createAs('idx_facts_fts_old', 'simple');+ await createAs('idx_facts_fts_next', 'simple');+ expect(await ensure()).toBe('present');+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ await expectServing('after');+ });++ test('a stray _old beside a stale index does not block the rename', async () => {+ await createAs('idx_facts_fts', 'simple');+ await createAs('idx_facts_fts_old', 'simple');+ expect(await ensure()).toBe('swapped');+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ });++ test('a failed build leaves the live index serving, and a rerun finishes the swap', async () => {+ await createAs('idx_facts_fts', 'simple');+ const fail = (sql: string) => sql.includes('idx_facts_fts_next') && sql.trimStart().startsWith('CREATE INDEX');+ if (kind === 'postgres') {+ const reserve = engine.withReservedConnection.bind(engine);+ engine.withReservedConnection = (async (fn: Parameters<BrainEngine['withReservedConnection']>[0]) => reserve(conn => fn({+ executeRaw: async (sql: string, params?: unknown[]) => {+ if (fail(sql)) throw new Error('synthetic interrupted index build');+ return conn.executeRaw(sql, params);+ },+ } as never))) as BrainEngine['withReservedConnection'];+ try { await expect(ensure()).rejects.toThrow('synthetic interrupted index build'); } finally { engine.withReservedConnection = reserve; }+ } else {+ const run = engine.runMigration.bind(engine);+ engine.runMigration = async (version: number, sql: string) => { if (fail(sql)) throw new Error('synthetic interrupted index build'); return run(version, sql); };+ try { await expect(ensure()).rejects.toThrow('synthetic interrupted index build'); } finally { engine.runMigration = run; }+ }+ expect((await states()).idx_facts_fts).toBe('valid:simple');+ await expectServing('after the failed build');+ expect(await ensure()).toBe('swapped');+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ });++ test.skipIf(kind !== 'postgres')('Postgres builds every index CONCURRENTLY on its own connection and drops CONCURRENTLY', async () => {+ await createAs('idx_facts_fts', 'simple');+ for (const name of ['idx_facts_unembedded', 'idx_facts_embedding_model']) await engine.executeRaw(`DROP INDEX IF EXISTS ${name}`);+ const reserved: string[] = [];+ const ddl: string[] = [];+ const reserve = engine.withReservedConnection.bind(engine);+ const run = engine.runMigration.bind(engine);+ engine.withReservedConnection = (async (fn: Parameters<BrainEngine['withReservedConnection']>[0]) => reserve(conn => fn({+ executeRaw: async (sql: string, params?: unknown[]) => { reserved.push(sql); return conn.executeRaw(sql, params); },+ } as never))) as BrainEngine['withReservedConnection'];+ engine.runMigration = async (version: number, sql: string) => { ddl.push(sql); return run(version, sql); };+ try { await v236.handler!(engine); } finally { engine.withReservedConnection = reserve; engine.runMigration = run; }+ expect(reserved.map(sql => sql.trim().split(/\s+/).slice(0, 8).join(' '))).toEqual([+ 'CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_facts_fts_next ON',+ 'CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_facts_unembedded ON',+ 'CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_facts_embedding_model ON',+ ]);+ expect(ddl).toEqual(['DROP INDEX CONCURRENTLY IF EXISTS idx_facts_fts_old', 'DROP INDEX CONCURRENTLY IF EXISTS idx_facts_fts_old']);+ expect(await states()).toEqual({ idx_facts_fts: `valid:${LANG}`, idx_facts_fts_next: 'missing', idx_facts_fts_old: 'missing' });+ });+ });+}diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 044505f621..d8255fe11a 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -33,7 +33,7 @@"chunkSearchVectorTriggerFnSql": "93ed4e29aa058949621b4198fe1ec317218f4b9ec0db0626ec6dc7001032047d","clampOAuthTokenTtls": "b1e94ea8f5b3c3870a56b0f6d00d0a274c2e9dcad912b828848aec250732645f","dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c",- "factsFtsIndexSql": "2bfacc9979a0962b592b2edd3541508259e21f42156fb94d042566461925286c",+ "ensureFactsFtsIndex": "95e723314ac30cea2db48e0e167c554ef1fa06df80cae765faa2a080a3a655c2","getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db","grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26",@@ -3554,10 +3554,14 @@"handler": {"form": "arrow","helpers": [- "factsFtsIndexSql",- "getFtsLanguage"+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "ensureFactsFtsIndex",+ "getFtsLanguage",+ "migrationNotice",+ "quietMigrationNotices"],- "sha256": "264dd41685abb98743d788ee00d1c0467d29c85989c95156bd54ea0dd0421a08"+ "sha256": "06353dd185ebc55facdacec7b361e3f0bc36994192547d72861c1cf64cf5a87a"},"idempotent": true,"name": "facts_question_recall_indexes",diff --git a/test/reindex-search-vector.serial.test.ts b/test/reindex-search-vector.serial.test.tsindex b2886b80d8..21822739af 100644--- a/test/reindex-search-vector.serial.test.ts+++ b/test/reindex-search-vector.serial.test.ts@@ -23,7 +23,7 @@ interface MockState {function makeMockEngine(state: MockState): BrainEngine {const config = state.config ?? (state.config = new Map());const order = state.order ?? (state.order = []);- return {+ const engine = {executeRaw: async (sql: string) => {state.calls.push(sql);order.push(sql);@@ -34,6 +34,11 @@ function makeMockEngine(state: MockState): BrainEngine {}return [];},+ runMigration: async (_version: number, sql: string) => {+ state.calls.push(sql);+ order.push(sql);+ },+ transaction: async <T>(fn: (tx: BrainEngine) => Promise<T>) => fn(engine),getConfig: async (key: string) => config.get(key) ?? null,setConfig: async (key: string, value: string) => {order.push(`set:${key}`);@@ -44,6 +49,22 @@ function makeMockEngine(state: MockState): BrainEngine {return config.delete(key) ? 1 : 0;},} as unknown as BrainEngine;+ return engine;+}++/** The facts keyword index swap the command ends with (facts/fts-index.ts on a non-Postgres engine with no index yet): 8 statements. */+function expectFactsSwap(calls: string[], lang: string): void {+ expect(calls.map(sql => sql.trim().split(/\s+/).slice(0, 6).join(' '))).toEqual([+ 'SELECT i.indisvalid AS valid, pg_get_indexdef(i.indexrelid) AS',+ 'SELECT i.indisvalid AS valid, pg_get_indexdef(i.indexrelid) AS',+ 'SELECT to_regclass($1) IS NOT NULL AS',+ 'CREATE INDEX IF NOT EXISTS idx_facts_fts_next',+ 'DROP INDEX IF EXISTS idx_facts_fts_old',+ 'ALTER INDEX IF EXISTS idx_facts_fts RENAME',+ 'ALTER INDEX idx_facts_fts_next RENAME TO idx_facts_fts',+ 'DROP INDEX IF EXISTS idx_facts_fts_old',+ ]);+ expect(calls[3]).toContain(`USING gin (to_tsvector('${lang}'::regconfig`);}const MARKER = 'fts.reindex_in_progress';@@ -122,8 +143,8 @@ describe('runReindexSearchVector', () => {// 1 inventory + 2 CREATE + 2 backfill batches (mock returns no rows, so// the keyset loop terminates after the first batch per table) + the facts- // keyword index drop and rebuild (v236) = 7 calls- expect(state.calls.length).toBe(7);+ // keyword index swap (8) = 13 calls+ expect(state.calls.length).toBe(13);expect(state.calls[1]).toContain('CREATE OR REPLACE FUNCTION update_page_search_vector');expect(state.calls[1]).toContain("to_tsvector('pt_br'");expect(state.calls[2]).toContain('CREATE OR REPLACE FUNCTION update_chunk_search_vector');@@ -135,8 +156,7 @@ describe('runReindexSearchVector', () => {// proconfig): both recreated bodies pin search_path.expect(state.calls[1]).toContain('SET search_path = pg_catalog, public');expect(state.calls[2]).toContain('SET search_path = pg_catalog, public');- expect(state.calls[5]).toBe('DROP INDEX IF EXISTS idx_facts_fts');- expect(state.calls[6]).toContain("CREATE INDEX idx_facts_fts ON facts USING gin (to_tsvector('pt_br'::regconfig");+ expectFactsSwap(state.calls.slice(5), 'pt_br');});test('default english language still recreates + backfills (no shortcut here)', async () => {@@ -151,7 +171,7 @@ describe('runReindexSearchVector', () => {expect(result.status).toBe('ok');expect(result.language).toBe('english');- expect(state.calls.length).toBe(7);+ expect(state.calls.length).toBe(13);// Trigger recreates (calls 1, 2) and chunks backfill (call 4) embed the// language literal. Pages backfill (call 3) is UPDATE-to-self that@@ -161,7 +181,7 @@ describe('runReindexSearchVector', () => {expect(state.calls[2]).toContain("'english'");expect(state.calls[3]).toMatch(/UPDATE pages/);expect(state.calls[4]).toContain("'english'");- expect(state.calls[6]).toContain("to_tsvector('english'::regconfig");+ expectFactsSwap(state.calls.slice(5), 'english');});test('SQL injection attempt falls back to english', async () => {@@ -283,7 +303,7 @@ describe('runReindexSearchVector', () => {expect([...state.config!.keys()]).toEqual([]);// The existing executeRaw shape is untouched (config goes through// get/set/unsetConfig, not executeRaw).- expect(state.calls.length).toBe(7);+ expect(state.calls.length).toBe(13);});test('resumes the chunks backfill from the persisted checkpoint when the marker matches the language', async () => {