Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate-embeddings): build HNSW indexes after the re-embed as a durable, resumable phase (#5088)
garrytana66fbdbcf0f1
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 7d0e2a93f9..4d49487eb2 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); 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 `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/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.mdindex ae695bff25..0cd0da01c4 100644--- a/docs/guides/embedding-migration.md+++ b/docs/guides/embedding-migration.md@@ -118,7 +118,8 @@ even if a custom base URL still serves its old model.in one transaction. It rebuilds **all three dim-pinned text-embedding-spacecolumns** — `content_chunks.embedding`, `query_cache.embedding`, and`facts.embedding` — at the new width, preserving each column's type- (`vector` vs `halfvec`) and recreating its HNSW index. Missing any of the+ (`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 thethree leaves it silently broken: a narrow `query_cache.embedding` makesevery cache write and read fail *by design* (the cache swallows errors soit can never break search) for a permanent 0% hit rate, and a narrow@@ -137,6 +138,17 @@ even if a custom base URL still serves its old model.path as `embed --facts --stale`, including same-width model swaps andfacts-only brains. Expired, withdrawn, superseded and audit rows are notwork. 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,+ 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+ clears only after every recorded index exists and is valid.## Recovery@@ -308,7 +320,9 @@ pages fail to embed), re-run the **same command**: chunks already embedded onthe target are never re-embedded, the schema/config steps no-op, and the runcontinues where it stopped. An in-flight marker (`embedding_migration.state`in DB config) records the target; it is cleared only when the backlog drains-to zero. Re-running with a DIFFERENT `--to` target while a migration is in+to zero and the vector indexes are built. A kill during the index build+resumes with the indexes not yet built; on Postgres an INVALID index left by an+interrupted concurrent build is dropped and rebuilt. Re-running with a DIFFERENT `--to` target while a migration is inflight refuses and names both options: the exact resume command for theoriginal target, or the same command with `--retarget` to abandon itdeliberately (the marker records the superseded target in its history).diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex bf5c9ba1ef..a1ebb5a724 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -26,6 +26,8 @@ const MIGRATION_WAVE_TESTS = [export const E2E_TEST_MAP: Record<string, string[]> = {// Fix wave 8, Lane G: reindex auto-concurrency sizing (#5181)."src/commands/reindex.ts": ["test/e2e/reindex-auto-workers-5181.test.ts"],+ // Fix wave 8, Lane G: deferred ANN build after the embedding re-embed (#5088).+ "src/core/embedding-ann-build.ts": ["test/e2e/migrate-embeddings-ann-build-5088-postgres.test.ts", "test/e2e/migrate-embeddings-postgres.test.ts"],// Fix wave 4, Lane D: the apply-migrations orchestration lease (#5693), source deletes and// orphan bindings (#5732), and deactivate racing admission (#5455)."src/core/migration-orchestration-lock.ts": ["test/e2e/apply-migrations-orchestration-lock.test.ts"],diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c0667d7ee7..2118ec43c0 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 150src/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 retrysrc/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 1525 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+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/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 refreshsrc/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 readsrc/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.tsindex 2e90eb0dd0..2a1066428f 100644--- a/src/commands/migrate-embeddings.ts+++ b/src/commands/migrate-embeddings.ts@@ -27,7 +27,8 @@ import {} from '../core/embedding-migration.ts';import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';import { embedBackfillLockId, EMBED_BACKFILL_LOCK_TTL_MIN } from '../core/embed-backfill-lock.ts';-import { PGVECTOR_HNSW_VECTOR_MAX_DIMS } from '../core/vector-index.ts';+import { PGVECTOR_HNSW_VECTOR_MAX_DIMS, hnswIndexExpected } from '../core/vector-index.ts';+import { annIndexValidity, buildDeferredAnnIndexes, canonicalChunkAnnIndex, mergeDeferredAnnIndexes, parseDeferredAnnIndexes } from '../core/embedding-ann-build.ts';import { redactPgUrl } from '../core/url-redact.ts';import { runEmbedCore, type EmbedResult, type parsePaceArgs } from './embed.ts';import { parseMigrateEmbeddingsFlags } from '../core/embedding-migration-cli.ts';@@ -801,6 +802,8 @@ export async function executeMigrationFlow(reranker,};if (remaining === 0 && !embedResult.lock_lost) {+ // #5088: ANN indexes are built only now, after the drain, and before the marker clears.+ await buildMigrationAnnIndexes(engine, plan.to_dims, assertOwned);// Completion smoke check (D11): warn-don't-block self-retrieval. The// outcome is stamped into the completion marker (content-free) so// `--status` can READ it later without re-spending on live probes.@@ -855,6 +858,26 @@ export async function executeMigrationFlow(}}+/**+ * #5088: build the marker's deferred ANN indexes, plus the canonical chunk+ * index when the cap policy expects it and it is missing or INVALID. Each+ * built index leaves the marker in its own transaction, so a kill resumes.+ */+async function buildMigrationAnnIndexes(engine: BrainEngine, targetDims: number, assertOwned: (tx?: BrainEngine) => Promise<void>): Promise<void> {+ const canonical = canonicalChunkAnnIndex();+ 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),+ writePending: pending => engine.transaction(async tx => {+ await assertOwned(tx);+ const raw = await tx.getConfig(MIGRATION_STATE_KEY);+ if (raw) await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify({ ...JSON.parse(raw) as MigrationState, deferred_ann_indexes: pending }));+ }),+ assertOwned: () => assertOwned(),+ });+}+export interface RunMigrateEmbeddingsOpts {/** Test seams. */confirm?: (question: string) => Promise<boolean>;diff --git a/src/core/embedding-ann-build.ts b/src/core/embedding-ann-build.tsnew file mode 100644index 0000000000..c600566e7c--- /dev/null+++ b/src/core/embedding-ann-build.ts@@ -0,0 +1,126 @@+/**+ * #5088: deferred ANN (HNSW) index build for `gbrain migrate embeddings`.+ *+ * The schema transition drops `content_chunks.embedding` and used to recreate+ * its HNSW indexes before the bulk re-embed, so every vector write inserted+ * into a live HNSW graph (measured 4x slower on PGLite; the reporter's PGLite+ * run stalled). The transition now restores only the non-ANN dependent+ * indexes (the stale drain needs them) and records the HNSW definitions in+ * the migration marker (`deferred_ann_indexes`). This phase builds them after+ * 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.+ */+import type { BrainEngine } from './engine.ts';+import { chunkEmbeddingIndexSql, hnswIndexExpected } from './vector-index.ts';++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_ ().,:<>=!'-]+)?$/;++/**+ * Only HNSW definitions over `content_chunks.embedding` are accepted: the+ * marker lives in the config table, so a planted row must never become DDL.+ */+export function parseDeferredAnnIndexes(raw: unknown): 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;+ });+}++/** The canonical chunk ANN index definition, in pg_get_indexdef form. */+export function canonicalChunkAnnIndex(): DeferredAnnIndex {+ return { name: 'idx_chunks_embedding', def: chunkEmbeddingIndexSql(1).replace(/;\s*$/, '') };+}++export function mergeDeferredAnnIndexes(a: DeferredAnnIndex[], b: DeferredAnnIndex[]): DeferredAnnIndex[] {+ const byName = new Map<string, DeferredAnnIndex>();+ for (const entry of [...a, ...b]) byName.set(entry.name, entry);+ return [...byName.values()];+}++/** null = absent; otherwise whether the index is valid (an interrupted CONCURRENTLY build leaves it invalid). */+export async function annIndexValidity(engine: Pick<BrainEngine, 'executeRaw'>, name: string): Promise<boolean | null> {+ const rows = await engine.executeRaw<{ valid: boolean }>(+ `SELECT i.indisvalid AS valid FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid+ WHERE c.relname = $1 AND c.relkind = 'i'`, [name]);+ return rows.length ? rows[0]!.valid === true : null;+}++export interface AnnBuildResult { built: string[]; already_valid: string[]; skipped_over_cap: string[] }++/**+ * Build every pending ANN index recorded in the marker. `readPending` and+ * `writePending` keep this module independent of the marker's full shape.+ */+export async function buildDeferredAnnIndexes(+ engine: BrainEngine,+ io: {+ targetDims: number;+ readPending: () => Promise<DeferredAnnIndex[]>;+ writePending: (pending: DeferredAnnIndex[]) => Promise<void>;+ assertOwned?: () => Promise<void>;+ log?: (line: string) => void;+ monitorIntervalMs?: number;+ },+): Promise<AnnBuildResult> {+ 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) {+ const next = pending[0]!;+ index++;+ await io.assertOwned?.();+ const validity = await annIndexValidity(engine, next.name);+ if (validity === true) {+ result.already_valid.push(next.name);+ } else {+ log(`[migrate] ${ANN_BUILD_MESSAGE}: ${next.name} (${index}/${total})`);+ const started = Date.now();+ if (engine.kind === 'postgres') {+ await engine.withReservedConnection(async conn => {+ if (validity === false) await conn.executeRaw(`DROP INDEX CONCURRENTLY IF EXISTS ${next.name}`);+ const build = conn.executeRaw(next.def.replace(/^CREATE INDEX (?:IF NOT EXISTS )?/, 'CREATE INDEX CONCURRENTLY IF NOT EXISTS '));+ const timer = setInterval(() => {+ void engine.executeRaw<{ blocks_done: number; blocks_total: number; phase: string }>(+ `SELECT p.blocks_done, p.blocks_total, p.phase FROM pg_stat_progress_create_index p+ JOIN pg_class c ON c.oid = p.relid WHERE c.relname = 'content_chunks' LIMIT 1`)+ .then(rows => {+ const row = rows[0];+ const pct = row && Number(row.blocks_total) > 0 ? ` ${Math.round(100 * Number(row.blocks_done) / Number(row.blocks_total))}%` : '';+ log(`[migrate] building ${next.name}: ${Math.round((Date.now() - started) / 1000)}s${row ? ` (${row.phase}${pct})` : ''}`);+ })+ .catch(() => {});+ }, io.monitorIntervalMs ?? 30_000);+ try { await build; } finally { clearInterval(timer); }+ });+ } else {+ if (validity === false) await engine.executeRaw(`DROP INDEX IF EXISTS ${next.name}`);+ await engine.executeRaw(next.def.replace(/^CREATE INDEX (?:IF NOT EXISTS )?/, 'CREATE INDEX IF NOT EXISTS '));+ }+ if (await annIndexValidity(engine, next.name) !== true) {+ throw new Error(`vector index ${next.name} is not valid after its build; rerun the migration to rebuild it`);+ }+ log(`[migrate] vector index ${next.name} ready (${Math.round((Date.now() - started) / 1000)}s)`);+ result.built.push(next.name);+ }+ pending = pending.slice(1);+ await io.writePending(pending);+ }+ return result;+}diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.tsindex bd35265192..b55cda8922 100644--- a/src/core/embedding-migration.ts+++ b/src/core/embedding-migration.ts@@ -21,6 +21,7 @@ import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';import { countStaleFactEmbeddings } from './facts/embedding-identity.ts';import { prepareEmbeddingProjections } from './embedding-readiness.ts';import { assertRetainedEmbeddingRebuildability } from './embedding-migration-retention.ts';+import { annIndexValidity, canonicalChunkAnnIndex, mergeDeferredAnnIndexes, parseDeferredAnnIndexes, type DeferredAnnIndex } from './embedding-ann-build.ts';export interface EnvOverrideWarning {triggered: boolean;@@ -103,7 +104,7 @@ export function formatEnvOverrideWarning(w: EnvOverrideWarning): string {* IF NOT EXISTS on CREATE INDEX makes the operation safe to re-run during* `--resume`.*/-export async function runSchemaTransition(engine: BrainEngine, targetDim: number, assertOwned?: (tx: BrainEngine) => Promise<void>): Promise<void> {+export async function runSchemaTransition(engine: BrainEngine, targetDim: number, assertOwned?: (tx: BrainEngine) => Promise<void>): Promise<DeferredAnnIndex[]> {// Sink-side guard: targetDim is interpolated into DDL below. Every current// caller validates upstream, but a future programmatic caller passing an// unvalidated value must fail HERE, not become SQL in an admin DDL path@@ -111,7 +112,7 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: numberif (!Number.isInteger(targetDim) || targetDim <= 0 || targetDim > 100_000) {throw new Error(`runSchemaTransition: targetDim must be a positive integer, got ${String(targetDim)}`);}- await engine.transaction(async (tx) => {+ const deferred = await engine.transaction(async (tx) => {await assertOwned?.(tx);await assertRetainedEmbeddingRebuildability(tx, targetDim);// #4252: capture every index the DROP COLUMN below will cascade-drop.@@ -137,25 +138,24 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: numberawait tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding`);await tx.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);await tx.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding vector(${targetDim})`);- // HNSW cap policy lives in vector-index.ts (single home): pgvector caps- // `vector` HNSW at 2000 dims, so a valid 2048d target must skip the index- // (exact scans stay correct) instead of failing the whole DDL.- if (hnswIndexExpected('vector', targetDim)) {- await tx.executeRaw(- `CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)`,- );- }- // #4252: replay the captured dependent indexes the cascade dropped.- // idx_chunks_embedding is skipped (recreated above under the cap policy);- // any other HNSW def on the column obeys the same cap. Btree/partial defs- // are dim-agnostic and replay unconditionally.+ // #5088: HNSW indexes are built after the re-embed drain (embedding-ann-build.ts),+ // never here; the cap policy (vector-index.ts) leaves a 2048d target without one.+ // #4252: btree/partial dependents are dim-agnostic and the stale drain needs them now.+ const ann: DeferredAnnIndex[] = hnswIndexExpected('vector', targetDim) ? [canonicalChunkAnnIndex()] : [];for (const idx of dependentIndexes) {if (idx.name === 'idx_chunks_embedding') continue;- if (/USING hnsw/i.test(idx.def) && !hnswIndexExpected('vector', targetDim)) continue;+ if (/USING hnsw/i.test(idx.def)) {+ if (hnswIndexExpected('vector', targetDim)) ann.push(...parseDeferredAnnIndexes([idx]));+ 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@@ -195,6 +195,7 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: numberfor (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, targetDim);}+ return merged;});// Post-tx data hygiene: the column rebuild NULLed every vector but left@@ -234,6 +235,7 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number// Best-effort: the vector column is the source of truth; a failed clear// must never fail the migration.}+ return deferred;}/**@@ -344,6 +346,8 @@ export interface MigrationState {retargeted_at?: string;/** History of abandoned targets (newest last) for --status forensics. */superseded?: Array<{ to_model: string; to_dims: number; started_at: string }>;+ /** #5088: HNSW indexes dropped by the schema transition, built after the re-embed drain. */+ deferred_ann_indexes?: DeferredAnnIndex[];}/**@@ -1086,6 +1090,9 @@ export async function verifyMigrationComplete(}const marker = await readMigrationState(engine);+ const annPending = parseDeferredAnnIndexes(marker.state?.deferred_ann_indexes).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';if (marker.corrupt) {markerState = 'corrupt';@@ -1185,7 +1192,9 @@ export async function applyEmbeddingMigration(state.authorization_generation = prior.state.authorization_generation;if (prior.state.retargeted_at) state.retargeted_at = prior.state.retargeted_at;if (prior.state.superseded) state.superseded = prior.state.superseded;- } else if (prior.state) {+ }+ if (prior.state?.deferred_ann_indexes) state.deferred_ann_indexes = parseDeferredAnnIndexes(prior.state.deferred_ann_indexes);+ if (prior.state && !sameTarget) {// Retarget: record the abandoned target's identity.state.retargeted_at = now;state.superseded = [@@ -1208,7 +1217,7 @@ export async function applyEmbeddingMigration(const col = await readContentChunksEmbeddingDim(engine);await opts.assertOwned?.();if (schemaRebuildNeeded(col.dims, plan.to_dims)) {- await runSchemaTransition(engine, plan.to_dims, opts.assertOwned);+ state.deferred_ann_indexes = await runSchemaTransition(engine, plan.to_dims, opts.assertOwned);schemaTransitioned = true;} else {const pinned = await readDimPinnedWidths(engine);diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.tsindex b0142f0dd9..c1e1006a70 100644--- a/test/e2e/helpers.ts+++ b/test/e2e/helpers.ts@@ -16,6 +16,7 @@ import { parseMarkdown } from '../../src/core/markdown.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';import { configureGateway } from '../../src/core/ai/gateway.ts';import { runSchemaTransition } from '../../src/core/embedding-migration.ts';+import { buildDeferredAnnIndexes } from '../../src/core/embedding-ann-build.ts';import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';// Local opt-in configuration; container CI must not import developer credentials.@@ -180,7 +181,9 @@ export async function setupLegacyEmbeddingDB(): Promise<PostgresEngine> {throw new Error('Legacy embedding fixture requires all four text embedding columns');}if (columns.some(column => column.table_name !== 'takes' && Number(column.dims) !== dims)) {- await runSchemaTransition(target, dims);+ // #5088: the transition defers HNSW builds to the migration's build phase; the fixture builds them now.+ let pending = await runSchemaTransition(target, dims);+ await buildDeferredAnnIndexes(target, { targetDims: dims, readPending: async () => pending, writePending: async next => { pending = next; }, log: () => {} });}const takes = columns.find(column => column.table_name === 'takes')!;if (Number(takes.dims) !== dims) {diff --git a/test/e2e/migrate-embeddings-ann-build-5088-postgres.test.ts b/test/e2e/migrate-embeddings-ann-build-5088-postgres.test.tsnew file mode 100644index 0000000000..5c86f27d7c--- /dev/null+++ b/test/e2e/migrate-embeddings-ann-build-5088-postgres.test.ts@@ -0,0 +1,75 @@+/**+ * #5088 on Postgres: the deferred ANN build uses CREATE INDEX CONCURRENTLY on+ * a reserved connection, so writers keep going while it waits and builds, and+ * an INVALID index left by an interrupted concurrent build is dropped and+ * rebuilt on resume.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB, getConn } from './helpers.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { annIndexValidity, buildDeferredAnnIndexes, canonicalChunkAnnIndex, type DeferredAnnIndex } from '../../src/core/embedding-ann-build.ts';++const RUN = hasDatabase();+const describeE2E = RUN ? describe : describe.skip;+let engine: PostgresEngine;+let dims: number;++async function build(pending: DeferredAnnIndex[]) {+ let list = pending;+ const result = await buildDeferredAnnIndexes(engine, { targetDims: dims, readPending: async () => list, writePending: async next => { list = next; }, log: () => {}, monitorIntervalMs: 200 });+ return { result, left: list };+}++describeE2E('deferred ANN build on Postgres (#5088)', () => {+ beforeAll(async () => {+ engine = await setupDB();+ const [{ dim }] = await engine.executeRaw<{ dim: number }>(+ "SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0 AND NOT attisdropped");+ dims = Number(dim);+ for (const slug of ['notes/ann-a', 'notes/ann-b']) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `text ${slug}`, chunk_source: 'compiled_truth', token_count: 2 }]);+ }+ }, 60_000);+ afterAll(async () => {+ if (engine && await annIndexValidity(engine, 'idx_chunks_embedding') !== true) await build([canonicalChunkAnnIndex()]);+ await teardownDB();+ });++ test('an INVALID index from an interrupted concurrent build is dropped and rebuilt', async () => {+ await getConn().unsafe("UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'idx_chunks_embedding'::regclass");+ expect(await annIndexValidity(engine, 'idx_chunks_embedding')).toBe(false);+ const { result, left } = await build([canonicalChunkAnnIndex()]);+ expect(result.built).toEqual(['idx_chunks_embedding']);+ expect(left).toEqual([]);+ expect(await annIndexValidity(engine, 'idx_chunks_embedding')).toBe(true);+ }, 60_000);++ test('writers to content_chunks proceed while the build waits on an open writer transaction', async () => {+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');+ const holder = await getConn().reserve();+ try {+ await holder.unsafe('BEGIN');+ await holder.unsafe("UPDATE content_chunks SET token_count = token_count WHERE page_id = (SELECT id FROM pages WHERE slug = 'notes/ann-a')");+ const building = build([canonicalChunkAnnIndex()]);+ const deadline = Date.now() + 10_000;+ for (;;) {+ const waiting = await getConn().unsafe("SELECT 1 FROM pg_stat_activity WHERE query ILIKE 'CREATE INDEX CONCURRENTLY%idx_chunks_embedding%' AND state = 'active'");+ if (waiting.length) break;+ if (Date.now() > deadline) throw new Error('build never started');+ await Bun.sleep(50);+ }+ const write = engine.executeRaw("UPDATE content_chunks SET chunk_text = 'edited while indexing' WHERE page_id = (SELECT id FROM pages WHERE slug = 'notes/ann-b')");+ const outcome = await Promise.race([write.then(() => 'written'), Bun.sleep(5_000).then(() => 'blocked')]);+ expect(outcome).toBe('written');+ await holder.unsafe('COMMIT');+ const { result } = await building;+ expect(result.built).toEqual(['idx_chunks_embedding']);+ expect(await annIndexValidity(engine, 'idx_chunks_embedding')).toBe(true);+ } finally {+ await holder.unsafe('ROLLBACK').catch(() => {});+ holder.release();+ }+ }, 60_000);+});diff --git a/test/e2e/migrate-embeddings-postgres.test.ts b/test/e2e/migrate-embeddings-postgres.test.tsindex 4d583df206..98331d7c75 100644--- a/test/e2e/migrate-embeddings-postgres.test.ts+++ b/test/e2e/migrate-embeddings-postgres.test.ts@@ -32,6 +32,7 @@ import {MIGRATION_STATE_KEY,} from '../../src/core/embedding-migration.ts';import { runSchemaTransition } from '../../src/core/embedding-migration.ts';+import { annIndexValidity, buildDeferredAnnIndexes } from '../../src/core/embedding-ann-build.ts';import type { ChunkInput } from '../../src/core/types.ts';const RUN = hasDatabase();@@ -104,7 +105,8 @@ d('embedding migration (live Postgres + pgvector)', () => {resetGateway();// Restore the shared test DB's column width for subsequent e2e files.if (engine && originalDims && (await columnDims()) !== originalDims) {- await runSchemaTransition(engine, originalDims);+ let pending = await runSchemaTransition(engine, originalDims);+ await buildDeferredAnnIndexes(engine, { targetDims: originalDims, readPending: async () => pending, writePending: async next => { pending = next; }, log: () => {} });}await teardownDB();for (const [k, v] of Object.entries(savedEnv)) {@@ -202,11 +204,13 @@ d('embedding migration (live Postgres + pgvector)', () => {expect(await engine.getConfig('embedding_model')).toBe(toModel);expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeTruthy();- // HNSW index rebuilt inside the same transaction.+ // #5088: the HNSW index is NOT rebuilt inside the transition; the marker+ // records it and the build phase runs after the re-embed.const idx = await engine.executeRaw<{ indexname: string }>(`SELECT indexname FROM pg_indexes WHERE tablename = 'content_chunks' AND indexname = 'idx_chunks_embedding'`,);- expect(idx.length).toBe(1);+ 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']);// Re-embed through the real pipeline at the new width. NOTE: no// resetGateway() here — it would clear the installed fake transport.@@ -242,6 +246,11 @@ d('embedding migration (live Postgres + pgvector)', () => {);expect(rows.length).toBe(3);+ 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);+await completeEmbeddingMigration(engine, plan);expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();}, 120000);diff --git a/test/migrate-embeddings-ann-deferred-5088.serial.test.ts b/test/migrate-embeddings-ann-deferred-5088.serial.test.tsnew file mode 100644index 0000000000..26a1c5c2e7--- /dev/null+++ b/test/migrate-embeddings-ann-deferred-5088.serial.test.ts@@ -0,0 +1,214 @@+/**+ * #5088: `gbrain migrate embeddings` used to recreate the HNSW indexes inside+ * the schema transition, before the bulk re-embed, so every vector write went+ * into a live HNSW graph. The transition now restores only the non-ANN+ * dependents and records the HNSW definitions in the migration marker; they+ * are built after the drain, before the marker clears, and a run interrupted+ * at any point resumes without re-embedding finished rows.+ *+ * `.serial`: one temp GBRAIN_HOME and a fake embed transport for the file.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { runEmbedCore } from '../src/commands/embed.ts';+import { runMigrateEmbeddings } from '../src/commands/migrate-embeddings.ts';+import { MIGRATION_STATE_KEY } from '../src/core/embedding-migration.ts';+import { parseDeferredAnnIndexes } from '../src/core/embedding-ann-build.ts';++const FROM_DIMS = 1024;+const PAGES = ['page-1', 'page-2', 'page-3', 'page-4', 'page-5', 'page-6'];+const PROBE_TEXT = 'gbrain embedding migration probe';+const TARGET = 'openai:text-embedding-3-small';++let engine: PGLiteEngine;+let tmpHome: string;+const savedEnv: Record<string, string | undefined> = {};+let currentDims = FROM_DIMS;+let failTexts: string[] = [];+let embeddedTexts: string[] = [];+let probeAnn = false;++class ExitError extends Error { constructor(public code: number) { super(`exit ${code}`); } }++async function runMigrate(args: string[]): Promise<number> {+ try {+ await runMigrateEmbeddings(engine, args, { exit: (code: number): never => { throw new ExitError(code); } });+ throw new Error('runMigrateEmbeddings returned without exiting');+ } catch (e) {+ if (e instanceof ExitError) return e.code;+ throw e;+ }+}++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 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. */+let embedCalls: Array<{ values: string[]; ann: string[] }> = [];+function installTransport(): void {+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {+ if (values.some(v => failTexts.some(f => v.includes(f)))) throw new Error('fake transport: simulated failure');+ if (probeAnn && values.some(v => v !== PROBE_TEXT)) embedCalls.push({ values, ann: await annNames() });+ for (const v of values) if (v !== PROBE_TEXT) embeddedTexts.push(v);+ return { embeddings: values.map(() => new Array(currentDims).fill(0).map((_, i) => Math.sin(i) * 0.01 + 0.001)), usage: { tokens: values.length * 4 } } as never;+ });+}++/** ANN indexes seen by embed calls up to and including the one that embedded every listed page (the drain). */+function annSeenDuringDrain(pages: string[]): string[] {+ const seen: string[] = [];+ const remaining = new Set(pages);+ for (const call of embedCalls) {+ seen.push(...call.ann);+ for (const page of pages) if (call.values.some(v => v.includes(page))) remaining.delete(page);+ if (remaining.size === 0) return seen;+ }+ throw new Error(`drain never embedded ${[...remaining].join(', ')}`);+}++async function freshBrain(): Promise<void> {+ currentDims = FROM_DIMS;+ engine = new PGLiteEngine();+ await engine.connect({ embedding_dimensions: FROM_DIMS } as never);+ await engine.initSchema();+ for (const slug of PAGES) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\ncontent for ${slug}` });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `chunk text for ${slug}`, chunk_source: 'compiled_truth', token_count: 5 }]);+ }+ expect((await runEmbedCore(engine, { stale: true, quiet: true })).embedded).toBe(PAGES.length);+}++beforeAll(async () => {+ for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'OPENAI_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL']) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-ann-deferred-'));+ process.env.GBRAIN_HOME = tmpHome;+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'pglite', embedding_model: 'voyage:voyage-4', embedding_dimensions: FROM_DIMS,+ voyage_api_key: 'voyage-test-fake', openai_api_key: 'sk-test-fake',+ }, null, 2));+ resetGateway();+ configureGateway({ embedding_model: 'voyage:voyage-4', embedding_dimensions: FROM_DIMS, env: { VOYAGE_API_KEY: 'voyage-test-fake', OPENAI_API_KEY: 'sk-test-fake' } });+ installTransport();+ await freshBrain();+}, 120_000);++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ rmSync(tmpHome, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++describe('migrate embeddings builds ANN indexes after the re-embed (#5088)', () => {+ test('interrupted run: no HNSW index during the drain or after it; btree dependents restored; worklist in the marker', async () => {+ 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']);+ currentDims = 1536;+ failTexts = ['page-4', 'page-5'];+ embeddedTexts = [];+ probeAnn = true;+ const code = await runMigrate(['--to', TARGET, '--yes', '--max-cost-usd', '1']);+ probeAnn = false;+ expect(code).toBe(1);+ expect(embeddedTexts.length).toBe(PAGES.length - 2);+ 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 marker()).deferred_ann_indexes.map((i: { name: string }) => i.name).sort())+ .toEqual(['idx_chunks_embedding', 'idx_chunks_embedding_custom_l2']);+ }, 120_000);++ test('resume: re-embeds only the unfinished rows, then builds every recorded ANN index and clears the marker', async () => {+ failTexts = [];+ embeddedTexts = [];+ embedCalls = [];+ probeAnn = true;+ const code = await runMigrate(['--to', TARGET, '--yes', '--max-cost-usd', '1']);+ probeAnn = false;+ expect(code).toBe(0);+ // The two unfinished pages, plus the three completion smoke-check queries.+ expect(embeddedTexts.length).toBe(5);+ expect(embeddedTexts.join(' ')).toContain('page-4');+ 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']);+ 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();+ }, 120_000);++ test('a build that dies part-way keeps the finished index out of the worklist and the next run builds the rest', async () => {+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding_resume_l2');+ const { buildDeferredAnnIndexes } = await import('../src/core/embedding-ann-build.ts');+ let pending = parseDeferredAnnIndexes([+ { name: 'idx_chunks_embedding', def: 'CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)' },+ { name: 'idx_chunks_embedding_resume_l2', def: 'CREATE INDEX idx_chunks_embedding_resume_l2 ON public.content_chunks USING hnsw (embedding vector_l2_ops)' },+ ]);+ let killed = false;+ const dying = new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => {+ if (!killed && /resume_l2/.test(sql) && sql.startsWith('CREATE INDEX')) { killed = true; return Promise.reject(new Error('process killed mid-build')); }+ return target.executeRaw(sql, params as never);+ };+ return Reflect.get(target, prop, receiver);+ } }) as PGLiteEngine;+ const io = { targetDims: 1536, readPending: async () => pending, writePending: async (next: typeof pending) => { pending = next; }, log: () => {} };+ await expect(buildDeferredAnnIndexes(dying, io)).rejects.toThrow('process killed mid-build');+ expect(pending.map(p => p.name)).toEqual(['idx_chunks_embedding_resume_l2']);+ const resumed = await buildDeferredAnnIndexes(engine, io);+ expect(resumed.built).toEqual(['idx_chunks_embedding_resume_l2']);+ expect(pending).toEqual([]);+ expect(await annNames()).toContain('idx_chunks_embedding');+ expect(await annNames()).toContain('idx_chunks_embedding_resume_l2');+ }, 60_000);++ test('a 2,048-dimension target completes with no vector HNSW index (cap policy)', async () => {+ await engine.disconnect();+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'pglite', embedding_model: 'voyage:voyage-4', embedding_dimensions: FROM_DIMS,+ voyage_api_key: 'voyage-test-fake', openai_api_key: 'sk-test-fake',+ }, null, 2));+ resetGateway();+ configureGateway({ embedding_model: 'voyage:voyage-4', embedding_dimensions: FROM_DIMS, env: { VOYAGE_API_KEY: 'voyage-test-fake', OPENAI_API_KEY: 'sk-test-fake' } });+ installTransport();+ await freshBrain();+ currentDims = 2048;+ embeddedTexts = [];+ const code = await runMigrate(['--to', 'voyage:voyage-4-large', '--dim', '2048', '--yes', '--max-cost-usd', '1']);+ expect(code).toBe(0);+ expect(await annNames()).toEqual([]);+ expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();+ }, 120_000);+});++describe('deferred ANN worklist parsing (#5088)', () => {+ test('only HNSW definitions over content_chunks.embedding whose name matches are accepted', () => {+ 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]);+ 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 },+ { name: 'idx_pages', def: 'CREATE INDEX idx_pages ON pages USING hnsw (embedding vector_cosine_ops)' },+ 'not-an-object',+ ])).toEqual([]);+ });+});