Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(pglite): HNSW builds fit the WASM heap at 50k chunks
time-attackd7506034de83
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 4dd183f706..080509d28d 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -316,6 +316,23 @@ Details in INSTALL_FOR_AGENTS.md ("Engine preference for harness installs").- tsvector + ts_rank for full-text search (same as Postgres)- pg_trgm for fuzzy slug resolution (same as Postgres)+### PGLite vector index ceiling++PGLite runs Postgres inside WebAssembly, and pglite.wasm caps its memory at+2 GiB. pgvector holds the whole HNSW graph in `maintenance_work_mem` while it+builds, about 4.7 KB per 1,024-dimension chunk (1.16 GB at 250k chunks).+gbrain starts PGLite with `max_parallel_maintenance_workers=0` (PGLite has no+worker processes, and a planned parallel build reserved all of+`maintenance_work_mem` up front) and `max_wal_size=8GB` (a build WAL-logs its+whole index in one statement, and WAL past the automatic checkpoint trigger+wedges PGLite). The deferred ANN build (`gbrain migrate embeddings`) and+`gbrain reindex --vectors` size `maintenance_work_mem` to the graph+(`withHnswBuildMemory` in `src/core/vector-index.ts`): a 248,802-chunk build+takes about 11 minutes and a 1.9 GB index. A graph past the 1.5 GiB budget,+about 300k chunks at 1,024 dimensions, is refused before the build with+`pglite_vector_index_too_large`; vector search keeps working with exact scans,+and the fix is the read-only `gbrain migrate --to postgres --plan --json`.+**When to use PGLite vs Postgres:**| Factor | PGLite | PostgresEngine + Supabase |diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex b62593f8e3..2b3e0986f3 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-multimodal.ts` — `gbrain reindex --multimodal [--limit N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]`. Walks `content_chunks WHERE embedding_multimodal IS NULL`, batches via `embedMultimodalSafe` (partial-failure-aware), persists. Lock via `tryAcquireDbLock` (360min) so a concurrent autopilot embed phase can't race it. Cost prompt + Ctrl-C grace window in TTY. `GBRAIN_NO_REEMBED=1` bypass. Checkpoint at `~/.gbrain/reindex-multimodal-checkpoint.json` for resume. Auto-flip prompt at coverage=100% completion (TTY: interactive; non-TTY: stderr hint with a paste-ready command).-- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.+- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding; each rebuild runs inside `withHnswBuildMemory` (vector-index.ts), which sizes PGLite's `maintenance_work_mem` to the graph or refuses with `pglite_vector_index_too_large`. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 8722a424cb..a4d17c1044 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.-- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (real `bun add -g`-shaped hoisted layout).+- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the squatted npm name; README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`, plus `PGLITE_START_PARAMS` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout).- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The methods of every migrated storage domain (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh PGLite adapter over `this.db` per access, so transaction clones run inside their transaction; outside one, writes take the #5449 checkpoint guard); PGLite-only code stays under `src/core/pglite-engine/`. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; one implementation in `engine-sql/links.ts`) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying PGLITE_SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (see its entry) with the PGLite dialect hooks; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` (in `engine-sql/pages.ts`) bind `slug = ANY($1::text[])`, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); one SQL copy in `src/core/engine-sql/chunks.ts`, shared with PostgresEngine. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and the chunk upsert (`engine-sql/chunks.ts` `upsertChunksOnce`, behind `_upsertChunksOnce`), line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry. Outermost `transaction()` calls run `PgliteCheckpointGuard` (`src/core/pglite-engine/checkpoint-guard.ts`) before BEGIN: when WAL since the last redo point passes half the automatic-checkpoint distance (256 MB with the default 1 GB `max_wal_size`) it issues a top-level `CHECKPOINT` (each probe is queued with its own transaction, so concurrent callers see their predecessors' WAL, and the whole guarded operation is admitted once into the datastore's shutdown drain), because PGLite runs the automatic checkpoint inline inside the WAL write that crosses the trigger and that nested checkpoint spins forever (#5449/#5284). Savepoint transactions never checkpoint; the direct read-only vector-search transaction and other direct driver transactions are not guarded. A failed WAL probe proceeds with a once-per-process warning; a failed `CHECKPOINT` refuses before BEGIN with a `GBrainError` naming `gbrain pglite-repair`. Tests: `test/pglite-checkpoint-guard.test.ts`; the large-store harness `scripts/pglite-checkpoint-harness/supervisor.ts` (external supervisor, WAL-bound assertion) runs outside CI.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`); each storage feature lands as a parity twin in both engines (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, statement-cache and WAL-checkpoint lifecycle); refactor wave 1 moves shared SQL to `src/core/engine-sql/`.diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex 80cb94af4f..a99a87c513 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -39,4 +39,4 @@ union widening (`'person' | 'company'` → `string`), facts/eligibility.tspack-aware `ELIGIBLE_TYPES` wiring, and 3 doctor checks (schema_pack_coverage,schema_pack_writability, schema_pack_mutation_audit).-- `src/core/vector-index.ts` + `src/commands/doctor/checks/embedding-health.ts:embedding_column_registry` — shared pgvector HNSW eligibility policy. `hnswIndexExpected(columnType, dims)` derives the answer from the canonical `vector`/`halfvec` dimension caps already used by migration index generation. Doctor reports an HNSW-less active embedding column as a healthy exact-scan configuration when its declared width exceeds the applicable pgvector cap, and only emits the index repair recipe when an index is actually supported. Pinned at both cap boundaries by `test/vector-index-lifecycle.test.ts`. `readExistingEmbeddingShape` resolves the same relation as migration DDL and validates its actual type and width. Historical facts/query-cache replay uses that shape instead of extension/config defaults, preserving existing rows, vectors and compatible indexes; malformed existing shapes refuse before migration writes. `test/migration-vector-replay.test.ts` and its PostgreSQL wrapper pin both engines.+- `src/core/vector-index.ts` + `src/commands/doctor/checks/embedding-health.ts:embedding_column_registry` — shared pgvector HNSW eligibility policy. `hnswIndexExpected(columnType, dims)` derives the answer from the canonical `vector`/`halfvec` dimension caps already used by migration index generation. Doctor reports an HNSW-less active embedding column as a healthy exact-scan configuration when its declared width exceeds the applicable pgvector cap, and only emits the index repair recipe when an index is actually supported. Pinned at both cap boundaries by `test/vector-index-lifecycle.test.ts`. `readExistingEmbeddingShape` resolves the same relation as migration DDL and validates its actual type and width. Historical facts/query-cache replay uses that shape instead of extension/config defaults, preserving existing rows, vectors and compatible indexes; malformed existing shapes refuse before migration writes. `test/migration-vector-replay.test.ts` and its PostgreSQL wrapper pin both engines. `withHnswBuildMemory(engine, table, column, build)` wraps every PGLite HNSW build (the deferred ANN build in `embedding-ann-build.ts`, `gbrain reindex --vectors`): it sets `maintenance_work_mem` to `hnswBuildMemoryMb(rows, vectorBytes)` (stored vector plus 640 B per element, +10%, floor 64 MB) so pgvector keeps the whole graph in memory instead of falling back to on-disk inserts, resets it after, and refuses with `pglite_vector_index_too_large` (fix: the read-only `gbrain migrate --to postgres --plan --json`) before building when the graph passes `PGLITE_HNSW_GRAPH_BUDGET_BYTES` (1.5 GiB of pglite.wasm's 2 GiB heap, about 300k 1024-dim chunks). Postgres runs `build` unchanged. Measured and pinned by `test/pglite-hnsw-build.test.ts`; ceiling documented in `docs/ENGINES.md#pglite-vector-index-ceiling`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 0d5999383b..eb01803137 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1970,6 +1970,16 @@ More: [docs/guides/troubleshooting.md#persistence-write-stall](../../docs/guidesReasons: `timeout`, `live_serve`.+### pglite_vector_index_too_large++<a id="pglite_vector_index_too_large"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap. | pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans. | Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json Run: gbrain migrate --to postgres --plan --json | agent | `gbrain doctor --json` | 1 | no |++More: [docs/ENGINES.md#pglite-vector-index-ceiling](../../docs/ENGINES.md#pglite-vector-index-ceiling)+### plan_output_failed<a id="plan_output_failed"></a>diff --git a/src/commands/reindex-vectors.ts b/src/commands/reindex-vectors.tsindex 0ad6ce4c40..3b094f16ff 100644--- a/src/commands/reindex-vectors.ts+++ b/src/commands/reindex-vectors.ts@@ -11,6 +11,7 @@*/import type { BrainEngine } from '../core/engine.ts';import { quoteIdentifier } from '../core/search/embedding-column.ts';+import { withHnswBuildMemory } from '../core/vector-index.ts';export const REINDEX_VECTORS_COMMAND = 'gbrain reindex --vectors';@@ -22,13 +23,17 @@ export interface ReindexVectorsResult {export async function runReindexVectors(engine: BrainEngine, args: string[]): Promise<ReindexVectorsResult> {const dryRun = args.includes('--dry-run');- const indexes = (await engine.executeRaw<{ table: string; index: string }>(- `SELECT tablename AS table, indexname AS index FROM pg_indexes- WHERE schemaname = current_schema() AND indexdef ~* 'USING hnsw' ORDER BY tablename, indexname`));+ const rows = (await engine.executeRaw<{ table: string; index: string; column: string }>(+ `SELECT p.tablename AS table, p.indexname AS index, a.attname AS column FROM pg_indexes p+ JOIN pg_index i ON i.indexrelid = to_regclass(quote_ident(p.indexname))+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0]+ WHERE p.schemaname = current_schema() AND p.indexdef ~* 'USING hnsw' ORDER BY p.tablename, p.indexname`));+ const indexes = rows.map(({ table, index }) => ({ table, index }));let rebuilt = 0;- for (const { table, index } of dryRun ? [] : indexes) {+ for (const { table, index, column } of dryRun ? [] : rows) {if (!args.includes('--json')) process.stderr.write(`[reindex] rebuilding ${table}.${index}\n`);- await engine.executeRaw(`REINDEX INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}${quoteIdentifier(index)}`);+ await withHnswBuildMemory(engine, table, column, () =>+ engine.executeRaw(`REINDEX INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}${quoteIdentifier(index)}`));rebuilt++;}const result = { indexes, rebuilt, dry_run: dryRun };diff --git a/src/core/embedding-ann-build.ts b/src/core/embedding-ann-build.tsindex 9914091762..7798dc967a 100644--- a/src/core/embedding-ann-build.ts+++ b/src/core/embedding-ann-build.ts@@ -18,7 +18,7 @@* again at build time.*/import type { BrainEngine } from './engine.ts';-import { chunkEmbeddingIndexSql, hnswIndexExpected } from './vector-index.ts';+import { chunkEmbeddingIndexSql, hnswIndexExpected, withHnswBuildMemory } from './vector-index.ts';export interface DeferredAnnIndex { name: string; def: string }@@ -115,7 +115,8 @@ export async function buildDeferredAnnIndexes(});} 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 '));+ await withHnswBuildMemory(engine, ANN_DEF.exec(next.def)![2]!, 'embedding', () =>+ 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`);diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 781b924d61..23d5409da9 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -308,6 +308,7 @@ export const CODES = {permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },+ pglite_vector_index_too_large: { class: 'unavailable', summary: "A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap.", why: "pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans.", docs: 'docs/ENGINES.md#pglite-vector-index-ceiling', suggestion: 'Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json', fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists what moves to Postgres, the blockers and the exact run command.', requires_exclusive: false } },plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },diff --git a/src/core/pglite-embedded-assets.ts b/src/core/pglite-embedded-assets.tsindex 7c2b6bb811..eea62039b9 100644--- a/src/core/pglite-embedded-assets.ts+++ b/src/core/pglite-embedded-assets.ts@@ -50,7 +50,7 @@ import { createRequire } from 'node:module';import { tmpdir } from 'node:os';import { join, dirname } from 'node:path';import { createHash } from 'node:crypto';-import type { Extension } from '@electric-sql/pglite';+import { PGlite, type Extension } from '@electric-sql/pglite';/** The five on-disk asset paths PGLite's runtime needs, however they were found. */export interface PgliteAssetPaths {@@ -159,8 +159,29 @@ export interface EmbeddedPgliteOptions {initdbWasmModule: WebAssembly.Module;fsBundle: Blob;extensions: { vector: Extension; pg_trgm: Extension };+ startParams: string[];}+/**+ * Backend start parameters, appended to PGLite's defaults. PGLite is one+ * backend with no worker processes, yet a CREATE INDEX still plans parallel+ * workers from max_parallel_maintenance_workers, and pgvector's HNSW build+ * then reserves maintenance_work_mem as a shared area up front inside the+ * 2 GiB WASM heap that no worker ever uses. And WAL a single statement writes+ * past the automatic checkpoint trigger (max_wal_size / 1.9) wedges PGLite+ * (see pglite-engine/checkpoint-guard.ts, which checkpoints between+ * statements): an HNSW build WAL-logs its whole index in one statement, about+ * 2 GB at 250k 1024-dim chunks, past the 1 GB default's 539 MB trigger. 8 GB+ * puts the trigger at 4.3 GB, above the largest index the heap can build+ * (vector-index.ts PGLITE_HNSW_GRAPH_BUDGET_BYTES); the guard still+ * checkpoints at 256 MB between statements.+ */+export const PGLITE_START_PARAMS = [+ ...PGlite.defaultStartParams,+ '-c', 'max_parallel_maintenance_workers=0',+ '-c', 'max_wal_size=8GB',+];+let cached: Promise<EmbeddedPgliteOptions> | null = null;/**@@ -210,7 +231,7 @@ async function build(): Promise<EmbeddedPgliteOptions> {setup: async () => ({ bundlePath: pgTrgmBundle }),};- return { pgliteWasmModule, initdbWasmModule, fsBundle, extensions: { vector, pg_trgm } };+ return { pgliteWasmModule, initdbWasmModule, fsBundle, extensions: { vector, pg_trgm }, startParams: PGLITE_START_PARAMS };}/**diff --git a/src/core/vector-index.ts b/src/core/vector-index.tsindex cf9cfbb9ec..8a40f7a207 100644--- a/src/core/vector-index.ts+++ b/src/core/vector-index.ts@@ -15,6 +15,8 @@*/import type { BrainEngine } from './engine.ts';+import { opError } from './ops/contract.ts';+import { quoteIdentifier } from './search/embedding-column.ts';export const PGVECTOR_HNSW_VECTOR_MAX_DIMS = 2000;export const PGVECTOR_HNSW_HALFVEC_MAX_DIMS = 4000;@@ -61,6 +63,62 @@ export function applyChunkEmbeddingIndexPolicy(sql: string, dims: number): strinreturn sql.replaceAll(CHUNK_EMBEDDING_HNSW_INDEX, chunkEmbeddingIndexSql(dims));}+/**+ * PGLite HNSW builds. pglite.wasm caps its heap at 2 GiB; an open brain uses+ * about 184 MB of it (128 MB shared_buffers included) and pgvector keeps the+ * whole graph in maintenance_work_mem until it writes the index. PGLite's+ * 64 MB default holds about 14k 1024-dim elements; past that pgvector inserts+ * the rest one by one into the on-disk index (hours at 250k chunks). The graph+ * budget leaves the rest of the heap to the backend. Measured on 248,802+ * 1024-dim chunks: 4,669 B per element (565 B beyond the stored vector),+ * a 1,300 MB build peaked the heap at 1,320 MB, the index was 1.9 GB.+ */+export const PGLITE_HNSW_GRAPH_BUDGET_BYTES = 1536 * 1024 * 1024;+const HNSW_ELEMENT_OVERHEAD_BYTES = 640;+const PGLITE_DEFAULT_MAINTENANCE_WORK_MEM_MB = 64;++/** The maintenance_work_mem (MB) an in-memory build of `rows` elements of `vectorBytes` each needs, with 10% headroom. */+export function hnswBuildMemoryMb(rows: number, vectorBytes: number): number {+ const mb = Math.ceil(rows * (vectorBytes + HNSW_ELEMENT_OVERHEAD_BYTES) * 1.1 / (1024 * 1024));+ return Math.max(PGLITE_DEFAULT_MAINTENANCE_WORK_MEM_MB, mb);+}++/**+ * Run a PGLite HNSW build of `table.column` with maintenance_work_mem sized to+ * hold its whole graph, or refuse before building when that graph cannot fit+ * the WASM heap. Postgres runs `build` unchanged.+ */+export async function withHnswBuildMemory<T>(+ engine: Pick<BrainEngine, 'kind' | 'executeRaw'>, table: string, column: string, build: () => Promise<T>,+): Promise<T> {+ if (engine.kind !== 'pglite') return build();+ const [shape] = await engine.executeRaw<{ rows: number; type: string; dims: number }>(+ `SELECT (SELECT count(*) FROM ${quoteIdentifier(table)} WHERE ${quoteIdentifier(column)} IS NOT NULL)::int AS rows,+ t.typname AS type, a.atttypmod AS dims+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid+ WHERE a.attrelid = to_regclass($1) AND a.attname = $2`, [table, column]);+ if (!shape) return build();+ const vectorBytes = 8 + Math.max(0, Number(shape.dims)) * (shape.type === 'halfvec' ? 2 : 4);+ const mb = hnswBuildMemoryMb(Number(shape.rows), vectorBytes);+ if (mb * 1024 * 1024 > PGLITE_HNSW_GRAPH_BUDGET_BYTES) {+ const budgetMb = PGLITE_HNSW_GRAPH_BUDGET_BYTES / (1024 * 1024);+ throw opError('pglite_vector_index_too_large',+ `The vector index on ${table}.${column} needs about ${mb} MB to build and PGLite can give it ${budgetMb} MB; nothing was built.`,+ 'Vector search still works here with exact scans. Preview a move to Postgres, which builds this index without the limit: gbrain migrate --to postgres --plan --json',+ {+ why: `PGLite runs Postgres inside WebAssembly with a 2 GiB memory ceiling, and pgvector holds the whole HNSW graph in memory while it builds: ${shape.rows} vectors of ${shape.dims} dimensions do not fit.`,+ fix: {+ argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'The plan is read-only: it lists what moves to Postgres, the blockers and the exact run command.',+ user_message: `Your brain has ${shape.rows} embedded chunks, more than PGLite can index for vector search (search still works, unindexed). Should I preview a move to Postgres? Nothing changes yet.`,+ verify: { argv: ['gbrain', 'doctor', '--only', 'pglite_scale', '--json'] },+ },+ });+ }+ await engine.executeRaw(`SET maintenance_work_mem = '${mb}MB'`);+ try { return await build(); } finally { await engine.executeRaw('RESET maintenance_work_mem'); }+}+/** pgvector defaults hnsw.ef_search to 40; the GUC's hard ceiling is 1000. */export const HNSW_EF_SEARCH_DEFAULT = 40;export const HNSW_EF_SEARCH_MAX = 1000;diff --git a/test/pglite-hnsw-build.test.ts b/test/pglite-hnsw-build.test.tsnew file mode 100644index 0000000000..c6cde4661a--- /dev/null+++ b/test/pglite-hnsw-build.test.ts@@ -0,0 +1,81 @@+/**+ * PGLite HNSW builds fit the WASM heap (GBRA-75 wave 8). pglite.wasm caps its+ * heap at 2 GiB. Three things broke a 50k-page build (248,802 1024-dim+ * chunks): PGLite planned parallel maintenance workers it cannot start, so+ * pgvector reserved all of maintenance_work_mem up front (out of memory at+ * 1 GB); the build WAL-logged its 1.9 GB index in one statement, past the+ * 539 MB automatic checkpoint trigger, which wedges PGLite; and the 64 MB+ * default sent every element past about 14k to hours of on-disk inserts.+ * In-memory PGLite ($0).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { cliRenderContext, toAgentError } from '../src/core/agent-output.ts';+import { PGLITE_HNSW_GRAPH_BUDGET_BYTES, hnswBuildMemoryMb, withHnswBuildMemory } from '../src/core/vector-index.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.executeRaw('CREATE EXTENSION IF NOT EXISTS vector');+});+afterAll(async () => { await engine.disconnect(); });++test('PGLite starts with no parallel maintenance workers and the checkpoint trigger above any buildable index', async () => {+ const rows = await engine.executeRaw<{ name: string; setting: string }>(+ `SELECT name, setting FROM pg_settings WHERE name IN ('max_parallel_maintenance_workers', 'max_wal_size') ORDER BY name`);+ expect(rows).toEqual([+ { name: 'max_parallel_maintenance_workers', setting: '0' },+ { name: 'max_wal_size', setting: '8192' },+ ]);+ // The index is about 1.7x its graph on disk and its build WAL-logs the whole index; the trigger is max_wal_size / 1.9.+ expect(8192 * 1024 * 1024 / 1.9).toBeGreaterThan(PGLITE_HNSW_GRAPH_BUDGET_BYTES * 1.7);+});++test('the graph estimate covers the measured 50k build and keeps the PGLite default as its floor', () => {+ // Measured: 248,802 vector(1024) elements need 4,669 B each; a 1,300 MB build fit, 1,400 MB of parallel reserve did not.+ const mb = hnswBuildMemoryMb(248_802, 8 + 1024 * 4);+ expect(mb * 1024 * 1024).toBeGreaterThan(248_802 * 4_669);+ expect(mb * 1024 * 1024).toBeLessThanOrEqual(PGLITE_HNSW_GRAPH_BUDGET_BYTES);+ expect(hnswBuildMemoryMb(10, 8 + 1024 * 4)).toBe(64);+});++test('a PGLite build runs with maintenance_work_mem sized to its graph, then the session setting is restored', async () => {+ await engine.executeRaw('CREATE TABLE hx (id int, embedding vector(1))');+ await engine.executeRaw('INSERT INTO hx SELECT g, ARRAY[(g % 97) + 1]::vector FROM generate_series(1, 100000) g');+ const expected = hnswBuildMemoryMb(100_000, 8 + 4);+ expect(expected).toBeGreaterThan(64);+ const during = await withHnswBuildMemory(engine, 'hx', 'embedding', async () => {+ const [row] = await engine.executeRaw<{ maintenance_work_mem: string }>('SHOW maintenance_work_mem');+ await engine.executeRaw('CREATE INDEX hx_hnsw ON hx USING hnsw (embedding vector_l2_ops) WHERE id <= 500');+ return row!.maintenance_work_mem;+ });+ expect(during).toBe(`${expected}MB`);+ const [after] = await engine.executeRaw<{ maintenance_work_mem: string }>('SHOW maintenance_work_mem');+ expect(after!.maintenance_work_mem).toBe('64MB');+ const [built] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pg_class WHERE relname = 'hx_hnsw'`);+ expect(built!.n).toBe(1);+}, 30_000);++test('a graph past the heap budget is refused before the build with a read-only next step', async () => {+ let built = false;+ const big = { kind: 'pglite' as const, executeRaw: async () => [{ rows: 400_000, type: 'vector', dims: 1024 }] as never[] };+ const error = await withHnswBuildMemory(big, 'content_chunks', 'embedding', async () => { built = true; })+ .then(() => null, (e: unknown) => e);+ expect(built).toBe(false);+ expect(error).toBeInstanceOf(OperationError);+ const envelope = toAgentError(error, { transport: 'cli', command: 'reindex', render: cliRenderContext() });+ expect(envelope.code).toBe('pglite_vector_index_too_large');+ expect(envelope.fix?.argv).toEqual(['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json']);+ expect(envelope.fix?.next).toBe('run');+ expect(envelope.fix?.verify).toBeDefined();+});++test('Postgres builds run unchanged, with no sizing query', async () => {+ let queried = false;+ const pg = { kind: 'postgres' as const, executeRaw: async () => { queried = true; return [] as never[]; } };+ expect(await withHnswBuildMemory(pg, 'content_chunks', 'embedding', async () => 'built')).toBe('built');+ expect(queried).toBe(false);+});