Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(pglite): cut cold-start overhead for one-shot reads

time-attack6d36a38077bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 322c7a9c7f..0e012b6a39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,33 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.213.0] - 2026-10-13
+
+**Shell-out reads on a local PGLite brain start about 110 ms faster.** Every `gbrain call get_page`, `gbrain get`, `gbrain list` or `gbrain search` on a local brain used to spend part of its startup preparing database features the command never used: a 128 MB page cache that one read never fills, and the vector and fuzzy-match extensions loaded before the first query whether or not the command touched them. One-shot reads now open with a smaller cache, the extensions load the first time a query needs them, and `gbrain call` starts preparing the database engine while the rest of the command loads, as `get` and `list` already did. Results are identical. `gbrain serve`, imports and every write keep the full cache.
+
+| Command (local PGLite brain, fresh process) | 85 pages, before | after | 5,000 pages, before | after |
+|---|---|---|---|---|
+| `gbrain call get_page` | 714–731 ms | 598–607 ms | 716–722 ms | 601–606 ms |
+| `gbrain list` | 575–616 ms | 514–533 ms | 597–605 ms | 507–516 ms |
+| MCP stdio start + first `get_page` | 863–865 ms | 840–894 ms | 865–874 ms | 857–861 ms |
+
+Medians (p50) of two runs of 20 cold processes each, on a 4-vCPU cloud machine. MCP start is unchanged within noise: serve keeps the full cache, and its boot touches a vector table, so the extension load only moves. Postgres brains are unchanged.
+
+## To take advantage of v0.60.213.0
+
+Nothing to do: `gbrain upgrade` is enough. There is no migration and no config.
+
+### Itemized changes
+
+- **Smaller buffer pool for one-shot reads** (`core/engine-connect.ts`, `core/pglite-embedded-assets.ts` `withSharedBuffers`, `EngineConfig.pglite_shared_buffers`). PGLite's backend zero-fills its whole `shared_buffers` pool when it starts, about 55 ms for the data directory's 128MB default. A CLI process that runs one read-scope operation (the shared-op path, `gbrain call <read op>`, `search`, `sources list`) now opens with `-c shared_buffers=32MB` (`ONE_SHOT_READ_SHARED_BUFFERS`), which keeps about 90% of that saving. Serve, writes, admin ops and every other command keep the default. Measured first-query cost after a fresh open on a 5,000-page brain moves by ±5 ms.
+- **Extensions load on first use** (`core/pglite-embedded-assets.ts` `lazyExtension`, `readExtensionFiles`). The `vector` and `pg_trgm` bundles are gunzipped and untarred in memory and written into PGLite's filesystem in the extension's `init`, after the backend starts, instead of PGLite streaming them through gunzip and compiling and linking both libraries before startup. Postgres loads each library on its first call into it. Open drops about 30 ms; the first query that needs `vector.so` pays about 1–4 ms more. The tarballs are no longer copied to a temp directory.
+- **`gbrain call`, `capture` and `forget` prewarm the PGLite WASM compile** while their modules load (`cli/main.ts`), as shared-op and post-connect commands already did.
+
+### For contributors
+
+- `scripts/bench/efficiency/probe-pglite-open.ts` times `PGlite.create` on a copy of a data directory: stock (eager) versus lazy extensions at 128MB and 32MB, one fresh process per sample, plus the first query that loads `vector.so`. On the 85-page brain: 202 / 239 ms stock at 128MB, 120 / 153 ms lazy at 32MB (p50 / p95, N=20).
+- Tests: `test/engine-connect.test.ts` pins 32MB for a one-shot read connect and 128MB otherwise, and that `gbrain call` asks for it only for read-scope tools; `test/pglite-embedded-assets.test.ts` pins the bundle contents, refuses an unsupported tar entry, and installs and queries both extensions through an HNSW and a trigram index.
+
## [0.60.212.0] - 2026-10-13
**CI test shards are packed from fresh timings again.** CI splits each test lane across several machines using the recorded run time of every test file. Test files added since the last refresh had no recorded time, so shards were packed from guesses for them. This release re-measures all three lanes from green master runs. No product behaviour changes.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index f3cb55790d..8ea55446f5 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -32,7 +32,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 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 `startParams` = PGLite's defaults then `PGLITE_START_PARAM_OVERRIDES` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). The package itself is a type-only import plus one lazy `await import('@electric-sql/pglite')` inside `build()` after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout, spawned with `bun --no-install` so script auto-install cannot mask a missing package).
+- `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 + `vector`/`pg_trgm` extensions via `PGliteOptions` (the tarballs are gunzipped and untarred in memory, and `lazyExtension` writes their files into PGLite's filesystem in the extension's `init`, after the backend starts, so postgres loads each `.so` on first use instead of PGLite preloading both on every open, about 30 ms; `readExtensionFiles` refuses any entry that is not a file or directory), plus `startParams` = PGLite's defaults then `PGLITE_START_PARAM_OVERRIDES` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). `withSharedBuffers` appends `-c shared_buffers=<size>` when `EngineConfig.pglite_shared_buffers` is set: `connectEngineForServe` sets `ONE_SHOT_READ_SHARED_BUFFERS` (32MB) for a one-shot read-scope CLI process (shared op path, `gbrain call <read op>`, `search`, `sources list`), because the backend zero-fills the whole pool at start (about 55 ms for the 128MB default) and one read never fills it; serve and writes keep the default. The package itself is a type-only import plus one lazy `await import('@electric-sql/pglite')` inside `build()` after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout, spawned with `bun --no-install` so script auto-install cannot mask a missing package).
- `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/scripts/bench/efficiency/README.md b/scripts/bench/efficiency/README.md
index b3051cf808..705dd1ce79 100644
--- a/scripts/bench/efficiency/README.md
+++ b/scripts/bench/efficiency/README.md
@@ -19,6 +19,7 @@ Requires Bun >= 1.4 (the repo's `engines.bun`) and Docker for the Postgres engin
| `probe-cold.ts` | Cold CLI start split: bun start, module graph, `--version`, real reads, each with stdout piped and with `GBRAIN_FLUSH_GRACE_MS=0` (the non-TTY exit-flush grace). |
| `probe-rerank.ts` | Direct Voyage `/v1/rerank` grid over `top_n_in x max_doc_tokens` and models on candidate sets drawn from a Postgres bench brain: billed tokens/call, $/1k queries, p50/p95, top-5 agreement with the 25x1400 default (a drift signal, not quality). Spends ~$0.1 per 20-query grid. |
| `probe-mcp-start.ts` | MCP stdio cold start: fresh `gbrain serve` per sample, spawn -> initialize, spawn -> tools/list, first tools/call latency and spawn -> first call, after each `--idle-ms` gap; interleaves several `--cli` trees and prints the tools/list size and hash per tree (equal hashes = byte-identical list). |
+| `probe-pglite-open.ts` | PGLite open cost on a copy of a data directory: `PGlite.create` with PGLite's stock (eager) vs gbrain's lazy extensions, at the 128MB default vs the 32MB one-shot-read `shared_buffers`, one fresh process per sample, plus the first query that loads `vector.so`. |
| `bench-chunk.ts` | In-process chunk pass: parse every page of a synthetic brain directory (or `--cjk <pages>` for a generated mixed CJK / Latin / emoji corpus), then time the importer's `prepareMarkdownChunks` over all pages for `--n` passes after a warm-up. Prints p50/p95 per pass and a sha256 over every chunk, so a before/after pair doubles as an equivalence check. |
| `vector-scope-share.ts` | Vector search latency and recall per source scope against an existing Postgres or PGLite brain (GBRA-71): `searchVector` per scope, recall of result pages against the exact statement, page share, the chunk count the engine routes on, underfilled exits; `--remote` adds the private-page rule. |
| `remote-rows.ts` | Rows for hosted-brain read latency recorded during a pull. |
diff --git a/scripts/bench/efficiency/probe-pglite-open.ts b/scripts/bench/efficiency/probe-pglite-open.ts
new file mode 100644
index 0000000000..aacffcfa28
--- /dev/null
+++ b/scripts/bench/efficiency/probe-pglite-open.ts
@@ -0,0 +1,66 @@
+#!/usr/bin/env bun
+/**
+ * PGLite open probe (GBRA-92). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/probe-pglite-open.ts --data <brain.pglite dir> [--n 20]
+ *
+ * Times `PGlite.create` on a copy of an existing PGLite data directory, one
+ * fresh process per sample, interleaving four variants:
+ * stock-128MB PGLite's stock vector/pg_trgm extensions (eager preload), the
+ * data directory's shared_buffers (128MB)
+ * lazy-128MB gbrain's extensions (files written after start, loaded on first use)
+ * stock-32MB / lazy-32MB the same with `-c shared_buffers=32MB` (one-shot reads)
+ * Each sample also times the first query that loads vector.so, so the cost the
+ * lazy extensions move to first use stays visible. Prints p50/p95 per variant.
+ */
+import { cpSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { flag, pct, round } from './lib.ts';
+
+const VARIANTS = ['stock-128MB', 'lazy-128MB', 'stock-32MB', 'lazy-32MB'] as const;
+
+if (flag('child')) {
+ const [ext, buffers] = flag('child')!.split('-') as ['stock' | 'lazy', string];
+ const { getEmbeddedPgliteOptions } = await import('../../../src/core/pglite-embedded-assets.ts');
+ const { PGlite } = await import('@electric-sql/pglite');
+ const embedded = await getEmbeddedPgliteOptions();
+ const extensions = ext === 'lazy' ? embedded.extensions : {
+ vector: (await import('@electric-sql/pglite/vector')).vector,
+ pg_trgm: (await import('@electric-sql/pglite/contrib/pg_trgm')).pg_trgm,
+ };
+ const startParams = buffers === '128MB' ? embedded.startParams : [...embedded.startParams, '-c', `shared_buffers=${buffers}`];
+ const t0 = performance.now();
+ const db = await PGlite.create({ ...embedded, extensions, startParams, dataDir: flag('data')! });
+ const t1 = performance.now();
+ await db.query(`SELECT '[1,2,3]'::vector <-> '[1,2,4]'::vector`);
+ const t2 = performance.now();
+ await db.close();
+ console.log(JSON.stringify({ create: t1 - t0, firstVector: t2 - t1 }));
+ process.exit(0);
+}
+
+const n = Number(flag('n', '20'));
+const work = mkdtempSync(join(tmpdir(), 'gbrain-probe-open-'));
+const dataDir = join(work, 'data');
+cpSync(flag('data')!, dataDir, { recursive: true });
+const samples: Record<string, { create: number[]; firstVector: number[] }> = {};
+try {
+ for (let i = 0; i < n + 1; i++) {
+ for (const v of VARIANTS) {
+ const proc = Bun.spawnSync([process.execPath, import.meta.path, '--child', v, '--data', dataDir], { stderr: 'inherit' });
+ if (proc.exitCode !== 0) throw new Error(`${v} sample failed (exit ${proc.exitCode})`);
+ if (i === 0) continue; // first round warms the page cache
+ const r = JSON.parse(proc.stdout.toString().trim().split('\n').pop()!);
+ (samples[v] ??= { create: [], firstVector: [] }).create.push(r.create);
+ samples[v]!.firstVector.push(r.firstVector);
+ }
+ }
+} finally {
+ rmSync(work, { recursive: true, force: true });
+}
+console.log(`variant n create p50/p95 ms first vector query p50/p95 ms`);
+for (const v of VARIANTS) {
+ const s = samples[v]!;
+ console.log(`${v.padEnd(13)} ${String(s.create.length).padStart(3)} ${round(pct(s.create, 0.5))} / ${round(pct(s.create, 0.95))}`.padEnd(40) + `${round(pct(s.firstVector, 0.5))} / ${round(pct(s.firstVector, 0.95))}`);
+}
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4067ab06e8..d381db67b1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown
src/core/pglite-engine.ts 3026 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts)
src/core/postgres-engine.ts 3042 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured)
src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)
-src/core/types.ts 2302 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc)
+src/core/types.ts 2304 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
src/commands/init.ts 1882 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 8aefdb61cd..709888bc0f 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -404,7 +404,7 @@ async function main() {
if (strictRefusal) exitCliError(strictRefusal, command);
// A command that opens the local PGLite brain compiles its WASM off the main thread while its modules load (connect awaits the same promise).
- const prewarm = (cliOps.has(command) || cliAliases.has(command) || findCliCommand(command)?.phase === 'post-connect') && loadConfig();
+ const prewarm = (cliOps.has(command) || cliAliases.has(command) || findCliCommand(command)?.phase === 'post-connect' || findCliCommand(command)?.dispatchedBy === 'deferred-persistence') && loadConfig();
if (prewarm && prewarm.engine === 'pglite' && prewarm.database_path) void import('../core/pglite-embedded-assets.ts').then(m => m.getEmbeddedPgliteOptions()).catch(() => {});
// T5 — `gbrain search modes|stats|tune` is the read-only config dashboard,
@@ -616,7 +616,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
}
// No live serve owns the selected brain; connect through the normal lock path.
- const engine = await connectEngine();
+ const engine = await connectEngine({ oneShotRead: op.scope === 'read' });
// #2084: the teardown contract (bounded drain of every background-work sink,
// bounded disconnect, computed-deadline backstop) lives in finishCliTeardown
// — see src/core/cli-force-exit.ts for the full design. The hard-deadline
@@ -2386,7 +2386,7 @@ async function runReadOnlyTimeoutDispatch(command: string, args: string[]): Prom
const label = `gbrain ${command}`;
let engine: BrainEngine;
try {
- engine = await withTimeout(connectEngine(), readOnlyTimeoutMs, `${label}: connect`);
+ engine = await withTimeout(connectEngine({ oneShotRead: command === 'search' || args[0] === 'list' || args[0] === undefined }), readOnlyTimeoutMs, `${label}: connect`);
} catch (e) {
if (e instanceof OperationTimeoutError) {
const hint = userTimeoutMs ? '' : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
@@ -2741,7 +2741,7 @@ async function dispatchReadOnlyCommand(engine: BrainEngine, command: string, arg
// re-exported) so cli.ts's own connectEngine() call sites bind it locally.
import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
export { buildGatewayConfig };
-import { connectEngineForServe, noBrainError, type EngineConnectHooks } from '../core/engine-connect.ts';
+import { connectEngineForServe, noBrainError, type EngineConnectHooks, type EngineConnectOptions } from '../core/engine-connect.ts';
/**
* Which brain this process's engine targets. Set by connectEngine after brain
@@ -2787,7 +2787,7 @@ async function connectMountEngine(brainId: string): Promise<BrainEngine> {
return handle.engine;
}
-async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngine> {
+async function connectEngine(opts?: EngineConnectOptions): Promise<BrainEngine> {
// Brain axis: resolve WHICH DATABASE this invocation targets before touching
// the host engine. --brain (global flag) / GBRAIN_BRAIN_ID / .gbrain-mount /
// mount-path-prefix resolve via the canonical 6-tier chain — the mirror of
diff --git a/src/commands/call.ts b/src/commands/call.ts
index 54cec655db..4e208e9228 100644
--- a/src/commands/call.ts
+++ b/src/commands/call.ts
@@ -1,4 +1,6 @@
import type { BrainEngine } from '../core/engine.ts';
+import type { EngineConnectOptions } from '../core/engine-connect.ts';
+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
import { handleToolCall } from '../mcp/server.ts';
import { resolveSourceWithTier, localFederatedSourceIds } from '../core/source-resolver.ts';
import { bigintToStringReplacer } from '../core/utils.ts';
@@ -32,7 +34,7 @@ function writePathFailure(error: unknown): boolean {
* env / dotfile / path-match all work.
*/
export async function runCall(
- engine: BrainEngine | (() => Promise<BrainEngine>),
+ engine: BrainEngine | ((opts?: EngineConnectOptions) => Promise<BrainEngine>),
args: string[],
// Test seam — production always uses the awaited-delivery writer (#3423).
out: (payload: string) => Promise<void> = writeStdoutFinal,
@@ -89,7 +91,9 @@ export async function runCall(
throw error;
}
try {
- const connected = typeof engine === 'function' ? await engine() : engine;
+ const connected = typeof engine === 'function'
+ ? await engine({ oneShotRead: OPERATION_MANIFEST.find(op => op.name === tool)?.scope === 'read' })
+ : engine;
// Resolve through the canonical 6-tier chain. resolveSourceWithTier()
// throws if an explicit/env/dotfile id refers to a non-registered source.
// #3874: mirror cli.ts's makeContext — when the source resolved via a
diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.ts
index 88e96f3f6e..160c2b0eab 100644
--- a/src/commands/persistence-delegate.ts
+++ b/src/commands/persistence-delegate.ts
@@ -1,6 +1,7 @@
/** CLI-only commands may parse/read input before lazily connecting to a local engine. */
import type { BrainEngine } from '../core/engine.ts';
import type { GBrainConfig } from '../core/config.ts';
+import type { EngineConnectOptions } from '../core/engine-connect.ts';
import { OperationError } from '../core/ops/contract.ts';
import { finishCliTeardown, noteRenderedErrorCode, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
@@ -73,7 +74,7 @@ export async function runDelegatedCliOperation(
export async function runDeferredPersistenceCommand(
command: 'capture' | 'forget' | 'call' | 'sources' | 'takes',
args: string[],
- connect: () => Promise<BrainEngine>,
+ connect: (opts?: EngineConnectOptions) => Promise<BrainEngine>,
): Promise<void> {
// A3: refusing to remove or archive the default source is invalid input (exit 2), as on
// the unmanaged lane; the write lane's verdict would be 1.
@@ -84,7 +85,7 @@ export async function runDeferredPersistenceCommand(
{ fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the named sources that can be removed or archived.' } }), 'sources');
}
let connected: BrainEngine | null = null;
- const getEngine = async () => connected ??= await connect();
+ const getEngine = async (opts?: EngineConnectOptions) => connected ??= await connect(opts);
try {
if (command === 'takes') {
const { runTakesMutation, runTakesRebuild } = await import('./takes-mutation.ts');
diff --git a/src/core/engine-connect.ts b/src/core/engine-connect.ts
index 77d078bf83..f042787552 100644
--- a/src/core/engine-connect.ts
+++ b/src/core/engine-connect.ts
@@ -23,6 +23,22 @@ export interface EngineConnectHooks {
completeStartup(engine: BrainEngine): Promise<void>;
}
+/**
+ * PGLite `shared_buffers` for a process that runs one read operation and exits.
+ * The backend zero-fills its whole buffer pool at start (emscripten's anonymous
+ * mmap), about 55 ms for the data directory's 128 MB default, and one read
+ * never fills it. 32 MB keeps about 90% of that saving. Serve, writes and
+ * every other command keep the default.
+ */
+export const ONE_SHOT_READ_SHARED_BUFFERS = '32MB';
+
+export interface EngineConnectOptions {
+ /** get_health, `upgrade --status`, doctor's migration_wedge check: never start or wait on migrations. */
+ probeOnly?: boolean;
+ /** The process runs one read-scope operation and exits (sizes PGLite's buffer pool, see above). */
+ oneShotRead?: boolean;
+}
+
/** No config on this machine: the classified error with the keyless-init fix. */
export function noBrainError() {
return opError('no_brain', 'No brain configured. Run: gbrain init', 'Run `gbrain init --pglite --no-embedding` for a local keyless brain, or `gbrain init --help` for hosted and Postgres options.', {
@@ -31,7 +47,7 @@ export function noBrainError() {
});
}
-export async function connectEngineForServe(hooks: EngineConnectHooks, opts: { probeOnly?: boolean } = {}): Promise<BrainEngine> {
+export async function connectEngineForServe(hooks: EngineConnectHooks, opts: EngineConnectOptions = {}): Promise<BrainEngine> {
const config = loadConfig();
if (!config) throw noBrainError();
if (isThinClient(config) && !config.database_url) {
@@ -42,15 +58,17 @@ export async function connectEngineForServe(hooks: EngineConnectHooks, opts: { p
const { configureGateway } = await import('./ai/gateway.ts');
configureGateway(buildGatewayConfig(config));
const { createEngine } = await import('./engine-factory.ts');
- const engine = await createEngine(toEngineConfig(config));
+ const engineConfig = opts.oneShotRead && config.engine === 'pglite'
+ ? { ...toEngineConfig(config), pglite_shared_buffers: ONE_SHOT_READ_SHARED_BUFFERS }
+ : toEngineConfig(config);
+ const engine = await createEngine(engineConfig);
hooks.SELECTED_CONFIG_BY_ENGINE.set(engine, config);
const noRetry = process.argv.includes('--no-retry-connect') || process.env.GBRAIN_NO_RETRY_CONNECT === '1';
const { connectWithRetry } = await import('./db.ts');
- await connectWithRetry(engine, toEngineConfig(config), { noRetry });
+ await connectWithRetry(engine, engineConfig, { noRetry });
try {
// Engine graduation: a fenced target or a cut-over source refuses every connect but the run's own.
await (await import('./persistence/graduation-custody.ts')).gateGraduationConnect(engine);
- // probeOnly (get_health, `upgrade --status`, doctor's migration_wedge check) never starts or waits on migrations.
if (opts.probeOnly !== true) await hooks.completeStartup(engine);
} catch (e) {
await engine.disconnect().catch(() => {});
diff --git a/src/core/pglite-embedded-assets.ts b/src/core/pglite-embedded-assets.ts
index 91a099bfcd..1857adaeaa 100644
--- a/src/core/pglite-embedded-assets.ts
+++ b/src/core/pglite-embedded-assets.ts
@@ -24,32 +24,26 @@
* - `pgliteWasmModule` — pglite.wasm bytes → WebAssembly.compile
* - `initdbWasmModule` — initdb.wasm bytes → WebAssembly.compile
* - `fsBundle` — pglite.data bytes → Blob
- * - custom `vector` / `pg_trgm` extensions whose `setup()` returns a
- * `bundlePath` URL pointing at the embedded tarball, replacing the stock
- * extensions' `new URL("../vector.tar.gz", import.meta.url)` (which breaks
- * under compile).
+ * - custom `vector` / `pg_trgm` extensions that write the embedded tarballs'
+ * files into PGLite's filesystem once the backend is up (see
+ * lazyExtension), replacing the stock extensions'
+ * `new URL("../vector.tar.gz", import.meta.url)` (which breaks under
+ * compile).
*
- * All of these are read with `readFileSync`, which works on `/$bunfs` paths.
- *
- * One wrinkle: PGLite loads an extension tarball via `fs.createReadStream`
- * (gunzip pipeline), and `createReadStream` — unlike `readFileSync`/`existsSync`
- * — does NOT work on `/$bunfs` paths. So the two tarballs are materialized to a
- * real temp file first (content-addressed + atomic write + size-verified reuse)
- * and the `bundlePath` points there. This runs unconditionally in both modes
- * (in source mode it's a one-time copy of a ~15-46KB file), so there is no
- * fragile compiled-vs-source branch. The WASM modules and fsBundle need no
- * materialization because PGLite consumes them as bytes we already hold.
+ * All of these are read with `readFileSync`, which works on `/$bunfs` paths;
+ * the tarballs are gunzipped and untarred in memory, so nothing is copied to a
+ * temp file (PGLite's own loader streams a bundle with `fs.createReadStream`,
+ * which does not work on `/$bunfs` paths).
*
* Guarded by scripts/check-pglite-embedded.sh (compiles a binary and asserts a
* real PGLite query round-trips), mirroring scripts/check-wasm-embedded.sh.
*/
-import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, statSync } from 'node:fs';
-import { pathToFileURL, fileURLToPath } from 'node:url';
+import { readFileSync, existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
-import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
-import { createHash } from 'node:crypto';
+import { gunzipSync } from 'node:zlib';
import type { Extension } from '@electric-sql/pglite';
/** The five on-disk asset paths PGLite's runtime needs, however they were found. */
@@ -185,27 +179,60 @@ export const PGLITE_START_PARAM_OVERRIDES = [
let cached: Promise<EmbeddedPgliteOptions> | null = null;
+/** One regular file of an extension tarball, path relative to PGLite's install prefix. */
+export interface ExtensionFile { path: string; data: Uint8Array }
+
/**
- * Read an embedded tarball and copy it to a stable, content-addressed temp file
- * that `fs.createReadStream` can open (see module doc for why the raw bunfs path
- * can't be streamed). Content-addressing (sha256 of bytes) means a version bump
- * writes a fresh file; the size check re-writes over a truncated remnant from a
- * crashed writer; the tmp-then-rename keeps concurrent writers from tearing.
+ * Gunzip and untar an extension bundle in memory. PGLite's bundles are plain
+ * ustar archives of regular files and directories; any other entry type
+ * (links, pax headers) means the bundle format changed, so it fails loudly
+ * instead of silently dropping files postgres would later need.
*/
-function materializeTarball(embeddedPath: string, baseName: string): URL {
- const bytes = readFileSync(embeddedPath);
- const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16);
- const dir = join(tmpdir(), 'gbrain-pglite-assets');
- mkdirSync(dir, { recursive: true });
- // 'vector.tar.gz' -> 'vector-<hash>.tar.gz' (keep the .tar.gz suffix intact).
- const dot = baseName.indexOf('.');
- const dest = join(dir, `${baseName.slice(0, dot)}-${hash}${baseName.slice(dot)}`);
- if (!(existsSync(dest) && statSync(dest).size === bytes.byteLength)) {
- const tmp = `${dest}.${process.pid}.${Date.now()}.tmp`;
- writeFileSync(tmp, bytes);
- renameSync(tmp, dest);
+export function readExtensionFiles(tarballPath: string): ExtensionFile[] {
+ const tar = gunzipSync(readFileSync(tarballPath));
+ const text = (start: number, length: number) => tar.toString('latin1', start, start + length).replace(/\0.*$/s, '');
+ const files: ExtensionFile[] = [];
+ for (let offset = 0; offset + 512 <= tar.length && tar[offset] !== 0;) {
+ const name = text(offset + 345, 155) ? `${text(offset + 345, 155)}/${text(offset, 100)}` : text(offset, 100);
+ const size = parseInt(text(offset + 124, 12).trim() || '0', 8);
+ const type = text(offset + 156, 1);
+ const dataStart = offset + 512;
+ if (type === '0' || type === '') files.push({ path: name.replace(/^\.\//, ''), data: tar.subarray(dataStart, dataStart + size) });
+ else if (type !== '5') throw new Error(`Unsupported entry type '${type}' for ${name} in PGLite extension bundle ${tarballPath}`);
+ offset = dataStart + Math.ceil(size / 512) * 512;
}
- return pathToFileURL(dest);
+ return files;
+}
+
+/**
+ * An extension whose files are written into PGLite's filesystem after the
+ * backend starts, without PGLite's eager preload. The stock path streams the
+ * bundle through gunzip and compiles and links every `.so` before the backend
+ * starts, about 30 ms per open even when the command never touches a vector or
+ * trigram. Postgres loads `$libdir/<name>.so` on its first call into the
+ * library (a vector value, an HNSW or trigram index, CREATE EXTENSION), and
+ * emscripten's dlopen then loads the file synchronously from the filesystem.
+ * Nothing postgres runs before `init` (startup, WAL replay, PGLite's array-type
+ * query) calls into either library.
+ */
+function lazyExtension(name: string, files: ExtensionFile[]): Extension {
+ return {
+ name,
+ setup: async (_pg, emscriptenOpts) => {
+ let mod: { FS: { mkdirTree(path: string): void; writeFile(path: string, data: Uint8Array): void }; WASM_PREFIX: string } | null = null;
+ return {
+ emscriptenOpts: { ...emscriptenOpts, preRun: [...(emscriptenOpts.preRun ?? []), (m: NonNullable<typeof mod>) => { mod = m; }] },
+ init: async () => {
+ if (!mod) throw new Error(`PGLite never ran the ${name} extension's preRun hook`);
+ for (const file of files) {
+ const target = `${mod.WASM_PREFIX}/${file.path}`;
+ mod.FS.mkdirTree(target.slice(0, target.lastIndexOf('/')));
+ mod.FS.writeFile(target, file.data);
+ }
+ },
+ };
+ },
+ };
}
async function build(): Promise<EmbeddedPgliteOptions> {
@@ -216,21 +243,10 @@ async function build(): Promise<EmbeddedPgliteOptions> {
]);
const fsBundle = new Blob([readFileSync(paths.fsBundle)]);
- const vectorBundle = materializeTarball(paths.vectorTarball, 'vector.tar.gz');
- const pgTrgmBundle = materializeTarball(paths.pgTrgmTarball, 'pg_trgm.tar.gz');
-
- // Custom extensions mirror the stock ones (dist/vector/index.js,
- // dist/contrib/pg_trgm.js) but hand back the embedded tarball's file URL
- // instead of `new URL("../vector.tar.gz", import.meta.url)`. vector passes the
- // emscripten opts through exactly as the stock extension does.
- const vector: Extension = {
- name: 'pgvector',
- setup: async (_pg, emscriptenOpts) => ({ emscriptenOpts, bundlePath: vectorBundle }),
- };
- const pg_trgm: Extension = {
- name: 'pg_trgm',
- setup: async () => ({ bundlePath: pgTrgmBundle }),
- };
+ // Same extension names as the stock `{ vector, pg_trgm }` so the schema's
+ // CREATE EXTENSION statements resolve unchanged; see lazyExtension().
+ const vector = lazyExtension('pgvector', readExtensionFiles(paths.vectorTarball));
+ const pg_trgm = lazyExtension('pg_trgm', readExtensionFiles(paths.pgTrgmTarball));
// The package import stays lazy and after resolvePgliteAssetPaths(): a top-level runtime import fails at module
// load with the raw "Cannot find module" when the package is missing, before the tier-3 reinstall sentence above
@@ -246,9 +262,14 @@ async function build(): Promise<EmbeddedPgliteOptions> {
/**
* Resolve the embedded PGLite runtime options. Cached: the WASM modules compile
* once per process and are reusable across every PGlite instance; the tarballs
- * materialize once. Spread the result into `PGlite.create({ ... })`.
+ * are read once. Spread the result into `PGlite.create({ ... })`.
*/
export function getEmbeddedPgliteOptions(): Promise<EmbeddedPgliteOptions> {
if (!cached) cached = build();
return cached;
}
+
+/** The options with `shared_buffers` overridden for one open; `size` unset returns them unchanged. */
+export function withSharedBuffers(options: EmbeddedPgliteOptions, size: string | undefined): EmbeddedPgliteOptions {
+ return size ? { ...options, startParams: [...options.startParams, '-c', `shared_buffers=${size}`] } : options;
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 502de50992..ef9ed93f07 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -27,7 +27,7 @@ import { join as joinPath, resolve as resolvePath, sep as pathSep } from 'node:p
// PGLite's WASM/fsBundle/extension assets embedded via `with { type: 'file' }`
// so a `bun build --compile` binary can serve a PGLite brain (Bun vfs #1340).
// The embedded `extensions` REPLACE the stock `{ vector, pg_trgm }` imports.
-import { getEmbeddedPgliteOptions } from './pglite-embedded-assets.ts';
+import { getEmbeddedPgliteOptions, withSharedBuffers } from './pglite-embedded-assets.ts';
import {
drainBackgroundWorkBeforeDisconnect,
backgroundWorkSinkCount,
@@ -903,7 +903,7 @@ export class PGLiteEngine implements BrainEngine {
// Embedded WASM/fsBundle/extension assets (Bun vfs #1340). Resolved once
// here so both the initial create and the WAL-repair retry below share the
// same compiled modules. Its `extensions` replaces the stock vector/pg_trgm.
- const embedded = await getEmbeddedPgliteOptions();
+ const embedded = withSharedBuffers(await getEmbeddedPgliteOptions(), config.pglite_shared_buffers);
try {
this._db = this._attachDatabase(await preservingProcessExitCode(() =>
PGlite.create({
diff --git a/src/core/types.ts b/src/core/types.ts
index a1f67cdf2b..3615cfed32 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -2286,6 +2286,8 @@ export interface EngineConfig {
engine?: 'postgres' | 'pglite';
/** #6495 file-plane `search.keyword_statement_timeout_ms`, read by the Postgres engine at connect (postgres-engine/keyword-statement-timeout.ts). */
keyword_statement_timeout_ms?: number;
+ /** PGLite `shared_buffers` for this open (e.g. '32MB'); unset keeps the data directory's setting. */
+ pglite_shared_buffers?: string;
}
// Errors
diff --git a/test/engine-connect.test.ts b/test/engine-connect.test.ts
index 49104f60e8..f465c6ae4e 100644
--- a/test/engine-connect.test.ts
+++ b/test/engine-connect.test.ts
@@ -11,7 +11,8 @@ import { describe, test, expect } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { connectEngineForServe, type EngineConnectHooks } from '../src/core/engine-connect.ts';
+import { connectEngineForServe, ONE_SHOT_READ_SHARED_BUFFERS, type EngineConnectHooks, type EngineConnectOptions } from '../src/core/engine-connect.ts';
+import { runCall } from '../src/commands/call.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import type { GBrainConfig } from '../src/core/config.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -55,4 +56,48 @@ describe('connectEngineForServe', () => {
rmSync(home, { recursive: true, force: true });
}
}, 60_000);
+
+ test('a one-shot read opens PGLite with the small buffer pool; every other connect keeps the data directory default', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-engine-connect-buffers-'));
+ try {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, 'brain.pglite') }));
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const sharedBuffers = async (opts: EngineConnectOptions) => {
+ const engine = await connectEngineForServe(hooks(), opts);
+ try { return (await engine.executeRaw<{ shared_buffers: string }>('SHOW shared_buffers'))[0]!.shared_buffers; }
+ finally { await engine.disconnect(); }
+ };
+ expect(ONE_SHOT_READ_SHARED_BUFFERS).toBe('32MB');
+ expect(await sharedBuffers({ oneShotRead: true })).toBe('32MB');
+ expect(await sharedBuffers({})).toBe('128MB');
+ expect(await sharedBuffers({ oneShotRead: false })).toBe('128MB');
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
+
+describe('gbrain call sizes its connect by the operation scope', () => {
+ const stub = {
+ executeRaw: async (sql: string) => sql.includes('FROM sources') ? [{ id: 'default' }] : [],
+ getStats: async () => ({ pages: 1, chunks: 1 }),
+ } as unknown as BrainEngine;
+ // Only the options runCall hands its connect are under test; the stub's op results may fail.
+
+ test('a read-scope operation asks for a one-shot read connect, an admin-scope one does not', async () => {
+ const asked: (EngineConnectOptions | undefined)[] = [];
+ const connect = async (opts?: EngineConnectOptions) => { asked.push(opts); return stub; };
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-engine-connect-call-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await runCall(connect, ['--source', 'default', 'get_page', '{"slug":"notes/x"}'], async () => {});
+ await runCall(connect, ['--source', 'default', 'get_stats'], async () => {});
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ expect(asked).toEqual([{ oneShotRead: true }, { oneShotRead: false }]);
+ });
});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 10f51ffadf..70b2b1c8c1 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -569,7 +569,8 @@
"database_path?: string | undefined",
"database_url?: string | undefined",
"engine?: \"postgres\" | \"pglite\" | undefined",
- "keyword_statement_timeout_ms?: number | undefined"
+ "keyword_statement_timeout_ms?: number | undefined",
+ "pglite_shared_buffers?: string | undefined"
],
"name": "EngineConfig"
},
@@ -8323,7 +8324,8 @@
"database_path?: string | undefined",
"database_url?: string | undefined",
"engine?: \"postgres\" | \"pglite\" | undefined",
- "keyword_statement_timeout_ms?: number | undefined"
+ "keyword_statement_timeout_ms?: number | undefined",
+ "pglite_shared_buffers?: string | undefined"
],
"name": "EngineConfig"
},
diff --git a/test/pglite-embedded-assets.test.ts b/test/pglite-embedded-assets.test.ts
index 6dc0c29d55..9ed255b73c 100644
--- a/test/pglite-embedded-assets.test.ts
+++ b/test/pglite-embedded-assets.test.ts
@@ -12,11 +12,12 @@
* moves them, this fails here instead of in a broken bun-global install.
*/
import { describe, test, expect } from 'bun:test';
-import { existsSync, statSync } from 'node:fs';
+import { existsSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { PGlite } from '@electric-sql/pglite';
-import { resolvePgliteAssetPaths, getEmbeddedPgliteOptions, PGLITE_START_PARAM_OVERRIDES } from '../src/core/pglite-embedded-assets.ts';
+import { resolvePgliteAssetPaths, getEmbeddedPgliteOptions, readExtensionFiles, PGLITE_START_PARAM_OVERRIDES } from '../src/core/pglite-embedded-assets.ts';
describe('resolvePgliteAssetPaths (#4116)', () => {
test('dev checkout resolves via the embedded anchor with all five assets present', async () => {
@@ -57,3 +58,47 @@ describe('resolvePgliteAssetPaths (#4116)', () => {
expect(PGLITE_START_PARAM_OVERRIDES).toEqual(['-c', 'max_parallel_maintenance_workers=0', '-c', 'max_wal_size=8GB']);
});
});
+
+describe('extension files load on first use (GBRA-92)', () => {
+ test('each bundle yields its library, control file and install script', async () => {
+ const { paths } = await resolvePgliteAssetPaths();
+ const vector = new Map(readExtensionFiles(paths.vectorTarball).map(f => [f.path, f.data.byteLength]));
+ const trgm = new Map(readExtensionFiles(paths.pgTrgmTarball).map(f => [f.path, f.data.byteLength]));
+ for (const [files, name] of [[vector, 'vector'], [trgm, 'pg_trgm']] as const) {
+ expect(files.get(`lib/postgresql/${name}.so`)).toBeGreaterThan(0);
+ expect(files.get(`share/postgresql/extension/${name}.control`)).toBeGreaterThan(0);
+ expect([...files.keys()].some(p => p.startsWith(`share/postgresql/extension/${name}--`) && p.endsWith('.sql'))).toBe(true);
+ }
+ });
+
+ test('a bundle entry that is neither a file nor a directory is refused, not dropped', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-ext-bundle-'));
+ try {
+ writeFileSync(join(dir, 'real.so'), 'x');
+ symlinkSync('real.so', join(dir, 'alias.so'));
+ const tarball = join(dir, 'bundle.tar.gz');
+ expect(Bun.spawnSync(['tar', '-czf', tarball, '-C', dir, 'real.so', 'alias.so']).exitCode).toBe(0);
+ expect(() => readExtensionFiles(tarball)).toThrow(/Unsupported entry type '2' for alias\.so/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('vector and pg_trgm install and answer queries without PGLite preloading them', async () => {
+ const db = await PGlite.create({ ...(await getEmbeddedPgliteOptions()) });
+ try {
+ await db.exec('CREATE EXTENSION vector; CREATE EXTENSION pg_trgm;');
+ await db.exec('CREATE TABLE items (id int, embedding vector(3), title text)');
+ await db.exec("CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops)");
+ await db.exec("CREATE INDEX ON items USING gin (title gin_trgm_ops)");
+ await db.exec("INSERT INTO items VALUES (1, '[1,0,0]', 'alpha example'), (2, '[0,1,0]', 'beta example')");
+ const { rows } = await db.query<{ id: number; d: number; s: number }>(
+ "SELECT id, embedding <=> '[1,0,0]' AS d, similarity(title, 'alpha exampel') AS s FROM items ORDER BY embedding <=> '[1,0,0]' LIMIT 1");
+ expect(rows[0]!.id).toBe(1);
+ expect(rows[0]!.d).toBe(0);
+ expect(rows[0]!.s).toBeGreaterThan(0.5);
+ } finally {
+ await db.close();
+ }
+ }, 60_000);
+});