Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Two gbrain processes can no longer run the same schema migration at once (GST-2501)

garrytan3b6656e22ce8
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index e1d8df3743..806a02c2dd 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -47,7 +47,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`). `formatBuildFailureWarning` appends `param=$n` (or `param=?` for an array element) to an `UNDEFINED_VALUE` line from the driver's `onbuilderror(code, statement, parameter)` (#6543).
-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + a transaction-local `set_config` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection; the keyword-side bound (`searchKeyword`, `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchKeywordChunks`, `_searchKeywordCJK`) is `search.keyword_statement_timeout_ms` (#6495; default 8000, range 1000-60000), resolved once per connection by `keywordStatementTimeoutSetting()` on the first keyword statement (`postgres-engine/keyword-statement-timeout.ts`: the `EngineConfig.keyword_statement_timeout_ms` value the engine connected with, else the DB plane's row read by one parameterless pool statement so no pg-types cache entry is described and `connect()` issues nothing for it, else the default; never a request parameter), with `countKeywordPages` keeping a caller's narrower `timeoutMs`. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. `withScopedReadTransaction` applies every setting a search read needs (RLS `app.scopes`, `jit`, the caller's `settings`: `statement_timeout`, the relaxed arms' `enable_seqscan`, the vector scan settings from `vectorScanSettings`, a thunk read after BEGIN) in one `withSearchSettings` statement, `SELECT set_config('<name>', $n, true), …`, so a top-level read is BEGIN, settings, query, COMMIT; `statement_timeout` stays a literal name with a bound value so the vendored driver's #6543 budget reads it. Inside a caller's transaction the search runs in a savepoint, reads the caller's values in one statement and restores every one afterwards (a failed read rolls them back with the savepoint). A top-level read transaction opts in to `begin({ early: isPipelinableSearchRead })` (GBRA-156): its settings statement and its reads (single SELECT or WITH statements naming no write, lock, sequence or session setting) go out behind BEGIN before BEGIN's answer on any pool that pipelines inside a transaction, one round trip instead of two. Pinned by `test/search-settings-one-statement.test.ts` and `test/e2e/search-query-contract-postgres.test.ts`. `executeRaw(sql, params, { jitOff: true })` (`postgres-engine/jit-off-statement.ts`) gives single statements the same setting only when it pays: the server's `jit` is read once per pool, a JIT-off server runs the plain statement, and a JIT-on server runs `BEGIN; SET LOCAL jit = off`, the statement and `COMMIT` pipelined in the `runBoundedStatement` envelope (`postgres-engine/bounded-statement.ts`, which keeps `timeoutMs`/`deadlineAt` and the abort signal); inside a caller's transaction it reads, overrides and restores the caller's value. Pinned by `test/e2e/typed-search-jit-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.
+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + a transaction-local `set_config` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection; the keyword-side bound (`searchKeyword`, `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchKeywordChunks`, `_searchKeywordCJK`) is `search.keyword_statement_timeout_ms` (#6495; default 8000, range 1000-60000), resolved once per connection by `keywordStatementTimeoutSetting()` on the first keyword statement (`postgres-engine/keyword-statement-timeout.ts`: the `EngineConfig.keyword_statement_timeout_ms` value the engine connected with, else the DB plane's row read by one parameterless pool statement so no pg-types cache entry is described and `connect()` issues nothing for it, else the default; never a request parameter), with `countKeywordPages` keeping a caller's narrower `timeoutMs`. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. `withScopedReadTransaction` applies every setting a search read needs (RLS `app.scopes`, `jit`, the caller's `settings`: `statement_timeout`, the relaxed arms' `enable_seqscan`, the vector scan settings from `vectorScanSettings`, a thunk read after BEGIN) in one `withSearchSettings` statement, `SELECT set_config('<name>', $n, true), …`, so a top-level read is BEGIN, settings, query, COMMIT; `statement_timeout` stays a literal name with a bound value so the vendored driver's #6543 budget reads it. Inside a caller's transaction the search runs in a savepoint, reads the caller's values in one statement and restores every one afterwards (a failed read rolls them back with the savepoint). A top-level read transaction opts in to `begin({ early: isPipelinableSearchRead })` (GBRA-156): its settings statement and its reads (single SELECT or WITH statements naming no write, lock, sequence or session setting) go out behind BEGIN before BEGIN's answer on any pool that pipelines inside a transaction, one round trip instead of two. Pinned by `test/search-settings-one-statement.test.ts` and `test/e2e/search-query-contract-postgres.test.ts`. `executeRaw(sql, params, { jitOff: true })` (`postgres-engine/jit-off-statement.ts`) gives single statements the same setting only when it pays: the server's `jit` is read once per pool, a JIT-off server runs the plain statement, and a JIT-on server runs `BEGIN; SET LOCAL jit = off`, the statement and `COMMIT` pipelined in the `runBoundedStatement` envelope (`postgres-engine/bounded-statement.ts`, which keeps `timeoutMs`/`deadlineAt` and the abort signal); inside a caller's transaction it reads, overrides and restores the caller's value. Pinned by `test/e2e/typed-search-jit-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `initSchema` runs the bootstrap, the schema replay and the migrations under the schema migration lock (GBRA-467, `holdSchemaMigrationLock`, key 42), the same lock `runMigrations()` takes when `gbrain apply-migrations` calls it directly (`withSchemaMigrationLock`), so no two runners apply a migration at once; the runner reads the schema version once the lock is held and checks it is still held before each migration, and PGLite (one process per datastore) serializes in-process (`src/core/schema-migration-lock.ts`, `test/schema-migration-lock-pglite.test.ts`). The lock is `pg_try_advisory_xact_lock(42)` inside a READ COMMITTED transaction held open on a backend reserved from the DDL pool, or from the statement pool when the DDL pool has one connection (a short-lived command's idle direct connection would time out and drop it); it holds through a transaction-mode pooler and is released when its holder dies. Only when every pool has one connection does it take the session lock. A timed-out waiter is told not to terminate a holder tagged `gbrain-schema-migration-lock`. The bootstrap and replay run on a second reserved backend (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool runs them unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts` `test/e2e/schema-migration-lock-postgres.test.ts` (direct and PgBouncer passes) and `test/e2e/schema-migration-lock-direct-pool-postgres.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.
- `src/core/search/connection-budget.ts` — per-op pooled-connection budget for `search` and `query`. `SEARCH_CONNECTION_LIMIT` (4) is the most connections one op holds at once. `withSearchConnectionBudget` opens the scope; the ops' `metered` wrapper in `src/core/ops/search.ts` and `dispatchToolCall` (`src/mcp/dispatch.ts`, so pre-op reads and the response-meta hook count too) both enter it, and a nested call shares the enclosing budget. `holdSearchConnection` is called at the engine's two connection seams, `PostgresEngine#transactionOn` (a top-level transaction, held until its COMMIT settles even when a read transaction answers early) and `runUnsafe` (one statement). Work inside a held slot runs outside the scope, so statements on a transaction's own connection never wait on a second slot. A read started under `withUrgentSearchConnections` (hybrid search's lexical, relational and vector arms, `hybrid/arms.ts`) takes the next free slot ahead of waiting ordinary reads (the keyword count and entity resolution an op starts early for its response; GBRA-156, `test/search-connection-budget-urgent.test.ts`). Outside a scope, and on PGLite, nothing waits. These reads use the ordinary read pool (the transaction pooler behind a split route), never the direct/session lane. Pinned on Postgres at the wire by `test/e2e/search-connection-budget-postgres.test.ts`.
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`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.
diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv
index 7e6fa80994..dd2ea888de 100644
--- a/scripts/core-world-reads-baseline.tsv
+++ b/scripts/core-world-reads-baseline.tsv
@@ -902,6 +902,8 @@ src/core/routing-eval.ts fs_import 1 W7: filesystem boundary moves to the local
src/core/runtime-build.ts fs_import 1 W7: filesystem boundary moves to the local app
src/core/runtime-version.ts process_global 2 W7: process-wide effects move to src/cli
src/core/schema-events.ts fs_import 1 W7: filesystem boundary moves to the local app
+src/core/schema-migration-lock.ts als_store 1 stays: GBRA-467 reentrancy scope of the schema migration lock held by this process (coordination state, not a setting)
+src/core/schema-migration-lock.ts module_collection 1 stays: GBRA-467 per-engine in-process queue for engines without a cross-process schema lock (PGLite); coordination state, not a setting
src/core/schema-pack/bundled-assets.ts fs_import 1 W7: filesystem boundary moves to the local app
src/core/schema-pack/candidate-audit.ts fs_import 1 W7: filesystem boundary moves to the local app
src/core/schema-pack/candidate-audit.ts process_env 1 W6: settings plane out of the core
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index 8608f203ed..43f3652c34 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -46,6 +46,7 @@ test/e2e/projection-recovery-parity.test.ts
test/e2e/takes-scorecard-parity.test.ts
test/e2e/evidence-delivery-parity.test.ts
test/e2e/apply-migrations-orchestration-lock.test.ts
+test/e2e/schema-migration-lock-postgres.test.ts
test/e2e/postgres-poisoned-connection.test.ts
test/e2e/write-attribution-postgres.test.ts
test/e2e/write-attribution-timeline-10k-postgres.test.ts
diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsv
index ccebac6587..a5e54b6801 100644
--- a/scripts/engine-sql-baseline.tsv
+++ b/scripts/engine-sql-baseline.tsv
@@ -61,7 +61,6 @@ method src/core/postgres-engine.ts PostgresEngine.getIngestLog
method src/core/postgres-engine.ts PostgresEngine.getOntology
method src/core/postgres-engine.ts PostgresEngine.getRawData
method src/core/postgres-engine.ts PostgresEngine.getStats
-method src/core/postgres-engine.ts PostgresEngine.initSchema
method src/core/postgres-engine.ts PostgresEngine.listConfigKeys
method src/core/postgres-engine.ts PostgresEngine.listEvalCandidates
method src/core/postgres-engine.ts PostgresEngine.listEvalCaptureFailures
@@ -78,4 +77,3 @@ method src/core/postgres-engine.ts PostgresEngine.setConfig
method src/core/postgres-engine.ts PostgresEngine.sweepDreamVerdicts
method src/core/postgres-engine.ts PostgresEngine.unsetConfig
method src/core/postgres-engine/init-schema-lock.ts acquireInitSchemaAdvisoryLock
-method src/core/postgres-engine/init-schema-lock.ts lockHolderPid
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f1cd64de0e..20cdbb05ea 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,7 +16,7 @@ src/commands/sync.ts 568 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3351 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relative; re-summed at the memory train #8481 merge with v0.60.576.0 (3348 measured); +3 GST-1856: the purge phase drops applied-capture records past 90 days (logic in ingestion/applied-captures.ts purgeStaleAppliedCaptures)
src/core/cycle/synthesize.ts 3244 ratchet +3 #7805: each captured session synthesizes only into its own frozen source (routing import, the outer wrapper, the routing parameter; logic in cycle/synthesize-source-routing.ts); +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
-src/core/engine.ts 2884 ratchet +5 #7191: findPages/countPagesBy signatures and type imports (SQL in engine-sql/page-lookup.ts); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); re-summed at the Wave B PR 4 merge with v0.60.452.0 (2866 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (2874 measured); +1 GST-731: TrajectoryPoint.valid_until (interface fields cannot move); +9 #9068: deletePage/deletePages scrub contract docs (interface docs cannot move)
+src/core/engine.ts 2886 ratchet +5 #7191: findPages/countPagesBy signatures and type imports (SQL in engine-sql/page-lookup.ts); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); re-summed at the Wave B PR 4 merge with v0.60.452.0 (2866 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (2874 measured); +1 GST-731: TrajectoryPoint.valid_until (interface fields cannot move); +9 #9068: deletePage/deletePages scrub contract docs (interface docs cannot move); +2 GBRA-467: optional holdSchemaMigrationLock member (interface members cannot move; logic in schema-migration-lock.ts)
src/core/import-file.ts 2091 ratchet +2 #7880: importFromContent's holdNoncanonicalPrivate option (interface field; the hold is screenImportContent's); +2 #7848: importFromFile holds a non-canonical private request (predicate and hold in persistence/visibility-request.ts); +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075; +7 GBRA-283 B3a (#8523): the three file import entry points re-enter an embedded engine's scope (needsEngineScope in core/engine-scope.ts), importFromContent runs its screened body in that scope as a closure, and the deferred embed resumes the import's scope; re-summed at the memory train #8481 merge with v0.60.576.0 (2088 measured); +3 GST-2112: importFromContent's expectedBaseRevision option and base check (a webhook capture binds its write to its readers check)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 249 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured); +1 Wakeshift PR 1: wakeshiftOperations import (ops/wakeshift.ts; its spread shares the jobs line)
diff --git a/src/core/engine.ts b/src/core/engine.ts
index be0c636b99..971e2f00b1 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -841,6 +841,8 @@ export interface BrainEngine {
*/
reconnect(ctx?: { error?: unknown }): Promise<void>;
initSchema(): Promise<void>;
+ /** GBRA-467: run `fn` under the cross-process schema migration lock; callers use schema-migration-lock.ts. */
+ holdSchemaMigrationLock?<T>(fn: (assertHeld: () => Promise<void>) => Promise<T>): Promise<T>;
transaction<T>(fn: (engine: BrainEngine) => Promise<T>, opts?: TransactionOptions): Promise<T>;
/** Short control transaction on the existing direct route; honors nested transaction scope. */
transactionDirect<T>(fn: (engine: BrainEngine) => Promise<T>, opts?: TransactionOptions): Promise<T>;
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 79d38df3c7..bebf7be332 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -2,6 +2,8 @@ import type { BrainEngine } from './engine.ts';
import type { Migration } from './schema-migrations/types.ts';
import { isLockTimeoutError } from './retry-matcher.ts';
import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from './postgres-engine/schema-lock-timeout.ts';
+import { SCHEMA_MIGRATION_LOCK_APPLICATION_NAME } from './postgres-engine/init-schema-lock.ts';
+import { assertSchemaMigrationLockHeld, withSchemaMigrationLock } from './schema-migration-lock.ts';
import { MIGRATIONS } from './schema-migrations/registry.generated.ts';
import { hasPendingMigrations } from './migrate-pending.ts';
import { runMigrationStatement, setQuietMigrationNotices } from './schema-migrations/helpers.ts';
@@ -113,7 +115,8 @@ export async function getIdleBlockers(engine: BrainEngine): Promise<IdleBlocker[
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND query_start < NOW() - INTERVAL '5 minutes'
- AND pid != pg_backend_pid()`
+ AND pid != pg_backend_pid()
+ AND application_name IS DISTINCT FROM '${SCHEMA_MIGRATION_LOCK_APPLICATION_NAME}'`
);
} catch {
return [];
@@ -364,7 +367,14 @@ export function isDeadlockError(err: unknown): boolean {
return /40P01|deadlock detected/i.test(msg);
}
+export { withSchemaMigrationLock };
+
+/** GBRA-467: under the schema migration lock (schema-migration-lock.ts); the version is read once it is held. */
export async function runMigrations(engine: BrainEngine): Promise<{ applied: number; current: number }> {
+ return withSchemaMigrationLock(engine, () => runMigrationsLocked(engine));
+}
+
+async function runMigrationsLocked(engine: BrainEngine): Promise<{ applied: number; current: number }> {
const currentStr = await engine.getConfig('version');
const current = parseInt(currentStr || '1', 10);
@@ -475,6 +485,7 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
await checkForBlockingConnections(engine);
for (const m of pending) {
+ await assertSchemaMigrationLockHeld();
if (!quietReplay) process.stderr.write(` [${m.version}] ${m.name}...\n`);
try {
await applyOneMigration(engine, m);
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 46699a1d57..139a57c8fc 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1165,13 +1165,16 @@ export class PGLiteEngine implements BrainEngine {
dims = storedIdentity.dimensions;
model = storedIdentity.model;
}
- await this.applyForwardReferenceBootstrap();
- await this.db.exec(getPGLiteSchema(dims, model));
-
- const { applied } = await (await import('./migrate.ts')).runMigrations(this); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
- if (applied > 0) {
- process.stderr.write(` ${applied} migration(s) applied\n`);
- }
+ const { runMigrations, withSchemaMigrationLock } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
+ await withSchemaMigrationLock(this, async () => {
+ await this.applyForwardReferenceBootstrap();
+ await this.db.exec(getPGLiteSchema(dims, model));
+
+ const { applied } = await runMigrations(this);
+ if (applied > 0) {
+ process.stderr.write(` ${applied} migration(s) applied\n`);
+ }
+ });
await registerManagedFilesystemEngine(this, this._savedConfig?.database_path);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index c80b4fdc49..a88d2376cb 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -132,7 +132,7 @@ import { assertEmbeddedEmbedding, embeddedSchemaEmbedding, embeddedSettingsRecor
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
-import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';
+import { holdSchemaMigrationSessionLock, holdSchemaMigrationTransactionLock } from './postgres-engine/init-schema-lock.ts';
import { isPipelinableSearchRead, SEARCH_JIT_OFF, withSearchJitOff, withSearchSettings, type SearchSettings } from './postgres-engine/search-settings.ts';
import { loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
@@ -606,51 +606,44 @@ export class PostgresEngine implements BrainEngine {
}
let sqlText = getPostgresSchema(dims, model);
- // Advisory lock prevents concurrent initSchema() calls from deadlocking
- // on DDL statements (DROP TRIGGER + CREATE TRIGGER acquire AccessExclusiveLock).
- //
- // pg_advisory_lock(42) is session-scoped but ddl() returns a POOL, so on a
- // pool of more than one backend the acquire, DDL and unlock are pinned to
- // one reserved backend (no long-hold permit: migrations reserve their own,
- // and a pool of one is already a single backend).
- const pinned = pool.options.max > 1;
- if (pinned) this.checkoutGauge.acquire('reserved');
- const conn: postgres.Sql = pinned ? await pool.reserve().catch((e) => { this.checkoutGauge.release('reserved'); throw e; }) : pool;
- if (pinned) this.checkoutGauge.checkedOut();
+ // GBRA-467: the schema migration lock covers the bootstrap, the replay and the migrations (holdSchemaMigrationLock).
+ const { runMigrations, withSchemaMigrationLock } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
+ const t0 = Date.now();
+ logConnectionEvent({
+ pool: this.connectionManager?.isDualPoolActive() ? 'ddl' : 'read',
+ op: 'acquire',
+ caller: 'PostgresEngine.initSchema',
+ });
try {
- const t0 = Date.now();
- logConnectionEvent({
- pool: this.connectionManager?.isDualPoolActive() ? 'ddl' : 'read',
- op: 'acquire',
- caller: 'PostgresEngine.initSchema',
- });
- // Lock-census (PR6 D5): INTENTIONALLY brain-global (session lock, fixed key 42) — initSchema DDL mutates the whole database; a per-source key would let two initSchema calls deadlock on shared DDL.
- // #2898: deadlined pg_try_advisory_lock loop + stderr heartbeat instead of
- // an unbounded pg_advisory_lock — a leaked pooler session holding key 42
- // hung every gbrain invocation forever with no output. On timeout the
- // error names the holder pid with pg_terminate_backend recovery guidance.
- await acquireInitSchemaAdvisoryLock((q) => conn.unsafe(q));
- try {
+ await withSchemaMigrationLock(this, async () => {
// Another initSchema may have recorded an identity between the read above and this lock: check it again here.
const lockedIdentity = storedIdentity ? null : await readStoredEmbeddingIdentity(this);
if (lockedIdentity?.model) {
if (embedded) assertEmbeddedEmbedding(embedded, lockedIdentity);
if (lockedIdentity.dimensions !== dims || lockedIdentity.model !== model) sqlText = getPostgresSchema(lockedIdentity.dimensions, lockedIdentity.model);
}
- // Pre-schema bootstrap: add forward-referenced state the embedded schema
- // blob requires but that older brains don't have yet (issues #366/#375/
- // #378/#396 + #266/#357). Idempotent on fresh installs and modern brains.
- // Threads the DDL connection (same one holding the advisory lock above)
- // so bootstrap probes run on the locked connection — without this, the
- // probes ran through `this.sql` (the pooler/instance pool) outside the
- // lock, opening a concurrent-bootstrap race for Supabase users on the
- // transaction pooler. Codex P1 finding from v0.36 dreamy-thompson wave.
- await this.applyForwardReferenceBootstrap(conn);
-
- await retrySchemaReplayOnDeadlock(() => withSchemaLockTimeout(conn, () => conn.unsafe(sqlText), { step: 'replay', diagnostic: schemaDiagnosticConnection(this._savedConfig?.database_url) })); // #5227: bounded wait, typed schema_lock_blocked; #6143: a deadlock victim runs again
+ // The bootstrap and the replay share one backend: withSchemaLockTimeout sets a session lock_timeout on it.
+ // On a pool of more than one it is a reserved backend (checkout gauge only, no long-hold permit: migrations
+ // reserve their own); a pool of one is already a single backend.
+ const pinned = pool.options.max > 1;
+ if (pinned) this.checkoutGauge.acquire('reserved');
+ const conn: postgres.Sql = pinned ? await pool.reserve().catch((e) => { this.checkoutGauge.release('reserved'); throw e; }) : pool;
+ if (pinned) this.checkoutGauge.checkedOut();
+ try {
+ // Pre-schema bootstrap: add forward-referenced state the embedded schema
+ // blob requires but that older brains don't have yet (issues #366/#375/
+ // #378/#396 + #266/#357). Idempotent on fresh installs and modern brains.
+ // Threads the DDL connection so the bootstrap probes run inside the schema
+ // lock, not on the pooler outside it (Codex P1 finding, v0.36 dreamy-thompson wave).
+ await this.applyForwardReferenceBootstrap(conn);
+
+ await retrySchemaReplayOnDeadlock(() => withSchemaLockTimeout(conn, () => conn.unsafe(sqlText), { step: 'replay', diagnostic: schemaDiagnosticConnection(this._savedConfig?.database_url) })); // #5227: bounded wait, typed schema_lock_blocked; #6143: a deadlock victim runs again
+ } finally {
+ if (pinned) { (conn as postgres.ReservedSql).release(); this.checkoutGauge.release('reserved'); }
+ }
// Run any pending migrations automatically
- const { applied } = await (await import('./migrate.ts')).runMigrations(this); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
+ const { applied } = await runMigrations(this);
if (applied > 0) {
process.stderr.write(` ${applied} migration(s) applied\n`);
}
@@ -673,17 +666,34 @@ export class PostgresEngine implements BrainEngine {
process.stderr.write(` HNSW sweep: dropped ${result.dropped.length} zombie index(es)\n`);
}
} catch { /* best-effort */ }
- } finally {
- await conn`SELECT pg_advisory_unlock(42)`;
- logConnectionEvent({
- pool: this.connectionManager?.isDualPoolActive() ? 'ddl' : 'read',
- op: 'release',
- caller: 'PostgresEngine.initSchema',
- duration_ms: Date.now() - t0,
- });
- }
+ });
+ } finally {
+ logConnectionEvent({
+ pool: this.connectionManager?.isDualPoolActive() ? 'ddl' : 'read',
+ op: 'release',
+ caller: 'PostgresEngine.initSchema',
+ duration_ms: Date.now() - t0,
+ });
+ }
+ }
+
+ /**
+ * GBRA-467: the schema migration lock (key 42, brain-global), transaction-scoped on a backend reserved from the
+ * DDL pool, or from the statement pool when the DDL pool has one connection (a short-lived command's direct pool,
+ * left idle by the migrations until its idle timeout drops it). Session lock only when every pool has one.
+ */
+ async holdSchemaMigrationLock<T>(fn: (assertHeld: () => Promise<void>) => Promise<T>): Promise<T> {
+ const ddl = this.connectionManager ? await this.connectionManager.ddl() : this.sql;
+ const pool = ddl.options.max > 1 ? ddl : this.sql.options.max > 1 ? this.sql : null;
+ if (!pool) return holdSchemaMigrationSessionLock(ddl, fn);
+ this.checkoutGauge.acquire('reserved');
+ const conn = await pool.reserve().catch((e) => { this.checkoutGauge.release('reserved'); throw e; });
+ this.checkoutGauge.checkedOut();
+ try {
+ return await holdSchemaMigrationTransactionLock(conn, fn);
} finally {
- if (pinned) { (conn as postgres.ReservedSql).release(); this.checkoutGauge.release('reserved'); }
+ conn.release();
+ this.checkoutGauge.release('reserved');
}
}
diff --git a/src/core/postgres-engine/init-schema-lock.ts b/src/core/postgres-engine/init-schema-lock.ts
index d632923d99..5e05d0e02e 100644
--- a/src/core/postgres-engine/init-schema-lock.ts
+++ b/src/core/postgres-engine/init-schema-lock.ts
@@ -28,6 +28,9 @@
* initSchema calls deadlock on shared DDL). */
export const INIT_SCHEMA_LOCK_KEY = 42;
+/** The `application_name` of the transaction holding the schema migration lock, so diagnostics name it as a running migration and idle-blocker reports skip it. */
+export const SCHEMA_MIGRATION_LOCK_APPLICATION_NAME = 'gbrain-schema-migration-lock';
+
const DEFAULT_TIMEOUT_MS = 10 * 60_000;
const DEFAULT_POLL_MS = 500;
const DEFAULT_HEARTBEAT_MS = 5_000;
@@ -60,21 +63,25 @@ export function resolveInitSchemaLockTimeoutMs(
return DEFAULT_TIMEOUT_MS;
}
-/** Best-effort: pid of the granted holder of the advisory lock, or null. */
-async function lockHolderPid(
+/** Best-effort: pid of the granted holder of the advisory lock, and whether it is a running migration's lock transaction. */
+// engine-sql-ok: pg_locks/pg_stat_activity read naming the holder of the Postgres advisory lock; PGLite takes none
+async function lockHolder(
query: (sql: string) => Promise<Array<Record<string, unknown>>>,
-): Promise<number | null> {
+): Promise<{ pid: number | null; migrating: boolean }> {
try {
const rows = await query(
- `SELECT pid FROM pg_locks
- WHERE locktype = 'advisory' AND classid = 0
- AND objid = ${INIT_SCHEMA_LOCK_KEY} AND granted
+ `SELECT l.pid, a.application_name FROM pg_locks l LEFT JOIN pg_stat_activity a ON a.pid = l.pid
+ WHERE l.locktype = 'advisory' AND l.classid = 0
+ AND l.objid = ${INIT_SCHEMA_LOCK_KEY} AND l.granted
LIMIT 1`,
);
const pid = rows[0]?.pid;
- return typeof pid === 'number' ? pid : pid != null ? Number(pid) : null;
+ return {
+ pid: typeof pid === 'number' ? pid : pid != null ? Number(pid) : null,
+ migrating: rows[0]?.application_name === SCHEMA_MIGRATION_LOCK_APPLICATION_NAME,
+ };
} catch {
- return null;
+ return { pid: null, migrating: false };
}
}
@@ -87,6 +94,16 @@ async function lockHolderPid(
export async function acquireInitSchemaAdvisoryLock(
query: (sql: string) => Promise<Array<Record<string, unknown>>>,
opts: InitSchemaLockOpts = {},
+): Promise<void> {
+ await waitForSchemaLock(async () => (await query(`SELECT pg_try_advisory_lock(${INIT_SCHEMA_LOCK_KEY}) AS locked`))[0]?.locked === true, query, opts);
+}
+
+/** Polls `tryLock` until it returns true, with the heartbeat and deadline described above. */
+// engine-sql-ok: polls a Postgres advisory-lock attempt; no storage-domain SQL
+async function waitForSchemaLock(
+ tryLock: () => Promise<boolean>,
+ query: (sql: string) => Promise<Array<Record<string, unknown>>>,
+ opts: InitSchemaLockOpts,
): Promise<void> {
const timeoutMs = resolveInitSchemaLockTimeoutMs(opts);
const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
@@ -98,15 +115,23 @@ export async function acquireInitSchemaAdvisoryLock(
const started = now();
let lastBeat = started;
for (;;) {
- const rows = await query(`SELECT pg_try_advisory_lock(${INIT_SCHEMA_LOCK_KEY}) AS locked`);
- if (rows[0]?.locked === true) return;
+ if (await tryLock()) return;
const elapsed = now() - started;
if (elapsed >= timeoutMs) {
- const holder = await lockHolderPid(query);
+ const { pid: holder, migrating } = await lockHolder(query);
const holderNote = holder != null
? `Held by backend pid ${holder}.`
: 'Holder pid could not be determined from pg_locks.';
+ // A live migration holds it: terminating that backend would let a second runner start the step in flight.
+ if (migrating) {
+ throw new Error(
+ `initSchema: timed out after ${Math.round(elapsed / 1000)}s waiting for the schema advisory lock ` +
+ `(pg_advisory_lock(${INIT_SCHEMA_LOCK_KEY})). ${holderNote} Another gbrain process is running schema migrations; ` +
+ `do not terminate it. Retry once it finishes (it releases the lock when it ends). ` +
+ `Tune the wait with GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS.`,
+ );
+ }
throw new Error(
`initSchema: timed out after ${Math.round(elapsed / 1000)}s waiting for the schema advisory lock ` +
`(pg_advisory_lock(${INIT_SCHEMA_LOCK_KEY})). ${holderNote} ` +
@@ -124,10 +149,10 @@ export async function acquireInitSchemaAdvisoryLock(
if (now() - lastBeat >= heartbeatMs) {
lastBeat = now();
- const holder = await lockHolderPid(query);
+ const { pid: holder, migrating } = await lockHolder(query);
log(
` [initSchema] waiting for the schema advisory lock` +
- `${holder != null ? ` (held by backend pid ${holder})` : ''}` +
+ `${holder != null ? ` (held by backend pid ${holder}${migrating ? ', running schema migrations' : ''})` : ''}` +
` — ${Math.round(elapsed / 1000)}s elapsed, timeout ${Math.round(timeoutMs / 1000)}s`,
);
}
@@ -135,3 +160,80 @@ export async function acquireInitSchemaAdvisoryLock(
await sleep(pollMs);
}
}
+
+type Query = (sql: string) => Promise<Array<Record<string, unknown>>>;
+
+// engine-sql-ok: pg_locks read of this backend's own advisory lock; no storage-domain SQL
+async function assertSchemaLockHeld(query: Query): Promise<void> {
+ const rows = await query(
+ `SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND classid = 0 AND objid = ${INIT_SCHEMA_LOCK_KEY}
+ AND pid = pg_backend_pid() AND granted) AS held`,
+ ).catch(() => []);
+ if (rows[0]?.held === true) return;
+ throw new Error('The schema migration lock was lost (the connection holding it closed), so another gbrain process may now run '
+ + 'schema migrations; stopped before the next migration. Run `gbrain apply-migrations --yes` again: it resumes where this run stopped.');
+}
+
+/**
+ * GBRA-467: hold the schema migration lock (key 42) on `conn`, a reserved connection, while `fn` runs its work
+ * on other connections. Every path that runs schema migrations takes this lock
+ * (migrate.ts `withSchemaMigrationLock`).
+ *
+ * The lock is transaction-scoped, taken inside a transaction that stays open on `conn` for the whole run. A
+ * transaction-mode pooler keeps one server connection for an open transaction, so the lock holds through it,
+ * and the server releases it when the holder's connection dies. A session lock does not hold there: it lands on
+ * whichever server connection the statement got, a second caller that gets the same one takes it again, and the
+ * unlock can run on another. The transaction disables its idle timeout, since it idles while migrations run.
+ * `fn` receives a check that the lock is still held, for the runner to call before each migration.
+ */
+// engine-sql-ok: transaction control and a Postgres advisory lock (BEGIN / SET LOCAL / pg_try_advisory_xact_lock / ROLLBACK); no storage-domain SQL
+export async function holdSchemaMigrationTransactionLock<T>(
+ conn: { unsafe: (sql: string) => Promise<unknown> },
+ fn: (assertHeld: () => Promise<void>) => Promise<T>,
+ opts: InitSchemaLockOpts = {},
+): Promise<T> {
+ const query: Query = sql => conn.unsafe(sql) as Promise<Array<Record<string, unknown>>>;
+ const tryLock = async (): Promise<boolean> => {
+ // READ COMMITTED whatever the role's default: a snapshot held for the whole run would make CREATE INDEX
+ // CONCURRENTLY wait on this transaction.
+ await query('BEGIN ISOLATION LEVEL READ COMMITTED');
+ try {
+ await query('SET LOCAL idle_in_transaction_session_timeout = 0');
+ await query(`SET LOCAL application_name = '${SCHEMA_MIGRATION_LOCK_APPLICATION_NAME}'`);
+ if ((await query(`SELECT pg_try_advisory_xact_lock(${INIT_SCHEMA_LOCK_KEY}) AS locked`))[0]?.locked === true) return true;
+ } catch (error) {
+ await query('ROLLBACK').catch(() => {});
+ throw error;
+ }
+ await query('ROLLBACK');
+ return false;
+ };
+ await waitForSchemaLock(tryLock, query, opts);
+ try {
+ return await fn(() => assertSchemaLockHeld(query));
+ } finally {
+ await query('ROLLBACK').catch(() => {});
+ }
+}
+
+/**
+ * The same lock as a session lock, the fallback when every pool has one connection (GBRAIN_POOL_SIZE=1): `fn` runs
+ * its work on that connection, so nothing can hold a transaction open beside it. This keeps the pre-GBRA-467
+ * guarantee and no more: the lock holds on a real session, not through a transaction-mode pooler, so there is no
+ * held-lock check (through such a pooler it would read another server connection). Both forms use key 42, so they
+ * exclude each other and an older gbrain's session lock.
+ */
+// engine-sql-ok: Postgres session advisory-lock unlock; no storage-domain SQL
+export async function holdSchemaMigrationSessionLock<T>(
+ conn: { unsafe: (sql: string) => Promise<unknown> },
+ fn: (assertHeld: () => Promise<void>) => Promise<T>,
+ opts: InitSchemaLockOpts = {},
+): Promise<T> {
+ const query: Query = sql => conn.unsafe(sql) as Promise<Array<Record<string, unknown>>>;
+ await acquireInitSchemaAdvisoryLock(query, opts);
+ try {
+ return await fn(async () => {});
+ } finally {
+ await query(`SELECT pg_advisory_unlock(${INIT_SCHEMA_LOCK_KEY})`);
+ }
+}
diff --git a/src/core/schema-migration-lock.ts b/src/core/schema-migration-lock.ts
new file mode 100644
index 0000000000..d05cf3a998
--- /dev/null
+++ b/src/core/schema-migration-lock.ts
@@ -0,0 +1,38 @@
+/**
+ * GBRA-467: the one lock every path that runs schema migrations takes: initSchema() on each process start, and
+ * `gbrain apply-migrations` (and --force-schema) through runMigrations(), which re-reads the schema version once the
+ * lock is held, so a runner that waited finds nothing left to do. Postgres holds it across processes and connections
+ * (`BrainEngine.holdSchemaMigrationLock`, key 42 in postgres-engine/init-schema-lock.ts). An engine without that
+ * method (PGLite, whose datastore lock admits a single process) is serialized in this process.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+import type { BrainEngine } from './engine.ts';
+
+const schemaLockScope = new AsyncLocalStorage<{ engine: BrainEngine; assertHeld: () => Promise<void>; released: boolean }>();
+const inProcessSchemaLocks = new WeakMap<BrainEngine, Promise<void>>();
+
+/** Run `fn` holding the schema migration lock; a nested call on the same engine inside `fn` reuses it. */
+export async function withSchemaMigrationLock<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {
+ const held = schemaLockScope.getStore();
+ if (held?.engine === engine && !held.released) return fn();
+ const run = async (assertHeld: () => Promise<void>): Promise<T> => {
+ const scope = { engine, assertHeld, released: false };
+ try { return await schemaLockScope.run(scope, fn); } finally { scope.released = true; }
+ };
+ if (engine.holdSchemaMigrationLock) return engine.holdSchemaMigrationLock(run);
+ const previous = inProcessSchemaLocks.get(engine) ?? Promise.resolve();
+ let release!: () => void;
+ const mine = new Promise<void>(resolve => { release = resolve; });
+ inProcessSchemaLocks.set(engine, previous.then(() => mine));
+ await previous;
+ try {
+ return await run(async () => {});
+ } finally {
+ release();
+ }
+}
+
+/** Throws when the lock the current scope took has been lost; the runner calls it before each migration. */
+export async function assertSchemaMigrationLockHeld(): Promise<void> {
+ await schemaLockScope.getStore()?.assertHeld();
+}
diff --git a/test/e2e/schema-migration-lock-direct-pool-postgres.test.ts b/test/e2e/schema-migration-lock-direct-pool-postgres.test.ts
new file mode 100644
index 0000000000..cdf3591a9e
--- /dev/null
+++ b/test/e2e/schema-migration-lock-direct-pool-postgres.test.ts
@@ -0,0 +1,36 @@
+/**
+ * GBRA-467: a short-lived command with a direct URL gets a DDL pool of one connection, and the migrations run on
+ * the statement pool, so that connection sits idle past its 20 s idle timeout. A schema lock held there dropped
+ * mid-step and let a second runner start the same migration. The lock now lives in a transaction on a backend
+ * reserved from the statement pool. Direct Postgres only: a direct URL is by definition not the pooler (the
+ * pooled arms are in test/e2e/schema-migration-lock-postgres.test.ts). The probe is test/helpers/schema-lock-probe.ts.
+ */
+import { describe, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { directPoolProfile, setDirectPoolProfile } from '../../src/core/direct-pool-profile.ts';
+import { expectProbeAppliedOnce, probeDatabase, processStart } from '../helpers/schema-lock-probe.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+
+describe.skipIf(!DATABASE_URL)('schema migration lock on a one-connection direct pool (E2E)', () => {
+ test('a second initSchema start waits out a step longer than the direct pool idle timeout', async () => {
+ const db = await probeDatabase(DATABASE_URL!);
+ const a = new PostgresEngine();
+ const b = new PostgresEngine();
+ const profile = directPoolProfile();
+ try {
+ setDirectPoolProfile('short_lived');
+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: db.url }, async () => {
+ await a.connect({ database_url: db.url, poolSize: 4 });
+ await b.connect({ database_url: db.url, poolSize: 4 });
+ });
+ await expectProbeAppliedOnce(a, b, processStart, processStart, 25_000);
+ } finally {
+ setDirectPoolProfile(profile);
+ await a.disconnect();
+ await b.disconnect();
+ await db.drop();
+ }
+ }, 240_000);
+});
diff --git a/test/e2e/schema-migration-lock-postgres.test.ts b/test/e2e/schema-migration-lock-postgres.test.ts
new file mode 100644
index 0000000000..9cbf412f6b
--- /dev/null
+++ b/test/e2e/schema-migration-lock-postgres.test.ts
@@ -0,0 +1,40 @@
+/**
+ * GBRA-467: every path that runs schema migrations takes one lock, and it holds through a transaction-mode
+ * PgBouncer (this file is in scripts/e2e-backend-matrix.txt, so it also runs through the pooler).
+ *
+ * Before the fix, `gbrain apply-migrations` called runMigrations() under its orchestration lease only, while every
+ * process start ran initSchema(), which took session advisory lock 42, so the two never excluded each other, in
+ * one process or two. Through a transaction-mode pooler lock 42 did not exclude two initSchema() callers either:
+ * a session lock lands on whichever server connection the statement got, and a second caller given the same one
+ * takes it again. The probe is test/helpers/schema-lock-probe.ts.
+ */
+import { describe, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { explicitRun, expectProbeAppliedOnce, probeDatabase, processStart, type Runner } from '../helpers/schema-lock-probe.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+
+const cases: Array<[string, Runner, Runner]> = [
+ ['an initSchema start while apply-migrations is inside a step', explicitRun, processStart],
+ ['apply-migrations while an initSchema start is inside a step', processStart, explicitRun],
+ ['a second initSchema start while the first is inside a step', processStart, processStart],
+];
+
+describe.skipIf(!DATABASE_URL)(`schema migrations run once under concurrent runners [${process.env.GBRAIN_TEST_BACKEND ?? 'postgres'}] (E2E)`, () => {
+ for (const [label, first, second] of cases) {
+ test(label, async () => {
+ const db = await probeDatabase(DATABASE_URL!);
+ const a = new PostgresEngine();
+ const b = new PostgresEngine();
+ try {
+ await a.connect({ database_url: db.url, poolSize: 4 });
+ await b.connect({ database_url: db.url, poolSize: 4 });
+ await expectProbeAppliedOnce(a, b, first, second, 3_000);
+ } finally {
+ await a.disconnect();
+ await b.disconnect();
+ await db.drop();
+ }
+ }, 240_000);
+ }
+});
diff --git a/test/helpers/schema-lock-probe.ts b/test/helpers/schema-lock-probe.ts
new file mode 100644
index 0000000000..18d7ef5c21
--- /dev/null
+++ b/test/helpers/schema-lock-probe.ts
@@ -0,0 +1,82 @@
+/**
+ * GBRA-467: the probe for "two runners apply a schema migration once". A deliberately non-idempotent migration
+ * (its SQL adds a column without IF NOT EXISTS; its handler records each run, then sleeps) is pushed past the
+ * latest version, the first runner is started, and the second starts once the first is inside the step. A
+ * second run of the step either fails on the column or records a second handler row; a correct lock makes the
+ * second runner wait, find nothing to do, and succeed.
+ */
+import { expect } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { LATEST_VERSION, MIGRATIONS, runMigrations } from '../../src/core/migrate.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+import { withEnv } from './with-env.ts';
+
+export const PROBE_VERSION = LATEST_VERSION + 1;
+
+export type Runner = (engine: BrainEngine) => Promise<unknown>;
+/** What `gbrain apply-migrations` runs under its orchestration lease. */
+export const explicitRun: Runner = engine => runMigrations(engine);
+/** What every process start runs on connect. */
+export const processStart: Runner = engine => engine.initSchema();
+
+/** A scratch database at the latest schema with an empty probe table; `drop` removes it. */
+export async function probeDatabase(databaseUrl: string): Promise<{ url: string; drop: () => Promise<void> }> {
+ assertSafeE2eDatabaseUrl(databaseUrl);
+ const name = `gbrain_test_schema_lock_${randomUUID().replaceAll('-', '')}`;
+ const admin = postgres(databaseUrl, { max: 1, prepare: false, onnotice: () => {} });
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ const drop = async () => {
+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }
+ };
+ const url = new URL(databaseUrl);
+ url.pathname = `/${name}`;
+ const setup = new PostgresEngine();
+ try {
+ await setup.connect({ database_url: url.toString(), poolSize: 4 });
+ await setup.initSchema();
+ await setup.executeRaw('CREATE TABLE schema_lock_probe (step TEXT NOT NULL)');
+ } catch (error) {
+ await drop();
+ throw error;
+ } finally { await setup.disconnect(); }
+ return { url: url.toString(), drop };
+}
+
+async function bounded<T>(label: string, ms: number, work: Promise<T>): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`${label} did not finish within ${ms}ms`)), ms); });
+ try { return await Promise.race([work, deadline]); } finally { clearTimeout(timer); }
+}
+
+/** Runs `first` on `a`, then `second` on `b` once `first` is inside the probe step, and expects one clean run of it. */
+export async function expectProbeAppliedOnce(a: BrainEngine, b: BrainEngine, first: Runner, second: Runner, stepMs: number): Promise<void> {
+ let entered!: () => void;
+ const inside = new Promise<void>(resolve => { entered = resolve; });
+ MIGRATIONS.push({
+ version: PROBE_VERSION,
+ name: 'schema_lock_probe',
+ sql: "INSERT INTO schema_lock_probe (step) VALUES ('sql'); ALTER TABLE schema_lock_probe ADD COLUMN applied INTEGER",
+ handler: async (engine) => {
+ entered();
+ await engine.executeRaw("INSERT INTO schema_lock_probe (step) VALUES ('handler')");
+ await Bun.sleep(stepMs);
+ },
+ idempotent: false,
+ });
+ try {
+ await withEnv({ GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS: '90' }, async () => {
+ const firstRun = first(a);
+ await bounded('first runner entering the probe step', 60_000, inside);
+ const results = await bounded('both runners', 150_000, Promise.allSettled([firstRun, second(b)]));
+ expect(results.map(r => r.status === 'fulfilled' ? 'ok' : (r.reason as Error).message)).toEqual(['ok', 'ok']);
+ });
+ expect(await a.executeRaw('SELECT step, count(*)::int AS n FROM schema_lock_probe GROUP BY step ORDER BY step'))
+ .toEqual([{ step: 'handler', n: 1 }, { step: 'sql', n: 1 }]);
+ expect(await a.getConfig('version')).toBe(String(PROBE_VERSION));
+ } finally {
+ MIGRATIONS.splice(MIGRATIONS.findIndex(m => m.version === PROBE_VERSION), 1);
+ }
+}
diff --git a/test/schema-migration-lock-pglite.test.ts b/test/schema-migration-lock-pglite.test.ts
new file mode 100644
index 0000000000..07e207a010
--- /dev/null
+++ b/test/schema-migration-lock-pglite.test.ts
@@ -0,0 +1,68 @@
+/**
+ * GBRA-467 on PGLite: every path that runs schema migrations takes one lock, so two runners in one process
+ * (initSchema() and a direct runMigrations(), as `gbrain apply-migrations` calls it) run a pending migration
+ * once. PGLite's datastore lock admits a single process, so the lock is in-process here; the Postgres arms,
+ * across connections and through a transaction-mode PgBouncer, are test/e2e/schema-migration-lock-postgres.test.ts.
+ *
+ * The probe migration is not idempotent (its SQL adds a column without IF NOT EXISTS) and its handler records
+ * each run and then sleeps, so the second runner starts while the first is inside the step.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { LATEST_VERSION, MIGRATIONS, runMigrations } from '../src/core/migrate.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const PROBE_VERSION = LATEST_VERSION + 1;
+let engine: PGLiteEngine;
+
+// Without the CI schema snapshot: an engine opened from it skips initSchema(), and this file needs the real one.
+beforeAll(() => withEnv({ GBRAIN_PGLITE_SNAPSHOT: undefined }, async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}), 120_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+type Runner = () => Promise<unknown>;
+const explicit: Runner = () => runMigrations(engine);
+const processStart: Runner = () => engine.initSchema();
+
+describe('GBRA-467 schema migrations run once under concurrent runners (PGLite)', () => {
+ for (const [label, first, second] of [
+ ['initSchema while a direct runMigrations is inside a step', explicit, processStart],
+ ['a direct runMigrations while initSchema is inside a step', processStart, explicit],
+ ['two direct runMigrations calls', explicit, explicit],
+ ] as Array<[string, Runner, Runner]>) {
+ test(label, async () => {
+ await engine.executeRaw('DROP TABLE IF EXISTS schema_lock_probe');
+ await engine.executeRaw('CREATE TABLE schema_lock_probe (step TEXT NOT NULL)');
+ await engine.setConfig('version', String(LATEST_VERSION));
+ let entered!: () => void;
+ const inside = new Promise<void>(resolve => { entered = resolve; });
+ MIGRATIONS.push({
+ version: PROBE_VERSION,
+ name: 'schema_lock_probe',
+ sql: "INSERT INTO schema_lock_probe (step) VALUES ('sql'); ALTER TABLE schema_lock_probe ADD COLUMN applied INTEGER",
+ handler: async (e) => {
+ entered();
+ await e.executeRaw("INSERT INTO schema_lock_probe (step) VALUES ('handler')");
+ await Bun.sleep(1_000);
+ },
+ idempotent: false,
+ });
+ try {
+ const firstRun = first();
+ await inside;
+ const results = await Promise.allSettled([firstRun, second()]);
+ expect(results.map(r => r.status === 'fulfilled' ? 'ok' : (r.reason as Error).message)).toEqual(['ok', 'ok']);
+ expect(await engine.executeRaw('SELECT step, count(*)::int AS n FROM schema_lock_probe GROUP BY step ORDER BY step'))
+ .toEqual([{ step: 'handler', n: 1 }, { step: 'sql', n: 1 }]);
+ expect(await engine.getConfig('version')).toBe(String(PROBE_VERSION));
+ } finally {
+ MIGRATIONS.splice(MIGRATIONS.findIndex(m => m.version === PROBE_VERSION), 1);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ }
+ }, 60_000);
+ }
+});