Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrate-embeddings): defer every rebuilt text column's HNSW index through one worklist, per-type cap at build time (#5088)

garrytancc9a872d082c
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 68df5ddcdc..2ecf6ce680 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/docker-postgres.ts` — gbrain's OWN docker Postgres container, the shared seam between the init ladder's docker rung and db-repair's `conn_refused` auto arm. `GBRAIN_PG_CONTAINER = 'gbrain-postgres'` / `GBRAIN_PG_IMAGE = 'pgvector/pgvector:pg16'` / `GBRAIN_PG_HOST_PORT = 5434` live HERE and only here (DRY — the init rung and the repair arm must never carry two string literals that can drift). Ownership contract: gbrain starts and reuses this container, NEVER stops or removes it, and never touches a container whose credentials it cannot recover via `inspectCredentials` (docker inspect → `POSTGRES_PASSWORD` env + the container's ORIGINAL port mapping — a freshly generated password can never match a surviving container; unrecoverable → refuse with a recreate-with-consent recipe). Hardening: the port binds loopback-only (`127.0.0.1:5434` — a single-machine brain store, not a network service); data lives on the named `gbrain-pgdata` volume so a container recreate never loses the brain; the password rides the child ENVIRONMENT (bare `-e POSTGRES_PASSWORD` — argv is world-readable in `ps`); `docker run` gets a 10-minute timeout (the first run synchronously pulls the image; 30s stays for cheap ps/inspect/start calls). `isGbrainDockerUrl` is the one predicate for "does this URL point at our container" (loopback + dedicated port — never error text).
-- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); the `content_chunks.embedding` HNSW indexes (canonical and custom) are NOT rebuilt in the transaction but recorded in the marker as `deferred_ann_indexes` and built after the re-embed drain by `src/core/embedding-ann-build.ts` (CONCURRENTLY on Postgres, INVALID remnants dropped first, one marker update per built index; config-planted definitions outside `content_chunks USING hnsw (embedding …)` are rejected), while btree/partial dependents replay immediately; `verifyMigrationComplete` blocks on pending or INVALID ANN indexes (`migrate-embeddings-ann-deferred-5088.serial.test.ts`); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.
+- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); the HNSW indexes of every rebuilt text-embedding column (`content_chunks` canonical and custom, plus each `TEXT_EMBEDDING_DIM_PINNED_TABLES` entry via `transitionDimPinnedColumn`'s returned definition; the allowed set is `DEFERRED_ANN_TABLES`) are NOT rebuilt in the transaction but recorded in the marker as `deferred_ann_indexes` (`recordDeferredAnnIndexes`) and built after the re-embed drain by `src/core/embedding-ann-build.ts` (CONCURRENTLY on Postgres, INVALID remnants dropped first, one marker update per built index; config-planted definitions outside `<deferred table> USING hnsw (embedding …)` are rejected), while btree/partial dependents replay immediately; `verifyMigrationComplete` blocks on pending or INVALID ANN indexes (`migrate-embeddings-ann-deferred-5088.serial.test.ts`); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.
- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup), and `TRAVERSE_WALK_ROW_CAP = 20000`, the bound on simple-path rows the recursive walks enumerate (`traverseGraph` and `traversePaths*`, both engines). The walk CTE is pulled through `LIMIT` so a dense hub stops enumerating, rows are deduped to `(page, depth)` before the edge join or the per-node link aggregation, and `traversePaths` stops recursing one layer early because the deepest layer only terminates edges. A capped walk sets `truncated` on `traversePathsDetailed`.
diff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.md
index 0cd0da01c4..d1958c6806 100644
--- a/docs/guides/embedding-migration.md
+++ b/docs/guides/embedding-migration.md
@@ -118,8 +118,8 @@ even if a custom base URL still serves its old model.
in one transaction. It rebuilds **all three dim-pinned text-embedding-space
columns** — `content_chunks.embedding`, `query_cache.embedding`, and
`facts.embedding` — at the new width, preserving each column's type
- (`vector` vs `halfvec`). The `query_cache` and `facts` HNSW indexes are
- recreated here; the chunk HNSW indexes are not (see step 7). Missing any of the
+ (`vector` vs `halfvec`). Their HNSW indexes are not recreated here (see
+ step 7). Missing any of the
three leaves it silently broken: a narrow `query_cache.embedding` makes
every cache write and read fail *by design* (the cache swallows errors so
it can never break search) for a permanent 0% hit rate, and a narrow
@@ -140,14 +140,14 @@ even if a custom base URL still serves its old model.
work. Unknown legacy fact provenance is never inferred from new config.
7. **Build the vector index.** The transition in step 5 restores the btree
and partial indexes on `content_chunks.embedding` right away (the re-embed
- needs them) and records every HNSW index it dropped, including custom ones,
- as `deferred_ann_indexes` in the migration marker. After the re-embed drains,
+ needs them) and records every HNSW index it dropped on the rebuilt text
+ columns, including custom ones, as `deferred_ann_indexes` in the migration marker. After the re-embed drains,
the run prints `building vector index after re-embed (search runs unindexed
until done)` with progress and builds them one at a time: Postgres uses
`CREATE INDEX CONCURRENTLY` (writes continue), PGLite a plain build. Loading
vectors before building the graph is several times faster than inserting
- each vector into a live HNSW index. A `vector` target above 2,000 dimensions
- gets no HNSW index (pgvector's cap; exact scans stay correct). The marker
+ each vector into a live HNSW index. A `vector` column above 2,000 dimensions
+ (`halfvec` above 4,000) gets no HNSW index (pgvector's cap; exact scans stay correct). The marker
clears only after every recorded index exists and is valid.
## Recovery
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c72d0869e1..a25eb7e7e6 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -32,7 +32,7 @@ src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 150
src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
src/commands/sources.ts 2013 ratchet +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
src/core/link-extraction.ts 2143 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note
-src/core/embedding-migration.ts 1534 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts)
+src/core/embedding-migration.ts 1544 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes)
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index 2a1066428f..d63e6b567e 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -18,6 +18,7 @@ import {
readMigrationStatus,
verifySearchRoundTrip,
MIGRATION_STATE_KEY,
+ DEFERRED_ANN_TABLES,
type EmbeddingMigrationPlan,
type MigrationVerify,
type MigrationState,
@@ -868,7 +869,7 @@ async function buildMigrationAnnIndexes(engine: BrainEngine, targetDims: number,
const expected = hnswIndexExpected('vector', targetDims) && await annIndexValidity(engine, canonical.name) !== true ? [canonical] : [];
await buildDeferredAnnIndexes(engine, {
targetDims,
- readPending: async () => mergeDeferredAnnIndexes(parseDeferredAnnIndexes((await readMigrationState(engine)).state?.deferred_ann_indexes), expected),
+ readPending: async () => mergeDeferredAnnIndexes(parseDeferredAnnIndexes((await readMigrationState(engine)).state?.deferred_ann_indexes, DEFERRED_ANN_TABLES), expected),
writePending: pending => engine.transaction(async tx => {
await assertOwned(tx);
const raw = await tx.getConfig(MIGRATION_STATE_KEY);
diff --git a/src/core/embedding-ann-build.ts b/src/core/embedding-ann-build.ts
index c600566e7c..bdb4049904 100644
--- a/src/core/embedding-ann-build.ts
+++ b/src/core/embedding-ann-build.ts
@@ -10,10 +10,12 @@
* the drain and before the marker clears, one at a time, removing each from
* the marker once it is valid, so a killed run resumes where it stopped.
*
- * Postgres builds with CREATE INDEX CONCURRENTLY on a reserved connection
- * (writes continue) and drops an INVALID remnant of an interrupted build
- * first; PGLite builds plainly. The cap policy (no `vector` HNSW above 2,000
- * dimensions) is applied again at build time.
+ * The worklist covers every text-embedding column the transition rebuilds
+ * (`content_chunks` plus the dim-pinned tables). Postgres builds with CREATE
+ * INDEX CONCURRENTLY on a reserved connection (writes continue) and drops an
+ * INVALID remnant of an interrupted build first; PGLite builds plainly. The
+ * per-type cap policy (vector 2,000, halfvec 4,000 dimensions) is applied
+ * again at build time.
*/
import type { BrainEngine } from './engine.ts';
import { chunkEmbeddingIndexSql, hnswIndexExpected } from './vector-index.ts';
@@ -22,17 +24,24 @@ export interface DeferredAnnIndex { name: string; def: string }
export const ANN_BUILD_MESSAGE = 'building vector index after re-embed (search runs unindexed until done)';
-const SAFE_ANN_DEF = /^CREATE INDEX (?:IF NOT EXISTS )?([a-z_][a-z0-9_]{0,62}) ON (?:public\.)?content_chunks USING hnsw \(embedding (?:vector|halfvec)_(?:cosine|l2|ip)_ops\)(?: WITH \([a-z_]+ ?= ?'?[0-9]+'?(?:, ?[a-z_]+ ?= ?'?[0-9]+'?)*\))?(?: WHERE [A-Za-z0-9_ ().,:<>=!'-]+)?$/;
+function safeAnnDef(tables: readonly string[]): RegExp {
+ const names = tables.filter(t => /^[a-z_][a-z0-9_]*$/.test(t)).join('|');
+ return new RegExp(`^CREATE INDEX (?:IF NOT EXISTS )?([a-z_][a-z0-9_]{0,62}) ON (?:public\\.)?(?:${names}) USING hnsw \\(embedding (?:vector|halfvec)_(?:cosine|l2|ip)_ops\\)`
+ + `(?: WITH \\([a-z_]+ ?= ?'?[0-9]+'?(?:, ?[a-z_]+ ?= ?'?[0-9]+'?)*\\))?(?: WHERE [A-Za-z0-9_ ().,:<>=!'-]+)?$`);
+}
/**
- * Only HNSW definitions over `content_chunks.embedding` are accepted: the
- * marker lives in the config table, so a planted row must never become DDL.
+ * Only HNSW definitions over the `embedding` column of the given tables are
+ * accepted: the marker lives in the config table, so a planted row must never
+ * become DDL. Whitespace is normalized.
*/
-export function parseDeferredAnnIndexes(raw: unknown): DeferredAnnIndex[] {
+export function parseDeferredAnnIndexes(raw: unknown, tables: readonly string[] = ['content_chunks']): DeferredAnnIndex[] {
if (!Array.isArray(raw)) return [];
- return raw.filter((entry): entry is DeferredAnnIndex => {
- if (!entry || typeof entry.name !== 'string' || typeof entry.def !== 'string' || entry.def.includes(';')) return false;
- return SAFE_ANN_DEF.exec(entry.def)?.[1] === entry.name;
+ const pattern = safeAnnDef(tables);
+ return raw.flatMap((entry): DeferredAnnIndex[] => {
+ if (!entry || typeof entry.name !== 'string' || typeof entry.def !== 'string' || entry.def.includes(';')) return [];
+ const def = entry.def.replace(/\s+/g, ' ').trim();
+ return pattern.exec(def)?.[1] === entry.name ? [{ name: entry.name, def }] : [];
});
}
@@ -75,11 +84,6 @@ export async function buildDeferredAnnIndexes(
const log = io.log ?? ((line: string) => process.stderr.write(line + '\n'));
const result: AnnBuildResult = { built: [], already_valid: [], skipped_over_cap: [] };
let pending = await io.readPending();
- if (!hnswIndexExpected('vector', io.targetDims)) {
- result.skipped_over_cap = pending.map(p => p.name);
- if (pending.length) await io.writePending([]);
- return result;
- }
const total = pending.length;
let index = 0;
while (pending.length > 0) {
@@ -87,7 +91,9 @@ export async function buildDeferredAnnIndexes(
index++;
await io.assertOwned?.();
const validity = await annIndexValidity(engine, next.name);
- if (validity === true) {
+ if (!hnswIndexExpected(/halfvec_/.test(next.def) ? 'halfvec' : 'vector', io.targetDims)) {
+ result.skipped_over_cap.push(next.name);
+ } else if (validity === true) {
result.already_valid.push(next.name);
} else {
log(`[migrate] ${ANN_BUILD_MESSAGE}: ${next.name} (${index}/${total})`);
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index b55cda8922..4d8258fb00 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -145,17 +145,13 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
for (const idx of dependentIndexes) {
if (idx.name === 'idx_chunks_embedding') continue;
if (/USING hnsw/i.test(idx.def)) {
- if (hnswIndexExpected('vector', targetDim)) ann.push(...parseDeferredAnnIndexes([idx]));
+ if (hnswIndexExpected('vector', targetDim)) ann.push(...parseDeferredAnnIndexes([idx], DEFERRED_ANN_TABLES));
continue;
}
await tx.executeRaw(
idx.def.replace(/^CREATE (UNIQUE )?INDEX /, 'CREATE $1INDEX IF NOT EXISTS '),
);
}
- const marker = await tx.getConfig(MIGRATION_STATE_KEY);
- const state = marker ? (() => { try { return JSON.parse(marker) as MigrationState; } catch { return null; } })() : null;
- const merged = mergeDeferredAnnIndexes(parseDeferredAnnIndexes(state?.deferred_ann_indexes), ann);
- if (state) await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify({ ...state, deferred_ann_indexes: merged }));
// Image/multimodal embedding column — rebuild index but preserve
// existing dimension. Only create it if it doesn't already exist
@@ -193,9 +189,10 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
// content_chunks.embedding. The image/multimodal columns above are the
// deliberate exception (separate models, independent dims).
for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
- await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, targetDim);
+ const deferredIndex = await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, targetDim);
+ if (deferredIndex) ann.push(deferredIndex);
}
- return merged;
+ return recordDeferredAnnIndexes(tx, ann);
});
// Post-tx data hygiene: the column rebuild NULLed every vector but left
@@ -290,7 +287,7 @@ async function transitionDimPinnedColumn(
indexName: string,
indexSql: (opclass: string) => string,
targetDim: number,
-): Promise<void> {
+): Promise<DeferredAnnIndex | null> {
// Same sink-side guard as runSchemaTransition (this runs standalone on the
// independent-repair path, not only under the guarded full transition).
if (!Number.isInteger(targetDim) || targetDim <= 0 || targetDim > 100_000) {
@@ -302,7 +299,7 @@ async function transitionDimPinnedColumn(
[table],
);
const udt = probe[0]?.udt_name;
- if (!udt) return; // table or column absent — nothing to transition
+ if (!udt) return null; // table or column absent — nothing to transition
// Preserve the column type; anything unexpected falls back to `vector`.
const columnType: 'vector' | 'halfvec' = udt.toLowerCase() === 'halfvec' ? 'halfvec' : 'vector';
const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
@@ -311,11 +308,21 @@ async function transitionDimPinnedColumn(
await tx.executeRaw(`ALTER TABLE ${table} DROP COLUMN IF EXISTS embedding`);
await tx.executeRaw(`ALTER TABLE ${table} ADD COLUMN embedding ${columnType}(${targetDim})`);
// HNSW has a per-type dimension ceiling; above it pgvector refuses the
- // index and exact scans remain the (correct, slower) path. Mirrors the
- // same guard in migrate.ts's original DDL.
- if (hnswIndexExpected(columnType, targetDim)) {
- await tx.executeRaw(indexSql(opclass));
- }
+ // index and exact scans remain the (correct, slower) path. #5088: the index
+ // is returned for the deferred build after the re-embed, not created here.
+ return hnswIndexExpected(columnType, targetDim) ? { name: indexName, def: indexSql(opclass).replace(/\s+/g, ' ').trim() } : null;
+}
+
+/** #5088: every text-embedding table whose HNSW index the transition defers. */
+export const DEFERRED_ANN_TABLES: readonly string[] = ['content_chunks', ...TEXT_EMBEDDING_DIM_PINNED_TABLES.map(t => t.table)];
+
+/** Merge deferred ANN indexes into the in-flight marker (same transaction as the drop) and return the full worklist. */
+async function recordDeferredAnnIndexes(tx: BrainEngine, ann: DeferredAnnIndex[]): Promise<DeferredAnnIndex[]> {
+ const marker = await tx.getConfig(MIGRATION_STATE_KEY);
+ const state = marker ? (() => { try { return JSON.parse(marker) as MigrationState; } catch { return null; } })() : null;
+ const merged = mergeDeferredAnnIndexes(parseDeferredAnnIndexes(state?.deferred_ann_indexes, DEFERRED_ANN_TABLES), ann);
+ if (state) await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify({ ...state, deferred_ann_indexes: merged }));
+ return merged;
}
/**
@@ -1090,7 +1097,7 @@ export async function verifyMigrationComplete(
}
const marker = await readMigrationState(engine);
- const annPending = parseDeferredAnnIndexes(marker.state?.deferred_ann_indexes).map(i => i.name);
+ const annPending = parseDeferredAnnIndexes(marker.state?.deferred_ann_indexes, DEFERRED_ANN_TABLES).map(i => i.name);
if (annPending.length) blockers.push(`vector index(es) ${annPending.join(', ')} not built yet (built after the re-embed; search runs unindexed until done)`);
if (await annIndexValidity(engine, 'idx_chunks_embedding') === false) blockers.push('vector index idx_chunks_embedding is INVALID (an interrupted build); a run rebuilds it');
let markerState: MigrationVerify['details']['marker'] = 'none';
@@ -1193,7 +1200,7 @@ export async function applyEmbeddingMigration(
if (prior.state.retargeted_at) state.retargeted_at = prior.state.retargeted_at;
if (prior.state.superseded) state.superseded = prior.state.superseded;
}
- if (prior.state?.deferred_ann_indexes) state.deferred_ann_indexes = parseDeferredAnnIndexes(prior.state.deferred_ann_indexes);
+ if (prior.state?.deferred_ann_indexes) state.deferred_ann_indexes = parseDeferredAnnIndexes(prior.state.deferred_ann_indexes, DEFERRED_ANN_TABLES);
if (prior.state && !sameTarget) {
// Retarget: record the abandoned target's identity.
state.retargeted_at = now;
@@ -1227,12 +1234,15 @@ export async function applyEmbeddingMigration(
await opts.assertOwned?.(tx);
await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
const stalePinned = (await readDimPinnedWidths(tx)).filter(p => schemaRebuildNeeded(p.dims, plan.to_dims));
+ const ann: DeferredAnnIndex[] = [];
for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
if (stalePinned.some((p) => p.table === t.table)) {
- await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, plan.to_dims);
+ const deferredIndex = await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, plan.to_dims);
+ if (deferredIndex) ann.push(deferredIndex);
pinnedRepaired.push(t.table);
}
}
+ state.deferred_ann_indexes = await recordDeferredAnnIndexes(tx, ann);
});
}
}
diff --git a/test/e2e/migrate-embeddings-postgres.test.ts b/test/e2e/migrate-embeddings-postgres.test.ts
index 98331d7c75..bc59515017 100644
--- a/test/e2e/migrate-embeddings-postgres.test.ts
+++ b/test/e2e/migrate-embeddings-postgres.test.ts
@@ -210,7 +210,8 @@ d('embedding migration (live Postgres + pgvector)', () => {
`SELECT indexname FROM pg_indexes WHERE tablename = 'content_chunks' AND indexname = 'idx_chunks_embedding'`,
);
expect(idx.length).toBe(0);
- expect(JSON.parse((await engine.getConfig(MIGRATION_STATE_KEY))!).deferred_ann_indexes.map((i: { name: string }) => i.name)).toEqual(['idx_chunks_embedding']);
+ expect(JSON.parse((await engine.getConfig(MIGRATION_STATE_KEY))!).deferred_ann_indexes.map((i: { name: string }) => i.name).sort())
+ .toEqual(['idx_chunks_embedding', 'idx_facts_embedding_hnsw', 'idx_query_cache_embedding_hnsw']);
// Re-embed through the real pipeline at the new width. NOTE: no
// resetGateway() here — it would clear the installed fake transport.
@@ -248,8 +249,8 @@ d('embedding migration (live Postgres + pgvector)', () => {
let pending = JSON.parse((await engine.getConfig(MIGRATION_STATE_KEY))!).deferred_ann_indexes;
const built = await buildDeferredAnnIndexes(engine, { targetDims, readPending: async () => pending, writePending: async next => { pending = next; }, log: () => {} });
- expect(built.built).toEqual(['idx_chunks_embedding']);
- expect(await annIndexValidity(engine, 'idx_chunks_embedding')).toBe(true);
+ expect(built.built.sort()).toEqual(['idx_chunks_embedding', 'idx_facts_embedding_hnsw', 'idx_query_cache_embedding_hnsw']);
+ for (const name of built.built) expect(await annIndexValidity(engine, name)).toBe(true);
await completeEmbeddingMigration(engine, plan);
expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();
diff --git a/test/migrate-embeddings-ann-deferred-5088.serial.test.ts b/test/migrate-embeddings-ann-deferred-5088.serial.test.ts
index 26a1c5c2e7..2dcc3477f6 100644
--- a/test/migrate-embeddings-ann-deferred-5088.serial.test.ts
+++ b/test/migrate-embeddings-ann-deferred-5088.serial.test.ts
@@ -49,6 +49,9 @@ async function chunkIndexes(): Promise<Array<{ name: string; def: string }>> {
return engine.executeRaw(`SELECT indexname AS name, indexdef AS def FROM pg_indexes WHERE tablename = 'content_chunks' ORDER BY indexname`);
}
const annNames = async () => (await chunkIndexes()).filter(i => /USING hnsw \(embedding /.test(i.def)).map(i => i.name);
+const PINNED_ANN = ['idx_facts_embedding_hnsw', 'idx_query_cache_embedding_hnsw'];
+const pinnedAnnNames = async () => (await engine.executeRaw<{ name: string }>(
+ "SELECT indexname AS name FROM pg_indexes WHERE indexname = ANY($1::text[]) ORDER BY indexname", [PINNED_ANN])).map(r => r.name);
const marker = async () => JSON.parse((await engine.getConfig(MIGRATION_STATE_KEY)) ?? 'null');
/** Records the ANN indexes present for each embed call, in order, so drain calls can be told from later smoke-check queries. */
@@ -120,6 +123,7 @@ describe('migrate embeddings builds ANN indexes after the re-embed (#5088)', ()
await engine.executeRaw('CREATE INDEX idx_chunks_embedding_custom_l2 ON content_chunks USING hnsw (embedding vector_l2_ops)');
await engine.executeRaw('CREATE INDEX idx_chunks_embedding_missing_example ON content_chunks (id) WHERE embedding IS NULL');
expect(await annNames()).toEqual(['idx_chunks_embedding', 'idx_chunks_embedding_custom_l2']);
+ expect(await pinnedAnnNames()).toEqual(PINNED_ANN);
currentDims = 1536;
failTexts = ['page-4', 'page-5'];
embeddedTexts = [];
@@ -131,8 +135,9 @@ describe('migrate embeddings builds ANN indexes after the re-embed (#5088)', ()
expect(annSeenDuringDrain(['page-1', 'page-2', 'page-3', 'page-6'])).toEqual([]);
expect(await annNames()).toEqual([]);
expect((await chunkIndexes()).map(i => i.name)).toContain('idx_chunks_embedding_missing_example');
+ expect(await pinnedAnnNames()).toEqual([]);
expect((await marker()).deferred_ann_indexes.map((i: { name: string }) => i.name).sort())
- .toEqual(['idx_chunks_embedding', 'idx_chunks_embedding_custom_l2']);
+ .toEqual(['idx_chunks_embedding', 'idx_chunks_embedding_custom_l2', ...PINNED_ANN]);
}, 120_000);
test('resume: re-embeds only the unfinished rows, then builds every recorded ANN index and clears the marker', async () => {
@@ -149,6 +154,7 @@ describe('migrate embeddings builds ANN indexes after the re-embed (#5088)', ()
expect(embeddedTexts.join(' ')).toContain('page-5');
expect(annSeenDuringDrain(['page-4', 'page-5'])).toEqual([]);
expect(await annNames()).toEqual(['idx_chunks_embedding', 'idx_chunks_embedding_custom_l2']);
+ expect(await pinnedAnnNames()).toEqual(PINNED_ANN);
const custom = (await chunkIndexes()).find(i => i.name === 'idx_chunks_embedding_custom_l2')!;
expect(custom.def).toContain('vector_l2_ops');
expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();
@@ -204,6 +210,10 @@ describe('deferred ANN worklist parsing (#5088)', () => {
const ok = { name: 'idx_chunks_embedding', def: 'CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)' };
const partial = { name: 'idx_x', def: "CREATE INDEX idx_x ON public.content_chunks USING hnsw (embedding vector_l2_ops) WITH (m='16') WHERE (embedding IS NOT NULL)" };
expect(parseDeferredAnnIndexes([ok, partial])).toEqual([ok, partial]);
+ const facts = { name: 'idx_facts_embedding_hnsw', def: 'CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw\n ON facts USING hnsw (embedding halfvec_cosine_ops)\n WHERE embedding IS NOT NULL AND expired_at IS NULL' };
+ expect(parseDeferredAnnIndexes([facts])).toEqual([]);
+ expect(parseDeferredAnnIndexes([facts], ['content_chunks', 'facts'])[0]!.def)
+ .toBe('CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE embedding IS NOT NULL AND expired_at IS NULL');
expect(parseDeferredAnnIndexes([
{ name: 'idx_chunks_embedding', def: 'CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops); DROP TABLE pages' },
{ name: 'other', def: ok.def },