Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): split CJK/Latin boundaries in the keyword index (#6370)
time-attacke1fd5664df5b
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex bab477331d..e0c1e30b2e 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -203,7 +203,7 @@ expansion (query: requested by default in every mode; --no-expand opts out;▼hybrid recall + fusion:├── vector (HNSW on chunk embeddings, per-page max-pool)- ├── keyword (BM25 via tsvector)+ ├── keyword (BM25 via tsvector; text indexed through gbrain_fts_input)├── title-phrase arm├── relational (typed-edge recall arm — relational queries only; 2-3│ relationship questions walk typed hop chains when@@ -253,6 +253,17 @@ limit slice → token-budget enforcement (per mode bundle)results (+ retrieval-confidence grade in query-op meta — crag.ts)```+**CJK/Latin boundaries in the keyword index (#6370).** Postgres' default+parser reads Han, Kana and Hangul as letters, so `升级PostgreSQL17后查询Redis7`+would be one lexeme and an ASCII query for `Redis7` would miss it. Every+indexing `to_tsvector` (both trigger functions, the page seal, the import seal+and `reindex-search-vector`) and the title arm's `websearch_to_tsquery` read+their text through `gbrain_fts_input()` (`src/core/fts-language.ts`), which+inserts a space at each CJK↔ASCII-letter/digit boundary. It is a no-op on text+without CJK, so non-CJK vectors are byte-identical. Pure-CJK queries still take+the raw-text CJK keyword path. The `fts_cjk_boundary` migration rebuilds only+the rows whose text holds such a boundary.+Per-arm fail-open has one deliberate exception: when BOTH lexical arms(`searchKeyword` + `searchTitles`) come back empty because of an ACCESS-classfailure (`isDbAccessFailure` in `src/core/pg-access-classify.ts` — the DBdiff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 752023dc5e..ee26ec1dba 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -18,7 +18,7 @@ src/commands/migrations/v0_32_2.ts 2 coordinator On a managed brain each entitysrc/commands/pages.ts 2 engine_guard Both engine references are dry-run previews (the --dry-run listing and the D6 consent count before a hard purge, #6114); the purge runs purgeDeletedPagesCoordinated, which is coordinated on managed brains.src/commands/reconcile-links.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/commands/reindex-aliases.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/commands/reindex-search-vector.ts 2 projection reindex-search-vector rewrites only pages.search_vector, through the seal's pageSearchVectorSql over the sanitized timeline and guarded by the knowledge revision it read (its read is an UPDATE-to-self of id); canonical fields are untouched and the managed writer guard passes search_vector-only updates.+src/core/search-vector-backfill.ts 2 projection backfillPageVectors (reindex-search-vector, the fts_cjk_boundary migration) rewrites only pages.search_vector, through the seal's pageSearchVectorSql over the sanitized timeline and guarded by the knowledge revision it read (its read is an UPDATE-to-self of id); canonical fields are untouched and the managed writer guard passes search_vector-only updates.src/commands/sources-set-path.ts 1 coordinator Managed rebind uses native exclusion, exact manifest verification and a retained source-incarnation receipt; unmanaged pointer repair remains explicit.src/commands/sources.ts 10 coordinator Managed add/archive/restore/remove/purge/reclone route through source lifecycle; remaining legacy canonical SQL stays fenced.src/commands/sync/deletes.ts 1 coordinator Managed Markdown sync routes to immutable page requests and an exhausted-cursor checkpoint; unsupported Git pull, code/image and connector paths refuse early. (Refactor wave 1: moved from src/commands/sync.ts.)diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex b3b7dac0ca..1dd51a0b5b 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 — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` and `content_chunks` 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`. 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`. 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-services-2.md b/docs/architecture/key-files/core-services-2.mdindex c9bc604d91..36738c4632 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -53,7 +53,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.-- `src/core/page-state/projections.ts` — `pageSearchVectorSql` is the one page keyword-vector expression (title weight A, sanitized timeline weight C) used by `sealPageTextProjection`, `sealImportedPage` and `reindex-search-vector`. Captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).+- `src/core/page-state/projections.ts` — `sealPageTextProjection` and `sealImportedPage` write the page keyword vector through `pageSearchVectorSql` (`fts-language.ts`: title weight A, sanitized timeline weight C, both through `gbrain_fts_input`), the same expression `search-vector-backfill.ts` uses. Captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 66569744d4..df42e0d6d5 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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 Postgres text-search configuration name used by FTS. `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). 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). 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/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex c470633f18..920721dc4c 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/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). 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.+- `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.- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as in-scope link endpoints grouped per entity page (ties break by slug in code-point order). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are three functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer).@@ -48,3 +48,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.- `src/core/worker-pool.ts` — (must-abort tags: `BUDGET_EXHAUSTED` and `SPEND_GROUP_REFUSED`, a job's spend-group refusal) Canonical sliding-pool + bounded-semaphore primitive (used by the `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts`'s `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem`, then the pool JOINS every worker (each finishes its current item) before rethrowing — the budget cap is a structural ceiling under concurrency and no worker is left running detached past the caller's catch. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.+- `src/core/search-vector-backfill.ts` — keyset-batched rebuilds of stored keyword vectors, shared by `reindex-search-vector` (every row) and the `fts_cjk_boundary` migration (an optional `where` limits it to rows with a CJK boundary). `backfillChunkVectors` recomputes `content_chunks.search_vector` with `chunkSearchVectorSql`; `backfillPageVectors` (#6374) reads each batch through an UPDATE-to-self of `id` (`RETURNING id, timeline, knowledge_revision`), sanitizes the timeline with `sanitizeRemoteBody` as the seal does, and writes `search_vector` through `pageSearchVectorSql` in one `UPDATE … FROM unnest(…)` guarded by the revision read (a page edited in between is skipped; its seal reindexes it). `BACKFILL_BATCH_SIZE` 5000 rows per statement, never one transaction; the cursor persists after every batch under `backfill.<checkpoint>.last_id` and the caller clears it. Pinned by `test/reindex-search-vector.serial.test.ts`, `test/reindex-search-vector-pages.serial.test.ts`, `test/fts-cjk-boundary.test.ts`. FTS write expressions (`src/core/fts-language.ts`, #6370): `FTS_INPUT_FUNCTION_SQL` (`gbrain_fts_input(text)`, IMMUTABLE STRICT PARALLEL SAFE, `search_path = pg_catalog`: two `regexp_replace` passes built from `CJK_SLUG_CHARS` that insert a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary; a byte-for-byte no-op without CJK, idempotent; spliced into src/schema.sql by `build:schema`), `FTS_CJK_BOUNDARY_REGEX` (the rows the `fts_cjk_boundary` migration rebuilds), `pageSearchVectorSql` (the sealed page vector used by the seal, the import seal and `search-vector-backfill.ts`), `chunkSearchVectorSql`, and `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (the two trigger functions under a language, byte-identical to src/schema.sql's for `english` so the blob replay after a migration leaves the catalog unchanged; used by `reindex-search-vector` and the migration). Every indexing `to_tsvector` reads through `gbrain_fts_input`; `applyFtsLanguagePolicy`'s `to_tsvector('english',` prefix rewrite still matches. Pinned by `test/fts-cjk-boundary.test.ts`, `test/fts-cjk-boundary-search.test.ts`, `test/e2e/fts-cjk-boundary-postgres.test.ts`.+- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.diff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex 8913f1d684..18c6f32f08 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -28,6 +28,7 @@ import { createHash } from 'node:crypto';import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { SOURCE_INGESTION_RECEIPTS_SCHEMA_SQL } from '../src/core/company-brain/receipt-schema.ts';+import { FTS_INPUT_FUNCTION_SQL } from '../src/core/fts-language.ts';import { FACT_WITHDRAWAL_SCHEMA_STATEMENTS } from '../src/core/facts/withdrawal-schema.ts';import { GRANT_AUDIT_SCHEMA_SQL } from '../src/core/grants/schema.ts';import { LEASE_TOKEN_SCHEMA_SQL } from '../src/core/lease-schema.ts';@@ -73,6 +74,7 @@ export interface Fragment {const persistenceSql = (statements: readonly string[]) => `${statements.join(';\n')};`;export const FRAGMENTS: readonly Fragment[] = [+ { source: 'src/core/fts-language.ts', expr: 'FTS_INPUT_FUNCTION_SQL', postgres: FTS_INPUT_FUNCTION_SQL, pglite: FTS_INPUT_FUNCTION_SQL },{ source: 'src/core/grants/schema.ts', expr: 'GRANT_AUDIT_SCHEMA_SQL', postgres: GRANT_AUDIT_SCHEMA_SQL, pglite: GRANT_AUDIT_SCHEMA_SQL },{source: 'src/core/facts/withdrawal-schema.ts',diff --git a/src/commands/reindex-search-vector.ts b/src/commands/reindex-search-vector.tsindex 8c8d5539b3..faab842cc8 100644--- a/src/commands/reindex-search-vector.ts+++ b/src/commands/reindex-search-vector.ts@@ -46,13 +46,12 @@*/import type { BrainEngine } from '../core/engine.ts';-import { getFtsLanguage, FTS_REINDEX_MARKER_KEY } 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 { consentGate } from '../core/consent-cli.ts';import type { ConsentEnv } from '../core/consent.ts';import { createProgress } from '../core/progress.ts';-import { pageSearchVectorSql } from '../core/page-state/projections.ts';-import { sanitizeRemoteBody } from '../core/remote-body.ts';+import { backfillChunkVectors, backfillPageVectors } from '../core/search-vector-backfill.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';export interface ReindexSearchVectorOpts {@@ -80,86 +79,9 @@ interface CountRow {chunks: number;}-/** Rows per backfill UPDATE. Keyset-batched so one statement never locks the whole table. */-export const BACKFILL_BATCH_SIZE = 5000;-/** Checkpoint names (→ `backfill.<name>.last_id`), one per backfilled table. */const CHECKPOINT_NAME = { pages: 'fts_pages', content_chunks: 'fts_content_chunks' } as const;-/**- * Keyset-batched UPDATE: applies `setClause` to `table` rows where- * search_vector IS NOT NULL, BACKFILL_BATCH_SIZE ids at a time, ticking- * the shared progress reporter after each batch. Terminates when a batch- * returns fewer rows than the batch size (or none). The cursor is persisted- * after every batch so a killed run loses at most one batch on resume.- */-async function batchedBackfill(- engine: BrainEngine,- table: 'content_chunks',- setClause: string,- tick: (n: number) => void-): Promise<void> {- const key = checkpointKey(CHECKPOINT_NAME[table]);- const saved = Number(await engine.getConfig(key));- let cursor = Number.isFinite(saved) && saved > 0 ? saved : 0;- for (;;) {- const rows = await engine.executeRaw<{ id: number }>(`- UPDATE ${table} SET ${setClause}- WHERE id IN (- SELECT id FROM ${table}- WHERE search_vector IS NOT NULL AND id > ${cursor}- ORDER BY id- LIMIT ${BACKFILL_BATCH_SIZE}- )- RETURNING id- `);- if (rows.length === 0) break;- tick(rows.length);- cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);- await engine.setConfig(key, String(cursor));- if (rows.length < BACKFILL_BATCH_SIZE) break;- }-}--/**- * #6374: page vectors rebuilt with the seal's own expression. The pages- * trigger fires only on `UPDATE OF title,timeline` and indexes the RAW- * timeline, so neither an UPDATE-to-self nor re-firing it is right. Each batch- * reads its rows through an UPDATE-to-self (row locks held for that statement- * only, never across the TypeScript sanitize), sanitizes the timeline exactly- * as the seal does, then writes `search_vector` guarded by the knowledge- * revision it read: a page edited in between is skipped, and its own seal- * indexes it under the new trigger language. The cursor is persisted after- * every batch, as for chunks.- */-async function backfillPageVectors(engine: BrainEngine, lang: string, tick: (n: number) => void): Promise<void> {- const key = checkpointKey(CHECKPOINT_NAME.pages);- const saved = Number(await engine.getConfig(key));- let cursor = Number.isFinite(saved) && saved > 0 ? saved : 0;- for (;;) {- const rows = await engine.executeRaw<{ id: number; timeline: string | null; knowledge_revision: string }>(`- UPDATE pages SET id = id- WHERE id IN (- SELECT id FROM pages- WHERE search_vector IS NOT NULL AND id > ${cursor}- ORDER BY id- LIMIT ${BACKFILL_BATCH_SIZE}- )- RETURNING id, timeline, knowledge_revision::text AS knowledge_revision- `);- if (rows.length === 0) break;- await engine.executeRaw(`- UPDATE pages p SET search_vector = ${pageSearchVectorSql('p.title', 'v.timeline', lang)}- FROM unnest($1::int[], $2::text[], $3::uuid[]) AS v(id, timeline, revision)- WHERE p.id = v.id AND p.knowledge_revision = v.revision- `, [rows.map(r => Number(r.id)), rows.map(r => sanitizeRemoteBody(r.timeline ?? '')), rows.map(r => r.knowledge_revision)]);- tick(rows.length);- cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);- await engine.setConfig(key, String(cursor));- if (rows.length < BACKFILL_BATCH_SIZE) break;- }-}-/*** Programmatic entrypoint — takes a typed opts object. Used by tests and* future internal callers. The CLI wrapper is `runReindexSearchVectorCli`@@ -223,48 +145,12 @@ export async function runReindexSearchVector(return { status: 'confirmation_required', language: lang, pagesUpdated: 0, chunksUpdated: 0, triggersRecreated: 0, durationMs: Date.now() - startedAt };}- // Recreate trigger functions. The strings are intentionally identical to- // the v124 migration body — keeping them in lockstep is the contract.- // `SET search_path = pg_catalog, public` mirrors the v120/#1647 hardening:- // CREATE OR REPLACE resets proconfig, so omitting it here would strip the- // hardening from every brain that runs this command.- //- // #2704: compiled_truth (the unbounded whole-page body) is deliberately- // NOT indexed here — it overflows Postgres's 1MB tsvector cap on large- // pages, and content_chunks.search_vector (populated separately, chunk-- // grain, well under the cap) is what searchKeyword() actually queries.- // See migrate.ts's v124 for the full rationale; keep this copy in sync.- const recreatePagesFn = `- CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS $fn$- DECLARE- timeline_text TEXT;- BEGIN- SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')- INTO timeline_text- FROM timeline_entries- WHERE page_id = NEW.id;-- NEW.search_vector :=- setweight(to_tsvector('${lang}', coalesce(NEW.title, '')), 'A') ||- setweight(to_tsvector('${lang}', coalesce(NEW.timeline, '')), 'C') ||- setweight(to_tsvector('${lang}', coalesce(timeline_text, '')), 'C');-- RETURN NEW;- END;- $fn$ LANGUAGE plpgsql;- `;-- const recreateChunksFn = `- CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS $fn$- BEGIN- NEW.search_vector :=- setweight(to_tsvector('${lang}', COALESCE(NEW.doc_comment, '')), 'A') ||- setweight(to_tsvector('${lang}', COALESCE(NEW.symbol_name_qualified, '')), 'A') ||- setweight(to_tsvector('${lang}', COALESCE(NEW.chunk_text, '')), 'B');- RETURN NEW;- END;- $fn$ LANGUAGE plpgsql;- `;+ // Trigger bodies come from the shared builders (fts-language.ts), the same+ // text the fts-cjk-boundary migration applies. gbrain_fts_input(), which+ // they call, exists on every brain: the schema blob and that migration+ // create it before any command runs.+ const recreatePagesFn = pageSearchVectorTriggerFnSql(lang);+ const recreateChunksFn = chunkSearchVectorTriggerFnSql(lang);// #4795: marker first (see the docblock). A prior run interrupted on the// SAME language resumes from its checkpoints; any other state starts over.@@ -297,22 +183,14 @@ export async function runReindexSearchVector(const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));// Backfill: pages through the seal's expression over the sanitized- // timeline (backfillPageVectors); content_chunks gets a direct vector- // compute since the column itself is what we want.+ // timeline; content_chunks gets a direct vector compute since the column+ // itself is what we want.progress.start('reindex_search_vector.pages', pagesCount);- await backfillPageVectors(engine, lang, n => progress.tick(n));+ await backfillPageVectors(engine, { lang, checkpoint: CHECKPOINT_NAME.pages, tick: n => progress.tick(n) });progress.finish();progress.start('reindex_search_vector.chunks', chunksCount);- await batchedBackfill(- engine,- 'content_chunks',- `search_vector =- setweight(to_tsvector('${lang}', COALESCE(doc_comment, '')), 'A') ||- setweight(to_tsvector('${lang}', COALESCE(symbol_name_qualified, '')), 'A') ||- setweight(to_tsvector('${lang}', COALESCE(chunk_text, '')), 'B')`,- n => progress.tick(n)- );+ await backfillChunkVectors(engine, { lang, checkpoint: CHECKPOINT_NAME.content_chunks, tick: n => progress.tick(n) });progress.finish();// Both backfills returned: the index is whole again under `lang`.diff --git a/src/core/fts-language.ts b/src/core/fts-language.tsindex 53e24d9442..087baddb25 100644--- a/src/core/fts-language.ts+++ b/src/core/fts-language.ts@@ -21,6 +21,8 @@* they must be literals or identifiers).*/+import { CJK_SLUG_CHARS } from './cjk.ts';+const VALID_CONFIG_NAME = /^[a-z][a-z0-9_]*$/;const DEFAULT_LANGUAGE = 'english';@@ -106,3 +108,84 @@ export function applyFtsLanguagePolicy(sql: string): string {// safe to interpolate as a SQL string literal.return sql.replaceAll(`to_tsvector('${DEFAULT_LANGUAGE}',`, `to_tsvector('${lang}',`);}++const CJK_CLASS = `[${CJK_SLUG_CHARS}]`;++/**+ * `gbrain_fts_input(text)`: the text every indexing `to_tsvector` and the+ * title query's `websearch_to_tsquery` read (#6370). Postgres' default parser+ * treats Han, Kana and Hangul as letters, so `升级PostgreSQL17后查询Redis7`+ * is one lexeme and keyword search for `Redis7` misses it. Two passes insert+ * a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary (two passes,+ * not lookbehind, so both engines run the same regex). A byte-for-byte no-op+ * on text without CJK, and idempotent. One copy of this DDL: the schema+ * build splices it into src/schema.sql and the fts-cjk-boundary migration+ * applies it.+ */+export const FTS_INPUT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog+AS $fn$+ SELECT regexp_replace(regexp_replace(t, '(${CJK_CLASS})([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])(${CJK_CLASS})', '\\1 \\2', 'g')+$fn$;`;++/** POSIX regex (SQL `~`) matching text that holds a CJK/ASCII-alnum boundary `gbrain_fts_input` splits. */+export const FTS_CJK_BOUNDARY_REGEX = `${CJK_CLASS}[A-Za-z0-9]|[A-Za-z0-9]${CJK_CLASS}`;++/**+ * The page keyword vector every sealed writer stores: the title (weight A) and+ * the SANITIZED timeline (weight C, bound by the caller; never the raw column,+ * which can hold private or withdrawn fence text). `title` and `timeline` are+ * SQL expressions. Shared by the seal, the import seal,+ * `reindex-search-vector` and the fts-cjk-boundary migration, so they cannot+ * drift.+ */+export function pageSearchVectorSql(title: string, timeline: string, lang: string = getFtsLanguage()): string {+ return `setweight(to_tsvector('${lang}',gbrain_fts_input(COALESCE(${title},''))),'A') || setweight(to_tsvector('${lang}',gbrain_fts_input(${timeline}::text)),'C')`;+}++/** The chunk keyword vector, over a row's own columns (`NEW.` in the trigger, bare in a backfill). */+export function chunkSearchVectorSql(lang: string, row = ''): string {+ return `setweight(to_tsvector('${lang}', gbrain_fts_input(COALESCE(${row}doc_comment, ''))), 'A') ||+ setweight(to_tsvector('${lang}', gbrain_fts_input(COALESCE(${row}symbol_name_qualified, ''))), 'A') ||+ setweight(to_tsvector('${lang}', gbrain_fts_input(COALESCE(${row}chunk_text, ''))), 'B')`;+}++/**+ * The two search_vector trigger functions under `lang`, for every runtime+ * rewrite (`reindex-search-vector`, the fts-cjk-boundary migration). Their+ * bodies are byte-identical to src/schema.sql's for 'english' (pinned by+ * test/fts-cjk-boundary.test.ts), so the blob replay that every boot runs+ * after a migration leaves the catalog unchanged. #2704: compiled_truth is not+ * indexed (it overflows the 1MB tsvector cap). `SET search_path = pg_catalog,+ * public` keeps the v120/#1647 hardening, which CREATE OR REPLACE would+ * otherwise reset.+ */+export function pageSearchVectorTriggerFnSql(lang: string): string {+ return `CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS $$+DECLARE+ timeline_text TEXT;+BEGIN+ SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')+ INTO timeline_text+ FROM timeline_entries+ WHERE page_id = NEW.id;++ NEW.search_vector :=+ setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||+ setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||+ setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;`;+}++export function chunkSearchVectorTriggerFnSql(lang: string): string {+ return `CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS $fn$+BEGIN+ NEW.search_vector :=+ ${chunkSearchVectorSql(lang, 'NEW.')};+ RETURN NEW;+END;+$fn$ LANGUAGE plpgsql;`;+}diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 143c685134..32b2097610 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -10,24 +10,13 @@ import { assertPageRevision, PageRevisionConflictError, type PageSnapshot } fromimport { sanitizeRemoteBody } from '../remote-body.ts';import { digest } from '../persistence/digest.ts';import { quoteIdentifier, resolveWriteColumnFromConfigRows, vectorCastSuffix } from '../search/embedding-column.ts';-import { getFtsLanguage } from '../fts-language.ts';+import { getFtsLanguage, pageSearchVectorSql } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { belowSafeChunkFence } from '../search/safe-chunks.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';-/**- * The page keyword vector every sealed writer stores: the title (weight A) and- * the SANITIZED timeline (weight C, bound by the caller; never the raw column,- * which can hold private or withdrawn fence text). `title` and `timeline` are- * SQL expressions. Shared by the seal, the import seal and- * `reindex-search-vector`, so the three cannot drift.- */-export function pageSearchVectorSql(title: string, timeline: string, lang: string = getFtsLanguage()): string {- return `setweight(to_tsvector('${lang}',COALESCE(${title},'')),'A') || setweight(to_tsvector('${lang}',${timeline}::text),'C')`;-}-/*** Complete the searchable snapshot only after its sanitized chunks are installed.* `guarded` is this transaction's own read of the page under its guard, whendiff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex e0e76a11e7..8d7681035a 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -186,6 +186,15 @@ CREATE INDEX IF NOT EXISTS idx_chunks_embedding_imageCREATE INDEX IF NOT EXISTS content_chunks_stale_idxON content_chunks(page_id, chunk_index) WHERE embedding IS NULL;+-- #6370: indexing and the title query read text through gbrain_fts_input(),+-- which splits CJK/ASCII-alnum boundaries (a no-op on text without CJK).+CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog+AS \$fn\$+ SELECT regexp_replace(regexp_replace(t, '([一-鿿-ゟ゠-ヿ가-])([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])([一-鿿-ゟ゠-ヿ가-])', '\\1 \\2', 'g')+\$fn\$;++CREATE TABLE IF NOT EXISTS links (id SERIAL PRIMARY KEY,from_page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,@@ -631,9 +640,9 @@ BEGINWHERE page_id = NEW.id;NEW.search_vector :=- setweight(to_tsvector('english', coalesce(NEW.title, '')), 'A') ||- setweight(to_tsvector('english', coalesce(NEW.timeline, '')), 'C') ||- setweight(to_tsvector('english', coalesce(timeline_text, '')), 'C');+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');RETURN NEW;END;diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex c815c62cb4..60c2a27649 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -391,6 +391,16 @@ CREATE INDEX IF NOT EXISTS idx_chunks_symbol_qualifiedCREATE INDEX IF NOT EXISTS content_chunks_stale_idxON content_chunks(page_id, chunk_index) WHERE embedding IS NULL;+-- #6370: indexing and the title query read text through gbrain_fts_input(),+-- which splits CJK/ASCII-alnum boundaries (a no-op on text without CJK).+-- BEGIN GENERATED from src/core/fts-language.ts (FTS_INPUT_FUNCTION_SQL). Edit that file, then run: bun run build:schema+CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog+AS \$fn\$+ SELECT regexp_replace(regexp_replace(t, '([一-鿿-ゟ゠-ヿ가-])([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])([一-鿿-ゟ゠-ヿ가-])', '\\1 \\2', 'g')+\$fn\$;+-- END GENERATED from src/core/fts-language.ts (FTS_INPUT_FUNCTION_SQL)+-- v0.20.0 Cathedral II: chunk-grain FTS trigger.-- Weight 'A' on doc_comment + symbol_name_qualified; weight 'B' on chunk_text.-- NL queries ("how do we handle errors") rank doc-comment hits above body text.@@ -399,9 +409,9 @@ CREATE INDEX IF NOT EXISTS content_chunks_stale_idxCREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS \$fn\$BEGINNEW.search_vector :=- setweight(to_tsvector('english', COALESCE(NEW.doc_comment, '')), 'A') ||- setweight(to_tsvector('english', COALESCE(NEW.symbol_name_qualified, '')), 'A') ||- setweight(to_tsvector('english', COALESCE(NEW.chunk_text, '')), 'B');+ setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.doc_comment, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.symbol_name_qualified, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.chunk_text, ''))), 'B');RETURN NEW;END;\$fn\$ LANGUAGE plpgsql;@@ -1139,17 +1149,15 @@ CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET searcDECLAREtimeline_text TEXT;BEGIN- -- Gather timeline_entries text for this pageSELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')INTO timeline_textFROM timeline_entriesWHERE page_id = NEW.id;- -- Build weighted tsvectorNEW.search_vector :=- setweight(to_tsvector('english', coalesce(NEW.title, '')), 'A') ||- setweight(to_tsvector('english', coalesce(NEW.timeline, '')), 'C') ||- setweight(to_tsvector('english', coalesce(timeline_text, '')), 'C');+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');RETURN NEW;END;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex f08dfeeffd..ed00b02841 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 231;+export const LATEST_SCHEMA_VERSION = 232;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 7b020ce4dc..5a9b7cf87c 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -232,6 +232,7 @@ import { v228 } from './v228-memory-purge.ts';import { v229 } from './v229-trust-allow-rules.ts';import { v230 } from './v230-trust-generation.ts';import { v231 } from './v231-fact-purge-lookup-indexes.ts';+import { v232 } from './v232-fts-cjk-boundary.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -462,4 +463,5 @@ export const MIGRATIONS: Migration[] = [v229,v230,v231,+ v232,];diff --git a/src/core/schema-migrations/v232-fts-cjk-boundary.ts b/src/core/schema-migrations/v232-fts-cjk-boundary.tsnew file mode 100644index 0000000000..04ab4a904b--- /dev/null+++ b/src/core/schema-migrations/v232-fts-cjk-boundary.ts@@ -0,0 +1,46 @@+import type { Migration } from './types.ts';+import { checkpointKey } from '../backfill-base.ts';+import {+ chunkSearchVectorTriggerFnSql,+ FTS_CJK_BOUNDARY_REGEX,+ FTS_INPUT_FUNCTION_SQL,+ getFtsLanguage,+ pageSearchVectorTriggerFnSql,+} from '../fts-language.ts';+import { backfillChunkVectors, backfillPageVectors } from '../search-vector-backfill.ts';+import { migrationNotice } from './helpers.ts';++const CHECKPOINT = { pages: 'fts_cjk_pages', chunks: 'fts_cjk_content_chunks' } as const;++// #6370: Latin/digit tokens glued to CJK text (`升级PostgreSQL17后查询Redis7`)+// were one lexeme, so keyword search for `Redis7` missed them. Creates+// gbrain_fts_input(), recreates both search_vector trigger functions on top of+// it under the configured language, then rebuilds only the rows whose text+// holds a CJK/ASCII-alnum boundary; every other row's vector is byte-identical+// under the helper and is not touched. Handler-only: the language must be a+// literal (getFtsLanguage() validates it). Batches run outside a transaction+// with a per-batch keyset checkpoint, so an interrupted run resumes where it+// stopped; re-running is safe (the rebuild is idempotent).+export const v232: Migration = {+ version: 232,+ name: 'fts_cjk_boundary',+ idempotent: true,+ sql: '',+ handler: async (engine) => {+ const lang = getFtsLanguage();+ await engine.executeRaw(FTS_INPUT_FUNCTION_SQL);+ await engine.executeRaw(pageSearchVectorTriggerFnSql(lang));+ await engine.executeRaw(chunkSearchVectorTriggerFnSql(lang));+ const re = `'${FTS_CJK_BOUNDARY_REGEX}'`;+ const pages = await backfillPageVectors(engine, {+ lang, checkpoint: CHECKPOINT.pages, where: `title ~ ${re} OR timeline ~ ${re}`,+ });+ const chunks = await backfillChunkVectors(engine, {+ lang, checkpoint: CHECKPOINT.chunks,+ where: `chunk_text ~ ${re} OR doc_comment ~ ${re} OR symbol_name_qualified ~ ${re}`,+ });+ await engine.unsetConfig(checkpointKey(CHECKPOINT.pages));+ await engine.unsetConfig(checkpointKey(CHECKPOINT.chunks));+ migrationNotice(` fts_cjk_boundary: keyword index splits CJK/Latin boundaries; rebuilt ${pages} page(s) and ${chunks} chunk(s) with CJK text (#6370)\n`);+ },+};diff --git a/src/core/search-vector-backfill.ts b/src/core/search-vector-backfill.tsnew file mode 100644index 0000000000..dd7de2b052--- /dev/null+++ b/src/core/search-vector-backfill.ts@@ -0,0 +1,93 @@+/**+ * Keyset-batched rebuilds of stored keyword vectors, shared by+ * `gbrain reindex-search-vector` (every row, new language) and the+ * fts-cjk-boundary migration (only rows whose text has a CJK/ASCII boundary).+ *+ * Each batch is its own statement, never one transaction: on Postgres one+ * transaction would hold every row lock for the whole run, and a hang inside+ * it would bank zero progress. The keyset cursor persists after every batch+ * under `backfill.<checkpoint>.last_id`, so a killed run resumes with at most+ * one batch redone; the caller clears it when the run finishes.+ */++import type { BrainEngine } from './engine.ts';+import { checkpointKey } from './backfill-base.ts';+import { chunkSearchVectorSql, pageSearchVectorSql } from './fts-language.ts';+import { sanitizeRemoteBody } from './remote-body.ts';++/** Rows per backfill UPDATE. Keyset-batched so one statement never locks the whole table. */+export const BACKFILL_BATCH_SIZE = 5000;++export interface VectorBackfillOpts {+ lang: string;+ /** Checkpoint name (→ `backfill.<name>.last_id`). */+ checkpoint: string;+ /** Extra SQL predicate over the table's own columns; only matching rows are rebuilt. */+ where?: string;+ tick?: (n: number) => void;+}++async function savedCursor(engine: BrainEngine, checkpoint: string): Promise<number> {+ const saved = Number(await engine.getConfig(checkpointKey(checkpoint)));+ return Number.isFinite(saved) && saved > 0 ? saved : 0;+}++const batchIds = (table: string, cursor: number, where: string | undefined) => `+ SELECT id FROM ${table}+ WHERE search_vector IS NOT NULL AND id > ${cursor}${where ? ` AND (${where})` : ''}+ ORDER BY id+ LIMIT ${BACKFILL_BATCH_SIZE}`;++/** Chunk vectors are a pure function of the row's own columns, so one UPDATE per batch. Returns rows rebuilt. */+export async function backfillChunkVectors(engine: BrainEngine, opts: VectorBackfillOpts): Promise<number> {+ let cursor = await savedCursor(engine, opts.checkpoint);+ let total = 0;+ for (;;) {+ const rows = await engine.executeRaw<{ id: number }>(`+ UPDATE content_chunks SET search_vector = ${chunkSearchVectorSql(opts.lang)}+ WHERE id IN (${batchIds('content_chunks', cursor, opts.where)})+ RETURNING id+ `);+ if (rows.length === 0) break;+ total += rows.length;+ opts.tick?.(rows.length);+ cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);+ await engine.setConfig(checkpointKey(opts.checkpoint), String(cursor));+ if (rows.length < BACKFILL_BATCH_SIZE) break;+ }+ return total;+}++/**+ * #6374: page vectors rebuilt with the seal's own expression. The pages+ * trigger fires only on `UPDATE OF title,timeline` and indexes the RAW+ * timeline, so neither an UPDATE-to-self nor re-firing it is right. Each batch+ * reads its rows through an UPDATE-to-self (row locks held for that statement+ * only, never across the TypeScript sanitize), sanitizes the timeline exactly+ * as the seal does, then writes `search_vector` guarded by the knowledge+ * revision it read: a page edited in between is skipped, and its own seal+ * indexes it under the current trigger. Returns rows read.+ */+export async function backfillPageVectors(engine: BrainEngine, opts: VectorBackfillOpts): Promise<number> {+ let cursor = await savedCursor(engine, opts.checkpoint);+ let total = 0;+ for (;;) {+ const rows = await engine.executeRaw<{ id: number; timeline: string | null; knowledge_revision: string }>(`+ UPDATE pages SET id = id+ WHERE id IN (${batchIds('pages', cursor, opts.where)})+ RETURNING id, timeline, knowledge_revision::text AS knowledge_revision+ `);+ if (rows.length === 0) break;+ await engine.executeRaw(`+ UPDATE pages p SET search_vector = ${pageSearchVectorSql('p.title', 'v.timeline', opts.lang)}+ FROM unnest($1::int[], $2::text[], $3::uuid[]) AS v(id, timeline, revision)+ WHERE p.id = v.id AND p.knowledge_revision = v.revision+ `, [rows.map(r => Number(r.id)), rows.map(r => sanitizeRemoteBody(r.timeline ?? '')), rows.map(r => r.knowledge_revision)]);+ total += rows.length;+ opts.tick?.(rows.length);+ cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);+ await engine.setConfig(checkpointKey(opts.checkpoint), String(cursor));+ if (rows.length < BACKFILL_BATCH_SIZE) break;+ }+ return total;+}diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.tsindex 9ba99852fa..ace3be0b08 100644--- a/src/core/search/title-statement.ts+++ b/src/core/search/title-statement.ts@@ -42,7 +42,7 @@ export interface SearchTitlesStatement {* `'acm':*A`). Lexemes are single-quoted with `''` escapes in that form.*/const WEIGHT_A_QUERY = (ftsLang: string): string =>- `regexp_replace(websearch_to_tsquery('${ftsLang}', $1)::text, '(''(?:[^'']|'''')*'')(?::(\\*))?', '\\1:\\2A', 'g')::tsquery`;+ `regexp_replace(websearch_to_tsquery('${ftsLang}', gbrain_fts_input($1))::text, '(''(?:[^'']|'''')*'')(?::(\\*))?', '\\1:\\2A', 'g')::tsquery`;export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undefined, dialect: SearchTitlesDialect): SearchTitlesStatement {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());@@ -57,7 +57,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();- const tsq = `websearch_to_tsquery('${ftsLang}', $1)`;+ const tsq = `websearch_to_tsquery('${ftsLang}', gbrain_fts_input($1))`;const matchSql = safeChunks ? `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}` : `p.search_vector @@ ${tsq}`;const rankSql = safeChunks ? `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})` : `ts_rank_cd(p.search_vector, ${tsq})`;diff --git a/src/schema.sql b/src/schema.sqlindex 61285eccc9..2207708473 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -387,6 +387,16 @@ CREATE INDEX IF NOT EXISTS idx_chunks_symbol_qualifiedCREATE INDEX IF NOT EXISTS content_chunks_stale_idxON content_chunks(page_id, chunk_index) WHERE embedding IS NULL;+-- #6370: indexing and the title query read text through gbrain_fts_input(),+-- which splits CJK/ASCII-alnum boundaries (a no-op on text without CJK).+-- BEGIN GENERATED from src/core/fts-language.ts (FTS_INPUT_FUNCTION_SQL). Edit that file, then run: bun run build:schema+CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog+AS $fn$+ SELECT regexp_replace(regexp_replace(t, '([一-鿿-ゟ゠-ヿ가-])([A-Za-z0-9])', '\1 \2', 'g'), '([A-Za-z0-9])([一-鿿-ゟ゠-ヿ가-])', '\1 \2', 'g')+$fn$;+-- END GENERATED from src/core/fts-language.ts (FTS_INPUT_FUNCTION_SQL)+-- v0.20.0 Cathedral II: chunk-grain FTS trigger.-- Weight 'A' on doc_comment + symbol_name_qualified; weight 'B' on chunk_text.-- NL queries ("how do we handle errors") rank doc-comment hits above body text.@@ -395,9 +405,9 @@ CREATE INDEX IF NOT EXISTS content_chunks_stale_idxCREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS $fn$BEGINNEW.search_vector :=- setweight(to_tsvector('english', COALESCE(NEW.doc_comment, '')), 'A') ||- setweight(to_tsvector('english', COALESCE(NEW.symbol_name_qualified, '')), 'A') ||- setweight(to_tsvector('english', COALESCE(NEW.chunk_text, '')), 'B');+ setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.doc_comment, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.symbol_name_qualified, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(COALESCE(NEW.chunk_text, ''))), 'B');RETURN NEW;END;$fn$ LANGUAGE plpgsql;@@ -1135,17 +1145,15 @@ CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET searcDECLAREtimeline_text TEXT;BEGIN- -- Gather timeline_entries text for this pageSELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')INTO timeline_textFROM timeline_entriesWHERE page_id = NEW.id;- -- Build weighted tsvectorNEW.search_vector :=- setweight(to_tsvector('english', coalesce(NEW.title, '')), 'A') ||- setweight(to_tsvector('english', coalesce(NEW.timeline, '')), 'C') ||- setweight(to_tsvector('english', coalesce(timeline_text, '')), 'C');+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||+ setweight(to_tsvector('english', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');RETURN NEW;END;diff --git a/test/e2e/fts-cjk-boundary-postgres.test.ts b/test/e2e/fts-cjk-boundary-postgres.test.tsnew file mode 100644index 0000000000..b219f33aac--- /dev/null+++ b/test/e2e/fts-cjk-boundary-postgres.test.ts@@ -0,0 +1,95 @@+/**+ * #6370 Postgres parity: gbrain_fts_input() returns the same text and the same+ * tsvectors on Postgres as on PGLite, the glued ASCII tokens are found by+ * keyword and title search, and the fts_cjk_boundary migration rebuilds only+ * rows with a CJK boundary. PGLite half: test/fts-cjk-boundary.test.ts and+ * test/fts-cjk-boundary-search.test.ts.+ *+ * Gated by DATABASE_URL; skips without a real Postgres.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { MIGRATIONS } from '../../src/core/migrate.ts';+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';++const describePg = hasDatabase() ? describe : describe.skip;++const SAMPLES = [+ '升级PostgreSQL17后查询Redis7无返回',+ 'サーバーはNginx1を使う',+ '서버는Caddy2를사용',+ '中a中a1中',+ 'plain english text with Redis7',+ 'café naïve — emoji 🚀 and e\u0301',+];++async function page(engine: BrainEngine, slug: string, title: string, body: string): Promise<void> {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: body });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));+}++async function tokenize(engine: BrainEngine): Promise<Array<{ input: string; vector: string }>> {+ const out: Array<{ input: string; vector: string }> = [];+ for (const t of SAMPLES) {+ const rows = await engine.executeRaw<{ input: string; vector: string }>(+ `SELECT gbrain_fts_input($1) AS input, to_tsvector('english', gbrain_fts_input($1))::text AS vector`, [t]);+ out.push(rows[0]!);+ }+ return out;+}++describePg('CJK/Latin FTS boundary on Postgres (#6370)', () => {+ let pg: BrainEngine;+ let lite: PGLiteEngine;++ beforeAll(async () => {+ pg = await setupDB();+ lite = new PGLiteEngine();+ await lite.connect({});+ await lite.initSchema();+ });+ afterAll(async () => {+ await lite.disconnect();+ await teardownDB();+ });+ beforeEach(async () => {+ await pg.executeRaw(`DELETE FROM pages WHERE slug LIKE 'cjk6370/%'`);+ });++ test('the helper and its tsvectors match PGLite byte-for-byte', async () => {+ expect(await tokenize(pg)).toEqual(await tokenize(lite));+ });++ test('glued ASCII tokens are found by keyword and title search', async () => {+ await page(pg, 'cjk6370/upgrade', '升级PostgreSQL17指南', '升级PostgreSQL17后查询Redis7无返回');+ await page(pg, 'cjk6370/other', 'Unrelated', 'Nothing relevant here.');+ const kw = await pg.searchKeyword('Redis7');+ expect(kw.map((r) => r.slug).filter((s) => s.startsWith('cjk6370/'))).toEqual(['cjk6370/upgrade']);+ const titles = await pg.searchTitles('PostgreSQL17');+ expect(titles.map((r) => r.slug).filter((s) => s.startsWith('cjk6370/'))).toEqual(['cjk6370/upgrade']);+ });++ test('the migration rebuilds only rows with a CJK boundary', async () => {+ const migration = MIGRATIONS.find((m) => m.name === 'fts_cjk_boundary')!;+ await page(pg, 'cjk6370/cjk', 'CJK', '升级PostgreSQL17后查询Redis7无返回');+ await page(pg, 'cjk6370/latin', 'Latin', 'Redis7 is the cache.');+ await pg.executeRaw(`ALTER TABLE content_chunks DISABLE TRIGGER chunk_search_vector_trigger`);+ try {+ await pg.executeRaw(`UPDATE content_chunks c SET search_vector = to_tsvector('english', c.chunk_text)+ FROM pages p WHERE p.id = c.page_id AND p.slug = 'cjk6370/cjk'`);+ await pg.executeRaw(`UPDATE content_chunks c SET search_vector = 'sentinel'::tsvector+ FROM pages p WHERE p.id = c.page_id AND p.slug = 'cjk6370/latin'`);+ } finally {+ await pg.executeRaw(`ALTER TABLE content_chunks ENABLE TRIGGER chunk_search_vector_trigger`);+ }+ const vectors = async (slug: string) => (await pg.executeRaw<{ v: string }>(+ `SELECT c.search_vector::text AS v FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = $1`, [slug])).map((r) => r.v).join(' ');+ expect(await vectors('cjk6370/cjk')).not.toContain("'redis7'");+ await migration.handler!(pg);+ expect(await vectors('cjk6370/cjk')).toContain("'redis7'");+ expect(await vectors('cjk6370/latin')).toBe("'sentinel'");+ });+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex e7d9d1a1a8..be574249f8 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -441,6 +441,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -459,8 +460,8 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1ff2515e6d6626907c0a6b660e31bd13bf51fe38fc585f7380d57ed746dc3357"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 15fbc1cf0c..f60716e308 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -441,6 +441,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -459,8 +460,8 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e099e8a1d30bd74b7632b6055d3edffe753c00c00183e3bdac34d28d23347555",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=078bd418f597924b56e631887aaddc41d98c231b3d27c6a52a9460b0ef252dd9"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e288cf3fefe11b32f9f006424f4a1b3b07b56d5fd5c3d1cd37ff1ce8658e1666"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 60b2f16aef..aafc143bd8 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -441,6 +441,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -459,8 +460,8 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1ff2515e6d6626907c0a6b660e31bd13bf51fe38fc585f7380d57ed746dc3357"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 4e015857cb..f2eb718e55 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -312,6 +312,7 @@"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",@@ -320,7 +321,7 @@"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex ce1e3a8e1f..ba4664b168 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -312,6 +312,7 @@"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",@@ -320,7 +321,7 @@"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3d98cc6ce4387bd742c1588ddc2133d036c7c5c8c64f7d33d1909c9ae44e73a6"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e288cf3fefe11b32f9f006424f4a1b3b07b56d5fd5c3d1cd37ff1ce8658e1666"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 7eee0739b9..fb3af29130 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -312,6 +312,7 @@"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",@@ -320,7 +321,7 @@"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 82a0863b19..0e3a4a5b17 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -321,6 +321,7 @@"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2",@@ -330,8 +331,8 @@"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d6d7b39b09838a1f5aaf343b766f21d2cd36f9d552a72b757266c779467f9647",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a05af543ed339a3e7b2b86b3eeddab6d6b14d9f2f52116dfe300caadde0dc230"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 5d4182e0ba..a036eba3de 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -444,6 +444,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -463,8 +464,8 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1ff2515e6d6626907c0a6b660e31bd13bf51fe38fc585f7380d57ed746dc3357"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 9d3449d39a..8754d0d6ec 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -444,6 +444,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -463,8 +464,8 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e099e8a1d30bd74b7632b6055d3edffe753c00c00183e3bdac34d28d23347555",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=078bd418f597924b56e631887aaddc41d98c231b3d27c6a52a9460b0ef252dd9"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e288cf3fefe11b32f9f006424f4a1b3b07b56d5fd5c3d1cd37ff1ce8658e1666"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 423b644953..2c3867a7cc 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -444,6 +444,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -463,8 +464,8 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1ff2515e6d6626907c0a6b660e31bd13bf51fe38fc585f7380d57ed746dc3357"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex b29dec1fcf..44d397114f 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 226,+ "count": 227,"gaps": [17,18,@@ -9,10 +9,13 @@],"helpers": {"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",+ "CHECKPOINT": "3c6ff909363c4ba1c9d730e748654ab90aa07549ddf4bf36b8f93c5f4ea3680b","FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c","FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1","FACT_RELINK_TABLE_SQL": "1fdde4b99d0077365274096f294be64a992961c7b4544af794224de238b03630","FACT_UNLINKED_INDEX_SQL": "87dcf23c3fa570d93bfb214b6bbb024faa9ff9bff227aa78869a29580be03298",+ "FTS_CJK_BOUNDARY_REGEX": "e8605bc0f2c6f3ecd2b451cbc8a4fe27ae0974d048f0bea655533cf37e0ff88d",+ "FTS_INPUT_FUNCTION_SQL": "d2f44fc1ef338ff7563c07659d938b743fedb20230948792c71068c022ec54c3","ISSUANCE_CLOCK_SLACK_SECONDS": "8f36c80392df6f9b9c754826289b63969d9d41ca8955213291e4413d614dce35","PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a","PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533",@@ -23,7 +26,11 @@"PERSISTENCE_SYNC_WATERMARK_INDEX": "93523954a30e8483717f07ec97a3e0cd062b15d8a60cc759281054b06c23bb40","TOKEN_TTL_MAX_SECONDS": "f4a45bec6ec0bacc859dc57732ceb76cec7eb72f242b5a6c89d47190d0525ab4","TOKEN_TTL_MIN_SECONDS": "441d8ce6bd21f753de90abd3013eaa9992a469ea60c590f1005533618199aa25",+ "backfillChunkVectors": "4c5dc231904e68639c19f5f5f3006b3b0fdac1cb33b82e94fa09dcb6da1822c9",+ "backfillPageVectors": "5c5d75ed6d65fde6cfe6ab1b30c1a0c5884976839f6026a149ef6a82c9b16e46","buildIndexOnline": "ed5378b90f24f7d662e02865cf73af4248e348002661f8fbfd8ee1087c60a3e5",+ "checkpointKey": "337ef776b18f428542093e27c4d570249d6a5856e5a17e4499d26a22877af34b",+ "chunkSearchVectorTriggerFnSql": "93ed4e29aa058949621b4198fe1ec317218f4b9ec0db0626ec6dc7001032047d","clampOAuthTokenTtls": "b1e94ea8f5b3c3870a56b0f6d00d0a274c2e9dcad912b828848aec250732645f","dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c","getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",@@ -32,6 +39,7 @@"migrateConnectorCheckpoints": "e0403022a56559556c82a9fa1e90d928f36e1d09c7db570e1d788a87d2dc9521","migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c","migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409",+ "pageSearchVectorTriggerFnSql": "c31a80562c8053479344d6060115a24854b1f419f6e09945f36b1403305f54e6","quietMigrationNotices": "4045c32034a8f46204dd5d89e185ff5c35e8073f560f14caa8b127f8a695957c","readExistingEmbeddingShape": "16d92d7cd52d8ebd7e89982f02e1bbdd8e8d08a6712a4ce57fbcf0952b7a6ca5","repairLegacyClientGrants": "c1dc6b1d0c4933c041583aa1c4eacaefc0ff0ae2a67f56cfad7534f87a5ab309",@@ -41,7 +49,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 231,+ "latest": 232,"records": [{"handler": {@@ -3455,6 +3463,35 @@"transaction": "absent","verify": "absent","version": 231+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "CHECKPOINT",+ "FTS_CJK_BOUNDARY_REGEX",+ "FTS_INPUT_FUNCTION_SQL",+ "backfillChunkVectors",+ "backfillPageVectors",+ "checkpointKey",+ "chunkSearchVectorTriggerFnSql",+ "getFtsLanguage",+ "migrationNotice",+ "pageSearchVectorTriggerFnSql",+ "quietMigrationNotices"+ ],+ "sha256": "b7a73381f45a5bcdc68e07cd45b2126cd7091140747f69e224abfc39bf8c7959"+ },+ "idempotent": true,+ "name": "fts_cjk_boundary",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 232}],"versions": [@@ -3683,7 +3720,8 @@228,229,230,- 231+ 231,+ 232]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 314db54966..5fe5498a66 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -441,6 +441,7 @@"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b",+ "gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",@@ -459,8 +460,8 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",- "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"+ "update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"},"grants": {"access_tokens": [diff --git a/test/fts-cjk-boundary-search.test.ts b/test/fts-cjk-boundary-search.test.tsnew file mode 100644index 0000000000..34f48bc94b--- /dev/null+++ b/test/fts-cjk-boundary-search.test.ts@@ -0,0 +1,60 @@+/**+ * #6370: Latin/digit tokens glued to CJK text are findable by keyword and+ * title search. Postgres' default parser reads Han/Kana/Hangul as letters, so+ * `升级PostgreSQL17后查询Redis7无返回` used to be one lexeme and an ASCII query+ * (`Redis7`) went through websearch_to_tsquery without matching it. Engine API+ * only, so the same file runs against a tree without the fix.+ *+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++async function page(slug: string, title: string, body: string): Promise<void> {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: body });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));+}++const slugs = (rows: Array<{ slug: string }>) => rows.map((r) => r.slug);++describe('CJK/Latin boundary in keyword search (#6370)', () => {+ test("the issue's chunk is found by the glued ASCII tokens", async () => {+ await page('notes/upgrade', 'Upgrade notes', '升级PostgreSQL17后查询Redis7无返回');+ await page('notes/other', 'Other', 'Nothing relevant here.');+ expect(slugs(await engine.searchKeyword('Redis7'))).toEqual(['notes/upgrade']);+ expect(slugs(await engine.searchKeyword('PostgreSQL17'))).toEqual(['notes/upgrade']);+ });++ test('Kana and Hangul boundaries split the same way', async () => {+ await page('notes/ja', 'Japanese', 'サーバーはNginx1を使う');+ await page('notes/ko', 'Korean', '서버는Caddy2를사용');+ expect(slugs(await engine.searchKeyword('Nginx1'))).toEqual(['notes/ja']);+ expect(slugs(await engine.searchKeyword('Caddy2'))).toEqual(['notes/ko']);+ });++ test('a glued title is found by its ASCII token and by the whole glued title', async () => {+ await page('guides/upgrade', '升级PostgreSQL17指南', 'Body text.');+ await page('guides/other', 'Unrelated title', 'Body text.');+ expect(slugs(await engine.searchTitles('PostgreSQL17'))).toEqual(['guides/upgrade']);+ expect(slugs(await engine.searchTitles('升级PostgreSQL17指南'))).toEqual(['guides/upgrade']);+ });++ test('pure Latin search is unchanged', async () => {+ await page('notes/latin', 'Redis notes', 'Redis7 is the cache we upgraded.');+ expect(slugs(await engine.searchKeyword('Redis7'))).toEqual(['notes/latin']);+ expect(slugs(await engine.searchTitles('Redis notes'))).toEqual(['notes/latin']);+ });+});diff --git a/test/fts-cjk-boundary.test.ts b/test/fts-cjk-boundary.test.tsnew file mode 100644index 0000000000..5f35cfe92d--- /dev/null+++ b/test/fts-cjk-boundary.test.ts@@ -0,0 +1,172 @@+/**+ * #6370: gbrain_fts_input() and the fts_cjk_boundary migration.+ *+ * - the helper splits CJK→ASCII-alnum and ASCII-alnum→CJK boundaries, is+ * idempotent, and returns text without CJK unchanged (so every non-CJK+ * tsvector is byte-identical);+ * - the runtime trigger builders are byte-identical to src/schema.sql's+ * bodies, so the blob replay after a migration leaves the catalog unchanged;+ * - the migration rebuilds only rows whose text holds a boundary, resumes from+ * its checkpoint and clears it.+ *+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MIGRATIONS } from '../src/core/migrate.ts';+import { checkpointKey } from '../src/core/backfill-base.ts';+import {+ chunkSearchVectorTriggerFnSql,+ FTS_INPUT_FUNCTION_SQL,+ pageSearchVectorTriggerFnSql,+} from '../src/core/fts-language.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++async function ftsInput(t: string): Promise<string> {+ const rows = await engine.executeRaw<{ v: string }>('SELECT gbrain_fts_input($1) AS v', [t]);+ return rows[0]!.v;+}++const NON_CJK = [+ 'plain english text with Redis7 and PostgreSQL17',+ 'café naïve résumé — accented Latin',+ 'e\u0301 combining acute, emoji 🚀🔥 and ZWJ 👩💻',+ 'Ελληνικά, кириллица, עברית, العربية, ไทย',+ 'punctuation: a-b_c.d/e:f (g) [h] {i} "j" \'k\'',+ '',+];++describe('gbrain_fts_input (#6370)', () => {+ test('splits both boundary directions in Han, Kana and Hangul', async () => {+ expect(await ftsInput('升级PostgreSQL17后查询Redis7无返回')).toBe('升级 PostgreSQL17 后查询 Redis7 无返回');+ expect(await ftsInput('サーバーはNginx1を使う')).toBe('サーバーは Nginx1 を使う');+ expect(await ftsInput('서버는Caddy2를사용')).toBe('서버는 Caddy2 를사용');+ expect(await ftsInput('中a中a1中')).toBe('中 a 中 a1 中');+ });++ test('is idempotent', async () => {+ for (const t of ['升级PostgreSQL17后查询Redis7无返回', '中a中a1中', 'a 中 b']) {+ const once = await ftsInput(t);+ expect(await ftsInput(once)).toBe(once);+ }+ });++ test('returns text without CJK unchanged, so its tsvector is byte-identical', async () => {+ for (const t of NON_CJK) {+ expect(await ftsInput(t)).toBe(t);+ const rows = await engine.executeRaw<{ a: string; b: string }>(+ `SELECT to_tsvector('english', $1)::text AS a, to_tsvector('english', gbrain_fts_input($1))::text AS b`, [t]);+ expect(rows[0]!.b).toBe(rows[0]!.a);+ }+ });++ test('CJK next to punctuation or spaces is left alone', async () => {+ for (const t of ['升级 PostgreSQL', '升级-PostgreSQL', '(Redis7)', '升级é']) expect(await ftsInput(t)).toBe(t);+ });++ test('is NULL-strict and declared immutable with a pinned search_path', async () => {+ const rows = await engine.executeRaw<{ n: string | null; vol: string; cfg: string[] }>(+ `SELECT gbrain_fts_input(NULL) AS n, p.provolatile AS vol, p.proconfig AS cfg FROM pg_proc p WHERE p.proname = 'gbrain_fts_input'`);+ expect(rows[0]!.n).toBeNull();+ expect(rows[0]!.vol).toBe('i');+ expect(rows[0]!.cfg).toEqual(['search_path=pg_catalog']);+ });+});++describe('one copy of the DDL', () => {+ const schema = readFileSync(new URL('../src/schema.sql', import.meta.url), 'utf8');++ test('src/schema.sql carries the helper and the runtime trigger bodies byte-for-byte', () => {+ expect(schema).toContain(FTS_INPUT_FUNCTION_SQL);+ expect(schema).toContain(pageSearchVectorTriggerFnSql('english'));+ expect(schema).toContain(chunkSearchVectorTriggerFnSql('english'));+ });++ test('every indexing to_tsvector in src/schema.sql reads through the helper', () => {+ const calls = schema.match(/to_tsvector\('english', [^\n]*/g) ?? [];+ expect(calls.length).toBeGreaterThan(0);+ for (const c of calls) expect(c).toMatch(/^to_tsvector\('english', gbrain_fts_input\(/);+ });+});++describe('fts_cjk_boundary migration (#6370)', () => {+ const migration = MIGRATIONS.find((m) => m.name === 'fts_cjk_boundary')!;+ const OLD_CHUNK = `setweight(to_tsvector('english', COALESCE(doc_comment, '')), 'A') || setweight(to_tsvector('english', COALESCE(symbol_name_qualified, '')), 'A') || setweight(to_tsvector('english', COALESCE(chunk_text, '')), 'B')`;++ async function page(slug: string, title: string, body: string): Promise<void> {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: body });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));+ }++ /** The pre-migration state: CJK rows tokenized without the helper, others carrying a sentinel. */+ async function seedPreMigration(): Promise<void> {+ await page('notes/cjk', '升级PostgreSQL17指南', '升级PostgreSQL17后查询Redis7无返回');+ await page('notes/latin', 'Latin title', 'Redis7 is the cache.');+ await engine.executeRaw(`ALTER TABLE content_chunks DISABLE TRIGGER chunk_search_vector_trigger`);+ await engine.executeRaw(`UPDATE content_chunks c SET search_vector = ${OLD_CHUNK.replaceAll('COALESCE(', 'COALESCE(c.')}+ FROM pages p WHERE p.id = c.page_id AND p.slug = 'notes/cjk'`);+ await engine.executeRaw(`UPDATE content_chunks c SET search_vector = 'sentinel'::tsvector FROM pages p WHERE p.id = c.page_id AND p.slug = 'notes/latin'`);+ await engine.executeRaw(`ALTER TABLE content_chunks ENABLE TRIGGER chunk_search_vector_trigger`);+ await engine.executeRaw(`UPDATE pages SET search_vector = setweight(to_tsvector('english', title), 'A') WHERE slug = 'notes/cjk'`);+ await engine.executeRaw(`UPDATE pages SET search_vector = 'sentinel'::tsvector WHERE slug = 'notes/latin'`);+ }++ const chunkVectors = async (slug: string) => (await engine.executeRaw<{ v: string }>(+ `SELECT c.search_vector::text AS v FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = $1 ORDER BY c.id`, [slug])).map((r) => r.v);+ const pageVector = async (slug: string) => (await engine.executeRaw<{ v: string }>(+ `SELECT search_vector::text AS v FROM pages WHERE slug = $1`, [slug]))[0]!.v;++ test('is registered handler-only and idempotent', () => {+ expect(migration).toBeDefined();+ expect(migration.sql).toBe('');+ expect(migration.idempotent).toBe(true);+ });++ test('rebuilds only rows with a CJK boundary and clears its checkpoints', async () => {+ await seedPreMigration();+ expect((await chunkVectors('notes/cjk')).join(' ')).not.toContain("'redis7'");+ await migration.handler!(engine);+ expect((await chunkVectors('notes/cjk')).join(' ')).toContain("'redis7'");+ expect(await pageVector('notes/cjk')).toContain("'postgresql17':2A");+ expect(await chunkVectors('notes/latin')).toEqual(["'sentinel'"]);+ expect(await pageVector('notes/latin')).toBe("'sentinel'");+ expect(await engine.getConfig(checkpointKey('fts_cjk_pages'))).toBeNull();+ expect(await engine.getConfig(checkpointKey('fts_cjk_content_chunks'))).toBeNull();+ });++ test('a rerun leaves the rebuilt vectors identical', async () => {+ await seedPreMigration();+ await migration.handler!(engine);+ const first = [await chunkVectors('notes/cjk'), await pageVector('notes/cjk')];+ await migration.handler!(engine);+ expect([await chunkVectors('notes/cjk'), await pageVector('notes/cjk')]).toEqual(first);+ });++ test('an interrupted run resumes after its saved cursor', async () => {+ await seedPreMigration();+ const [{ max }] = await engine.executeRaw<{ max: number }>(`SELECT max(c.id)::int AS max FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = 'notes/cjk'`);+ await engine.setConfig(checkpointKey('fts_cjk_content_chunks'), String(max));+ await migration.handler!(engine);+ expect((await chunkVectors('notes/cjk')).join(' ')).not.toContain("'redis7'");+ expect(await engine.getConfig(checkpointKey('fts_cjk_content_chunks'))).toBeNull();+ });++ test('the recreated trigger indexes new CJK writes through the helper', async () => {+ await migration.handler!(engine);+ await page('notes/new', 'New', 'サーバーはNginx1を使う');+ expect((await chunkVectors('notes/new')).join(' ')).toContain("'nginx1'");+ });+});diff --git a/test/pglite-upgrade-replay.test.ts b/test/pglite-upgrade-replay.test.tsindex 8edb8b0447..dd49346fcc 100644--- a/test/pglite-upgrade-replay.test.ts+++ b/test/pglite-upgrade-replay.test.ts@@ -80,7 +80,6 @@ const FRESH_GOLDEN = 'pglite-upgrade-replay/catalog-before-boot';const WHITESPACE_ONLY_FUNCTION_DRIFT = ['bump_page_generation_clock_fn()','bump_page_generation_fn()',- 'update_page_search_vector()',];/** The OID-churn list is already sorted identity keys; nothing volatile to scrub. */const recreatedObjectsNormalizer = defineNormalizer<string[]>('oid-churn-keys-v1', (keys) => [...keys].sort());