Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres): bound schema lock waits and name the blocker instead of hanging (#5227)
garrytan0b126aaa7f4f
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 02b82fbe60..e85d38e9e4 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -697,6 +697,33 @@ the operations that preceded them. A pool created with `max: 1` keeps thedriver's documented single-connection idiom (`BEGIN` as an ordinary query)for unreserved statements.+<a id="schema-lock-blocked"></a>**`schema_lock_blocked`** (error, retryable).+A schema step waited its `lock_timeout` for a table lock another session holds+and stopped instead of hanging (#5227). `gbrain init` and `upgrade` replay+`schema.sql` on the reserved DDL backend; every `ALTER TABLE` there takes an+ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another+client (idle in transaction, a stuck job) used to park the whole command in+`wait_event_type=Lock` with no output. The replay runs under a session-level+`lock_timeout` on that backend (`GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default+60; the value found before is restored on release, so a pooled backend never+leaks it), a transaction-wrapped migration binds the same wait with+`SET LOCAL lock_timeout`, and a `transaction: false` migration sets and+restores it on its own reserved backend. Handler migrations and the+post-migration `verifySchema` run outside the bound: they issue their own+statements (`CREATE INDEX CONCURRENTLY` cannot run in a transaction) and stay+as they were. While the wait is active a separate one-backend connection+samples `pg_blocking_pids()` of the waiting backend once, so the refusal names+the blocking sessions by pid, `application_name`, state and transaction age;+after the cancel the blocker may already be gone, and the message says when the+sample came late. Query text is never read or shown. `detail` names the step+(`replay`, `migration v<N>`). The RLS block skips tables whose+`relrowsecurity` is already set, so a re-run on a live brain no longer takes+ACCESS EXCLUSIVE on them. `init` retries a blocked step a few times with a+short backoff (`init-schema-retry.ts`); a lock that never clears is a bounded+failure, not a hang. Fix: let the named session finish or, with the user's+agreement, end it on the database host with `SELECT pg_terminate_backend(<pid>)`,+then rerun the same command. Test: `test/e2e/init-schema-lock-blocked.test.ts`.+<a id="pg-connection-stuck"></a>**`pg_connection_stuck`** (warn). A pooledstatement waited past the pool's `statement_timeout` plus a grace with nothingcoming back from the server, so the vendored driver retired that connection:diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 08a34fda4b..bb2b7283e8 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -60,7 +60,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts` and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 59430ec766..336cf41206 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2384,6 +2384,16 @@ Reasons: `rename_source_changed`.|---|---|---|---|---|---|---|| The exact authorized revision is unavailable. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### schema_lock_blocked++<a id="schema_lock_blocked"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging. | Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing. | Let the named session finish or, with the user's agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff. Run: gbrain doctor --json | agent | `gbrain doctor --json` | 1 | yes |++More: [docs/ENGINES.md#schema-lock-blocked](../../docs/ENGINES.md#schema-lock-blocked)+### schema_pack_emit_mismatch<a id="schema_pack_emit_mismatch"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex a65f779b41..5e6c067942 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -43,6 +43,7 @@| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` || [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` || [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` |+| `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head || [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` || [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` || [Search answers look keyword-only on a large Postgres brain](#hybrid-search-returns-only-keyword-hits) | read doctor's `vector_plan`; run the index command it prints | brain host | none | `gbrain doctor --only vector_plan --json` |diff --git a/llms-full.txt b/llms-full.txtindex f046d1285d..2a89c2307d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5778,6 +5778,33 @@ the operations that preceded them. A pool created with `max: 1` keeps thedriver's documented single-connection idiom (`BEGIN` as an ordinary query)for unreserved statements.+<a id="schema-lock-blocked"></a>**`schema_lock_blocked`** (error, retryable).+A schema step waited its `lock_timeout` for a table lock another session holds+and stopped instead of hanging (#5227). `gbrain init` and `upgrade` replay+`schema.sql` on the reserved DDL backend; every `ALTER TABLE` there takes an+ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another+client (idle in transaction, a stuck job) used to park the whole command in+`wait_event_type=Lock` with no output. The replay runs under a session-level+`lock_timeout` on that backend (`GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default+60; the value found before is restored on release, so a pooled backend never+leaks it), a transaction-wrapped migration binds the same wait with+`SET LOCAL lock_timeout`, and a `transaction: false` migration sets and+restores it on its own reserved backend. Handler migrations and the+post-migration `verifySchema` run outside the bound: they issue their own+statements (`CREATE INDEX CONCURRENTLY` cannot run in a transaction) and stay+as they were. While the wait is active a separate one-backend connection+samples `pg_blocking_pids()` of the waiting backend once, so the refusal names+the blocking sessions by pid, `application_name`, state and transaction age;+after the cancel the blocker may already be gone, and the message says when the+sample came late. Query text is never read or shown. `detail` names the step+(`replay`, `migration v<N>`). The RLS block skips tables whose+`relrowsecurity` is already set, so a re-run on a live brain no longer takes+ACCESS EXCLUSIVE on them. `init` retries a blocked step a few times with a+short backoff (`init-schema-retry.ts`); a lock that never clears is a bounded+failure, not a hang. Fix: let the named session finish or, with the user's+agreement, end it on the database host with `SELECT pg_terminate_backend(<pid>)`,+then rerun the same command. Test: `test/e2e/init-schema-lock-blocked.test.ts`.+<a id="pg-connection-stuck"></a>**`pg_connection_stuck`** (warn). A pooledstatement waited past the pool's `statement_timeout` plus a grace with nothingcoming back from the server, so the vendored driver retired that connection:@@ -9836,6 +9863,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` || [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` || [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` |+| `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head || [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` || [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` || [Search answers look keyword-only on a large Postgres brain](#hybrid-search-returns-only-keyword-hits) | read doctor's `vector_plan`; run the index command it prints | brain host | none | `gbrain doctor --only vector_plan --json` |diff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex 8913f1d684..0d8eebbe56 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -429,7 +429,7 @@ export const PGLITE_RULES: readonly Rule[] = [/** DO blocks outside fragment regions are opaque, so each is classified by content hash. */export const PGLITE_DO_BLOCKS: Readonly<Record<string, { keep: boolean; reason: string }>> = {- '28b8b384fc62': { keep: false, reason: 'schema.sql RLS enablement block: PGLite has no role system (the shared-skills fragment keeps its own block)' },+ '146e456b365a': { keep: false, reason: 'schema.sql RLS enablement block (#5227 conditional enables): PGLite has no role system (the shared-skills fragment keeps its own block)' },};interface Addition {diff --git a/src/core/ai/decide/schema.ts b/src/core/ai/decide/schema.tsindex 0e2e39b16a..0131351b1c 100644--- a/src/core/ai/decide/schema.ts+++ b/src/core/ai/decide/schema.ts@@ -9,7 +9,7 @@const rls = (table: string) => `DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = '${table}' AND c.relrowsecurity) THEN ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;`;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7f63b69cc6..20f1841ea9 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -387,6 +387,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.156.0', text: 'The conversation parser now reads chat timestamps in the page\'s declared `timezone:` (an IANA zone such as Asia/Tokyo) and stores them in UTC, so a 09:00 Tokyo message is 00:00Z and the facts extracted from it carry the right `valid_from`; before, the zone only silenced the UTC warning and every timestamp was stored as if it were UTC. Conversation pages with a declared zone give different timestamps than before on re-extraction. A zone the runtime does not know keeps UTC and the warning names it. In a daylight-saving fold the first occurrence is taken; a time inside a spring-forward gap resolves with the offset in force before the change.' },// W14 PR1 P1.7 (#5966). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.156.0', text: 'A page whose slug its file path cannot derive (a doubled hyphen, which the path rule collapses to one) is now written with a `slug:` frontmatter stamp by every render (write-through, repairs, export), so sync, reconcile and repair find the page again; the stamp does not change the page\'s content digest. A file an earlier version rendered without the stamp still refuses `source_changed` on reconcile until it is repaired: `gbrain repair frontmatter --source <id>` proposes the stamp as a safe repair, and the reconcile audit\'s classify mode reports such pages as `slug_rule_mismatch`.' },+ // W14 PR1 P1.6 (#5227). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.156.0', text: 'On Postgres, `gbrain init` and `gbrain upgrade` no longer hang silently when another session holds a table lock (an open transaction in another client): the schema replay and each migration wait at most `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS` (default 60) and then stop with `schema_lock_blocked`, which names the blocking sessions by pid, application and state (never their query text) and the `pg_terminate_backend` exit; init retries a few times with a short backoff. The row-level-security block now skips tables where it is already on, so a re-run takes no exclusive lock on them.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/core-memory-schema.ts b/src/core/core-memory-schema.tsindex f41a2c6056..d8f24e6dcd 100644--- a/src/core/core-memory-schema.ts+++ b/src/core/core-memory-schema.ts@@ -28,7 +28,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'core_edit_notices' AND c.relrowsecurity) THEN ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;`;diff --git a/src/core/eligibility/generation-schema.ts b/src/core/eligibility/generation-schema.tsindex 16f8d31a0e..16de7ed1cb 100644--- a/src/core/eligibility/generation-schema.ts+++ b/src/core/eligibility/generation-schema.ts@@ -94,7 +94,7 @@ export const TRUST_GENERATION_SCHEMA_STATEMENTS: readonly string[] = [)`,`DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE ${TRUST_POLICY_STATE_TABLE} ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = '${TRUST_POLICY_STATE_TABLE}' AND c.relrowsecurity) THEN ALTER TABLE ${TRUST_POLICY_STATE_TABLE} ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$`,`INSERT INTO ${TRUST_POLICY_STATE_TABLE} (id) VALUES (1) ON CONFLICT (id) DO NOTHING`,diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2ce94ca936..e71bf2eca8 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -307,6 +307,7 @@ export const CODES = {pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },+ schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement waited past the pool's statement_timeout plus grace with nothing coming back from the server, so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "A legitimate statement cannot outlive the server-side statement_timeout, so a connection that is still waiting past it is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },pg_statement_build_failed: { class: 'server', summary: "A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was answered in its place in the pipeline by a query the server refuses; only it failed, and a transaction it was part of was aborted rather than committed without it.", why: "This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now answers the culprit in its place (the approach of porsager/postgres#1236), so only it rejects and a transaction it was in aborts.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined.' },diff --git a/src/core/facts/purge-schema.ts b/src/core/facts/purge-schema.tsindex d185cd6961..993168e36b 100644--- a/src/core/facts/purge-schema.ts+++ b/src/core/facts/purge-schema.ts@@ -26,7 +26,7 @@const RLS = (table: string) => `DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = '${table}' AND c.relrowsecurity) THEN ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;`;diff --git a/src/core/facts/relink-schema.ts b/src/core/facts/relink-schema.tsindex adfb4c2384..704fc186bb 100644--- a/src/core/facts/relink-schema.ts+++ b/src/core/facts/relink-schema.ts@@ -12,7 +12,7 @@const rls = (table: string) => `DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = '${table}' AND c.relrowsecurity) THEN ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;`;diff --git a/src/core/init-schema-retry.ts b/src/core/init-schema-retry.tsindex 5841521f0b..43de9afe85 100644--- a/src/core/init-schema-retry.ts+++ b/src/core/init-schema-retry.ts@@ -1,5 +1,6 @@import type { BrainEngine } from './engine.ts';import {+ isLockTimeoutError,isRetryableConnError,isStatementTimeoutError,} from './retry-matcher.ts';@@ -7,6 +8,8 @@ import {export interface InitSchemaRetryOpts {maxAttempts?: number;backoffMs?: number;+ /** #5227: a short bounded backoff for a lock the other session will release in a moment (default 2 s). */+ lockBackoffMs?: number;log?: (line: string) => void;_hooks?: {initSchema?: () => Promise<void>;@@ -22,12 +25,18 @@ function isMigrationRetryExhausted(err: unknown): boolean {return err instanceof Error && err.name === 'MigrationRetryExhausted';}+/** #5227: the typed `schema_lock_blocked` refusal, or a raw SQLSTATE 55P03 from a lock_timeout. */+function isSchemaLockBlocked(err: unknown): boolean {+ return (typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'schema_lock_blocked') || isLockTimeoutError(err);+}+function isRetryableInitSchemaError(err: unknown): boolean {if (isMigrationRetryExhausted(err)) return false;- return isStatementTimeoutError(err) || isRetryableConnError(err);+ return isStatementTimeoutError(err) || isRetryableConnError(err) || isSchemaLockBlocked(err);}function retryReason(err: unknown): string {+ if (isSchemaLockBlocked(err)) return 'a lock another session holds (schema_lock_blocked)';if (isStatementTimeoutError(err)) return 'statement_timeout';if (isRetryableConnError(err)) return 'transient connection error';return 'retryable schema error';@@ -59,8 +68,9 @@ export async function runInitSchemaWithRetry(throw err;}- log(` [init retry ${attempt}/${maxAttempts}] schema setup hit ${retryReason(err)}; retrying in ${backoffMs}ms`);- await sleep(backoffMs);+ const wait = isSchemaLockBlocked(err) ? (opts.lockBackoffMs ?? 2_000) : backoffMs;+ log(` [init retry ${attempt}/${maxAttempts}] schema setup hit ${retryReason(err)}; retrying in ${wait}ms`);+ await sleep(wait);}}diff --git a/src/core/link-temporal-schema.ts b/src/core/link-temporal-schema.tsindex 320172d6d1..ebfdea5ac0 100644--- a/src/core/link-temporal-schema.ts+++ b/src/core/link-temporal-schema.ts@@ -19,7 +19,7 @@const rls = (table: string) => `DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = '${table}' AND c.relrowsecurity) THEN ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;`;diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 9a22dc4a16..91634f77fa 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -1,5 +1,7 @@import type { BrainEngine } from './engine.ts';import type { Migration } from './schema-migrations/types.ts';+import { isLockTimeoutError } from './retry-matcher.ts';+import { resolveSchemaLockTimeoutMs, schemaLockBlockedError, withSchemaLockTimeout } from './postgres-engine/schema-lock-timeout.ts';import { MIGRATIONS } from './schema-migrations/registry.generated.ts';import { hasPendingMigrations } from './migrate-pending.ts';import { setQuietMigrationNotices } from './schema-migrations/helpers.ts';@@ -199,7 +201,7 @@ async function runMigrationSQLWithRetry(* Uses SET LOCAL statement_timeout inside a transaction to override* server-enforced timeouts (required for Supabase Postgres).*/-async function runMigrationSQL(+export async function runMigrationSQL(engine: BrainEngine,m: Migration,sql: string,@@ -209,16 +211,23 @@ async function runMigrationSQL(if (useTransaction || engine.kind === 'pglite') {// Wrap in transaction with extended timeout for Supabase compatibility.// SET LOCAL scopes the timeout to this transaction only.- await engine.transaction(async (tx) => {- if (engine.kind === 'postgres') {- try {- await tx.runMigration(m.version, "SET LOCAL statement_timeout = '600000'");- } catch {- // Non-fatal: PGLite or older Postgres versions may not support this+ try {+ await engine.transaction(async (tx) => {+ if (engine.kind === 'postgres') {+ try {+ await tx.runMigration(m.version, "SET LOCAL statement_timeout = '600000'");+ // #5227 (W14 P1.6): a real transaction, so SET LOCAL binds the lock wait to this migration only.+ await tx.runMigration(m.version, `SET LOCAL lock_timeout = '${resolveSchemaLockTimeoutMs()}ms'`);+ } catch {+ // Non-fatal: PGLite or older Postgres versions may not support this+ }}- }- await tx.runMigration(m.version, sql);- });+ await tx.runMigration(m.version, sql);+ });+ } catch (error) {+ if (engine.kind === 'postgres' && isLockTimeoutError(error)) throw schemaLockBlockedError({ step: `migration v${m.version}`, timeoutMs: resolveSchemaLockTimeoutMs(), sessions: null, sampledDuringWait: false });+ throw error;+ }} else {// Postgres + transaction:false → can't use SET LOCAL (needs a txn),// can't use plain SET on the pooled connection (leaks to other@@ -241,7 +250,8 @@ async function runMigrationSQL(// Non-fatal: some managed Postgres may restrict this GUC.// Falling through means the DDL runs with the server default.}- await conn.executeRaw(sql);+ // #5227 (W14 P1.6): no transaction here, so the lock bound is session-level on this reserved backend and restored after.+ await withSchemaLockTimeout({ unsafe: (query: string) => conn.executeRaw(query) }, () => conn.executeRaw(sql), { step: `migration v${m.version}` });}, { selfContained: true });}}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex e0e76a11e7..3cc7407450 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1774,7 +1774,10 @@ BEGINFOREACH target IN ARRAY ARRAY['shared_skill_state','shared_skill_policies','shared_skill_packs','shared_skill_policy_audit','shared_skill_heads','shared_skill_revisions','shared_skill_revision_leases','shared_skill_members','shared_skill_delivery_batches','persistence_writer_protocols'] LOOP- EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relrowsecurity) THEN+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ END IF;END LOOP;END IF;END \$\$;@@ -1837,17 +1840,17 @@ CREATE TABLE IF NOT EXISTS decide_state ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decision_receipts ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decision_receipts' AND c.relrowsecurity) THEN ALTER TABLE decision_receipts ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_spend ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_spend' AND c.relrowsecurity) THEN ALTER TABLE decide_spend ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_state ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_state' AND c.relrowsecurity) THEN ALTER TABLE decide_state ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -1881,7 +1884,7 @@ CREATE TABLE IF NOT EXISTS decide_calibrations (CREATE INDEX IF NOT EXISTS decide_calibrations_lookup_idx ON decide_calibrations (slot, provider, model_resolved, created_at DESC);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_calibrations ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_calibrations' AND c.relrowsecurity) THEN ALTER TABLE decide_calibrations ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -1917,12 +1920,12 @@ CREATE TABLE IF NOT EXISTS decide_sweep_deferred ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_proposals' AND c.relrowsecurity) THEN ALTER TABLE decide_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_sweep_deferred' AND c.relrowsecurity) THEN ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -1960,12 +1963,12 @@ CREATE TABLE IF NOT EXISTS decide_review_proposals (CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_review_queue' AND c.relrowsecurity) THEN ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_review_proposals' AND c.relrowsecurity) THEN ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -1985,7 +1988,7 @@ CREATE TABLE IF NOT EXISTS fact_relink_attempts (CREATE INDEX IF NOT EXISTS fact_relink_attempts_outcome_idx ON fact_relink_attempts (source_id, outcome, attempted_at);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE fact_relink_attempts ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'fact_relink_attempts' AND c.relrowsecurity) THEN ALTER TABLE fact_relink_attempts ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -2010,7 +2013,7 @@ CREATE INDEX IF NOT EXISTS link_transitions_relationship_idx ON link_transitionsCREATE INDEX IF NOT EXISTS link_transitions_origin_idx ON link_transitions (origin_page_id);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_transitions ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_transitions' AND c.relrowsecurity) THEN ALTER TABLE link_transitions ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS link_relationships (@@ -2038,7 +2041,7 @@ CREATE INDEX IF NOT EXISTS link_relationships_to_idx ON link_relationships (to_pCREATE INDEX IF NOT EXISTS link_relationships_source_idx ON link_relationships (source_id, status_now);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_relationships ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_relationships' AND c.relrowsecurity) THEN ALTER TABLE link_relationships ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS link_edge_proposals (@@ -2065,7 +2068,7 @@ CREATE TABLE IF NOT EXISTS link_edge_proposals (CREATE INDEX IF NOT EXISTS link_edge_proposals_status_idx ON link_edge_proposals (source_id, status, created_at);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_edge_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_edge_proposals' AND c.relrowsecurity) THEN ALTER TABLE link_edge_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE SEQUENCE IF NOT EXISTS graph_generation_seq;@@ -2086,7 +2089,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'core_edit_notices' AND c.relrowsecurity) THEN ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -2104,7 +2107,7 @@ CREATE TABLE IF NOT EXISTS fact_purges ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE fact_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'fact_purges' AND c.relrowsecurity) THEN ALTER TABLE fact_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS take_purges (@@ -2117,7 +2120,7 @@ CREATE TABLE IF NOT EXISTS take_purges ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE take_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'take_purges' AND c.relrowsecurity) THEN ALTER TABLE take_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS page_purges (@@ -2130,7 +2133,7 @@ CREATE TABLE IF NOT EXISTS page_purges ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE page_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'page_purges' AND c.relrowsecurity) THEN ALTER TABLE page_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS derivation_inputs (@@ -2145,7 +2148,7 @@ CREATE TABLE IF NOT EXISTS derivation_inputs (CREATE INDEX IF NOT EXISTS idx_derivation_inputs_input ON derivation_inputs (input_table, input_id);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE derivation_inputs ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'derivation_inputs' AND c.relrowsecurity) THEN ALTER TABLE derivation_inputs ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS needs_rederive (@@ -2159,7 +2162,7 @@ CREATE TABLE IF NOT EXISTS needs_rederive ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE needs_rederive ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'needs_rederive' AND c.relrowsecurity) THEN ALTER TABLE needs_rederive ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -2210,8 +2213,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS write_gate_holds_dedupe_idx ON write_gate_holdCREATE INDEX IF NOT EXISTS write_gate_holds_status_idx ON write_gate_holds (status, source_id, id);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY;- ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_receipts' AND c.relrowsecurity) THEN ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY; END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_holds' AND c.relrowsecurity) THEN ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 3229a8ed40..fef592cf9b 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -18,6 +18,7 @@ import { reservedTransactions, type ReservedTransactions } from './postgres-engiimport { traceSqlOptions } from './sql-trace.ts';import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';import { runBoundedStatement } from './postgres-engine/bounded-statement.ts';+import { schemaDiagnosticConnection, withSchemaLockTimeout } from './postgres-engine/schema-lock-timeout.ts';export { hasPostgresCancellationCapability } from './postgres-engine/cancellation.ts';import type {BrainEngine,@@ -569,7 +570,7 @@ export class PostgresEngine implements BrainEngine {// transaction pooler. Codex P1 finding from v0.36 dreamy-thompson wave.await this.applyForwardReferenceBootstrap(conn);- await conn.unsafe(sqlText);+ await withSchemaLockTimeout(conn, () => conn.unsafe(sqlText), { step: 'replay', diagnostic: schemaDiagnosticConnection(this._savedConfig?.database_url) }); // #5227: bounded wait, typed schema_lock_blocked// Run any pending migrations automaticallyconst { applied } = await (await import('./migrate.ts')).runMigrations(this); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connectdiff --git a/src/core/postgres-engine/schema-lock-timeout.ts b/src/core/postgres-engine/schema-lock-timeout.tsnew file mode 100644index 0000000000..216f9ec1dc--- /dev/null+++ b/src/core/postgres-engine/schema-lock-timeout.ts@@ -0,0 +1,140 @@+/**+ * #5227 (W14 P1.6): a bounded wait for the schema DDL's locks.+ *+ * `initSchema` replays `schema.sql` through one `conn.unsafe(sqlText)` (dozens+ * of `ALTER TABLE` and `ENABLE ROW LEVEL SECURITY`, each an ACCESS EXCLUSIVE+ * lock even as a no-op) on the reserved DDL backend, with no `lock_timeout`.+ * One idle-in-transaction session touching any table made every `gbrain init`+ * and `upgrade` wait in `wait_event_type=Lock` with no output until killed.+ *+ * The replay is many statements, not one transaction, so `SET LOCAL` binds+ * nothing there: this sets a SESSION-level `lock_timeout` on the reserved+ * backend (the `migrate.ts` `statement_timeout` precedent) and restores the+ * value it found, so a pooled backend never leaks the setting. While the wait+ * is active, a separate diagnostic connection samples `pg_blocking_pids()` of+ * the waiting backend once (after the cancel the blocker may already be gone);+ * SQLSTATE 55P03 then becomes the typed `schema_lock_blocked` refusal naming+ * those sessions by pid, application, state and transaction age. Query text+ * is never read: the message carries identifiers only.+ */+import postgres from '#postgres';+import { opError, type OperationError } from '../ops/contract.ts';+import { isLockTimeoutError } from '../retry-matcher.ts';++export interface Queryable { unsafe(query: string, params?: unknown[]): Promise<unknown> }++export interface BlockingSession {+ pid: number;+ application_name: string | null;+ state: string | null;+ wait_event_type: string | null;+ transaction_age_seconds: number | null;+}++export interface SchemaLockTimeoutOpts {+ /** The session lock_timeout in ms. Default: GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS or 60 s. */+ timeoutMs?: number;+ /** Which schema step runs under the bound; named in the refusal. */+ step: string;+ /** A separate connection for the blocker sample; `null` when none can be opened (the sample is skipped). */+ diagnostic?: () => Promise<(Queryable & { end(): Promise<void> }) | null>;+ /** When to sample blockers, in ms after the statement starts (default: half the timeout). Test seam. */+ sampleAtMs?: number;+}++const DEFAULT_TIMEOUT_MS = 60_000;++/** Resolve the timeout from opts > env > default. Invalid env falls through. */+export function resolveSchemaLockTimeoutMs(opts: Pick<SchemaLockTimeoutOpts, 'timeoutMs'> = {}, env: NodeJS.ProcessEnv = process.env): number {+ if (opts.timeoutMs !== undefined) return opts.timeoutMs;+ const raw = env.GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS;+ if (raw !== undefined && raw !== '') {+ const n = Number(raw);+ if (Number.isFinite(n) && n > 0) return n * 1000;+ }+ return DEFAULT_TIMEOUT_MS;+}++/** Sessions blocking `pid`, identifiers only (no query text). */+export const BLOCKING_SESSIONS_SQL = `SELECT pid, application_name, state, wait_event_type,+ EXTRACT(EPOCH FROM now() - xact_start)::int AS transaction_age_seconds+ FROM pg_stat_activity WHERE pid = ANY(pg_blocking_pids($1::int)) ORDER BY pid`;++export async function sampleBlockingSessions(diagnostic: Queryable, pid: number): Promise<BlockingSession[]> {+ const rows = await diagnostic.unsafe(BLOCKING_SESSIONS_SQL, [pid]) as Array<Record<string, unknown>>;+ return rows.map(row => ({+ pid: Number(row.pid),+ application_name: row.application_name == null ? null : String(row.application_name),+ state: row.state == null ? null : String(row.state),+ wait_event_type: row.wait_event_type == null ? null : String(row.wait_event_type),+ transaction_age_seconds: row.transaction_age_seconds == null ? null : Number(row.transaction_age_seconds),+ }));+}++function describe(sessions: BlockingSession[]): string {+ return sessions.map(s => `pid ${s.pid}${s.application_name ? ` (${s.application_name})` : ''}, ${s.state ?? 'unknown state'}`+ + `${s.transaction_age_seconds != null ? `, transaction open ${s.transaction_age_seconds}s` : ''}`).join('; ');+}++/** The typed refusal for SQLSTATE 55P03 under the schema bound. */+export function schemaLockBlockedError(input: { step: string; timeoutMs: number; sessions: BlockingSession[] | null; sampledDuringWait: boolean }): OperationError {+ const { step, timeoutMs, sessions } = input;+ const holders = sessions === null ? 'The blocking sessions could not be sampled.'+ : sessions.length === 0 ? `No blocking session was found${input.sampledDuringWait ? ' at the sample' : ' after the cancel (it may have finished)'}.`+ : `Blocked by ${describe(sessions)}${input.sampledDuringWait ? '' : ' (sampled after the cancel)'}.`;+ const pids = sessions?.map(s => s.pid) ?? [];+ return opError('schema_lock_blocked',+ `Schema ${step} waited ${Math.round(timeoutMs / 1000)}s for a table lock another session holds, and stopped instead of hanging. ${holders} Query text is not shown.`,+ `Nothing was changed by the cancelled step; the schema is as it was. Find what holds the lock (an open transaction in another client, a stuck job): ${pids.length+ ? `the blocking pid(s) are ${pids.join(', ')}. Let that session finish or, with the user's agreement, end it with SELECT pg_terminate_backend(<pid>) on the database host.`+ : 'run SELECT pid, application_name, state FROM pg_stat_activity WHERE state LIKE \'idle in transaction%\' on the database host and let that session finish or, with the user\'s agreement, end it with SELECT pg_terminate_backend(<pid>).'} Then rerun the same gbrain command; a longer wait is GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS.`,+ { detail: step, docs: 'docs/ENGINES.md#schema-lock-blocked' });+}++/**+ * A one-backend connection beside the DDL backend for the blocker sample;+ * `null` when the engine has no URL to open one with (the sample is skipped).+ */+export function schemaDiagnosticConnection(url: string | undefined): SchemaLockTimeoutOpts['diagnostic'] {+ if (!url) return undefined;+ return async () => {+ const sql = postgres(url, { max: 1, connect_timeout: 10, prepare: false, onnotice: () => {}, connection: { application_name: 'gbrain-schema-lock-diagnostic' } });+ return { unsafe: (query: string, params?: unknown[]) => sql.unsafe(query, params as never), end: () => sql.end({ timeout: 5 }) };+ };+}++/**+ * Run `run` on `conn` under a session-level `lock_timeout`, restoring the+ * previous value afterwards. A lock timeout becomes `schema_lock_blocked`+ * with the blockers sampled from the diagnostic connection while the wait+ * was active; every other error propagates unchanged.+ */+export async function withSchemaLockTimeout<T>(conn: Queryable, run: () => Promise<T>, opts: SchemaLockTimeoutOpts): Promise<T> {+ const timeoutMs = resolveSchemaLockTimeoutMs(opts);+ const previous = String(((await conn.unsafe('SHOW lock_timeout')) as Array<{ lock_timeout: string }>)[0]?.lock_timeout ?? '0');+ await conn.unsafe(`SET lock_timeout = '${Math.max(1, Math.round(timeoutMs))}ms'`);+ const pid = Number(((await conn.unsafe('SELECT pg_backend_pid() AS pid')) as Array<{ pid: number | string }>)[0]?.pid);+ let sampled: BlockingSession[] | null | undefined;+ let sampling: Promise<void> | undefined;+ const sample = async () => {+ const diagnostic = await opts.diagnostic?.().catch(() => null);+ if (!diagnostic) { sampled = null; return; }+ try { sampled = await sampleBlockingSessions(diagnostic, pid); }+ catch { sampled = null; }+ finally { await diagnostic.end().catch(() => {}); }+ };+ const sampleAt = Math.min(opts.sampleAtMs ?? Math.floor(timeoutMs / 2), Math.max(0, timeoutMs - 50));+ const timer = opts.diagnostic ? setTimeout(() => { sampling = sample(); }, sampleAt) : undefined;+ try {+ return await run();+ } catch (error) {+ if (!isLockTimeoutError(error)) throw error;+ if (sampling) await sampling;+ const sampledDuringWait = sampled !== undefined;+ if (!sampledDuringWait) await sample();+ throw schemaLockBlockedError({ step: opts.step, timeoutMs, sessions: sampled ?? null, sampledDuringWait });+ } finally {+ if (timer) clearTimeout(timer);+ await conn.unsafe(`SET lock_timeout = '${previous.replace(/'/g, '')}'`).catch(() => {});+ }+}diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex c815c62cb4..0358f529c6 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1762,49 +1762,28 @@ CREATE TRIGGER minion_job_notify AFTER INSERT OR UPDATE OF status ON minion_jobsDO \$\$DECLAREhas_bypass BOOLEAN;+ target TEXT;BEGIN-- #1385: recognize superuser + inherited-role BYPASSRLS, not just the role's-- own rolbypassrls (alias \`pr\` avoids any plpgsql record-variable collision).SELECT EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) INTO has_bypass;IF has_bypass THEN- ALTER TABLE pages ENABLE ROW LEVEL SECURITY;- ALTER TABLE content_chunks ENABLE ROW LEVEL SECURITY;- ALTER TABLE links ENABLE ROW LEVEL SECURITY;- ALTER TABLE wanted_links ENABLE ROW LEVEL SECURITY;- ALTER TABLE tags ENABLE ROW LEVEL SECURITY;- ALTER TABLE raw_data ENABLE ROW LEVEL SECURITY;- ALTER TABLE timeline_entries ENABLE ROW LEVEL SECURITY;- ALTER TABLE page_versions ENABLE ROW LEVEL SECURITY;- ALTER TABLE ingest_log ENABLE ROW LEVEL SECURITY;- ALTER TABLE config ENABLE ROW LEVEL SECURITY;- ALTER TABLE files ENABLE ROW LEVEL SECURITY;- ALTER TABLE minion_jobs ENABLE ROW LEVEL SECURITY;- ALTER TABLE sources ENABLE ROW LEVEL SECURITY;- ALTER TABLE file_migration_ledger ENABLE ROW LEVEL SECURITY;- ALTER TABLE access_tokens ENABLE ROW LEVEL SECURITY;- ALTER TABLE mcp_request_log ENABLE ROW LEVEL SECURITY;- ALTER TABLE minion_inbox ENABLE ROW LEVEL SECURITY;- ALTER TABLE minion_attachments ENABLE ROW LEVEL SECURITY;- ALTER TABLE subagent_messages ENABLE ROW LEVEL SECURITY;- ALTER TABLE subagent_tool_executions ENABLE ROW LEVEL SECURITY;- ALTER TABLE subagent_rate_leases ENABLE ROW LEVEL SECURITY;- ALTER TABLE gbrain_cycle_locks ENABLE ROW LEVEL SECURITY;- ALTER TABLE dream_verdicts ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_candidates ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_capture_failures ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_takes_quality_runs ENABLE ROW LEVEL SECURITY;- -- v0.32.6 contradiction probe tables- ALTER TABLE eval_contradictions_cache ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_contradictions_runs ENABLE ROW LEVEL SECURITY;- -- v0.36.1.0 Hindsight calibration wave tables- ALTER TABLE calibration_profiles ENABLE ROW LEVEL SECURITY;- ALTER TABLE take_proposals ENABLE ROW LEVEL SECURITY;- ALTER TABLE take_grade_cache ENABLE ROW LEVEL SECURITY;- ALTER TABLE take_nudge_log ENABLE ROW LEVEL SECURITY;- -- v0.26 OAuth 2.1 tables- ALTER TABLE oauth_clients ENABLE ROW LEVEL SECURITY;- ALTER TABLE oauth_tokens ENABLE ROW LEVEL SECURITY;- ALTER TABLE oauth_codes ENABLE ROW LEVEL SECURITY;+ -- #5227 (W14 P1.6): conditional enables. ALTER TABLE ... ENABLE ROW LEVEL SECURITY takes an+ -- ACCESS EXCLUSIVE lock even when RLS is already on, so re-running this block on a live brain+ -- queued behind every open transaction; a table whose relrowsecurity is already set is skipped.+ FOREACH target IN ARRAY ARRAY[+ 'pages','content_chunks','links','wanted_links','tags','raw_data','timeline_entries',+ 'page_versions','ingest_log','config','files','minion_jobs','sources','file_migration_ledger',+ 'access_tokens','mcp_request_log','minion_inbox','minion_attachments','subagent_messages',+ 'subagent_tool_executions','subagent_rate_leases','gbrain_cycle_locks','dream_verdicts',+ 'eval_candidates','eval_capture_failures','eval_takes_quality_runs','eval_contradictions_cache',+ 'eval_contradictions_runs','calibration_profiles','take_proposals','take_grade_cache',+ 'take_nudge_log','oauth_clients','oauth_tokens','oauth_codes'] LOOP+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relrowsecurity) THEN+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);+ END IF;+ END LOOP;RAISE NOTICE 'RLS enabled on all tables (role % has BYPASSRLS)', current_user;ELSERAISE WARNING 'Skipping RLS: role % does not have BYPASSRLS privilege. Run as postgres role to enable.', current_user;@@ -2511,7 +2490,10 @@ BEGINFOREACH target IN ARRAY ARRAY['shared_skill_state','shared_skill_policies','shared_skill_packs','shared_skill_policy_audit','shared_skill_heads','shared_skill_revisions','shared_skill_revision_leases','shared_skill_members','shared_skill_delivery_batches','persistence_writer_protocols'] LOOP- EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relrowsecurity) THEN+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ END IF;END LOOP;END IF;END \$\$;@@ -2576,17 +2558,17 @@ CREATE TABLE IF NOT EXISTS decide_state ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decision_receipts ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decision_receipts' AND c.relrowsecurity) THEN ALTER TABLE decision_receipts ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_spend ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_spend' AND c.relrowsecurity) THEN ALTER TABLE decide_spend ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_state ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_state' AND c.relrowsecurity) THEN ALTER TABLE decide_state ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -2620,7 +2602,7 @@ CREATE TABLE IF NOT EXISTS decide_calibrations (CREATE INDEX IF NOT EXISTS decide_calibrations_lookup_idx ON decide_calibrations (slot, provider, model_resolved, created_at DESC);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_calibrations ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_calibrations' AND c.relrowsecurity) THEN ALTER TABLE decide_calibrations ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -2656,12 +2638,12 @@ CREATE TABLE IF NOT EXISTS decide_sweep_deferred ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_proposals' AND c.relrowsecurity) THEN ALTER TABLE decide_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_sweep_deferred' AND c.relrowsecurity) THEN ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;@@ -2699,12 +2681,12 @@ CREATE TABLE IF NOT EXISTS decide_review_proposals (CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_review_queue' AND c.relrowsecurity) THEN ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_review_proposals' AND c.relrowsecurity) THEN ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;-- END GENERATED from src/core/ai/decide/schema.ts (DECIDE_SCHEMA_SQL)@@ -2726,7 +2708,7 @@ CREATE TABLE IF NOT EXISTS fact_relink_attempts (CREATE INDEX IF NOT EXISTS fact_relink_attempts_outcome_idx ON fact_relink_attempts (source_id, outcome, attempted_at);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE fact_relink_attempts ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'fact_relink_attempts' AND c.relrowsecurity) THEN ALTER TABLE fact_relink_attempts ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;-- END GENERATED from src/core/facts/relink-schema.ts (FACT_RELINK_SCHEMA_SQL)@@ -2753,7 +2735,7 @@ CREATE INDEX IF NOT EXISTS link_transitions_relationship_idx ON link_transitionsCREATE INDEX IF NOT EXISTS link_transitions_origin_idx ON link_transitions (origin_page_id);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_transitions ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_transitions' AND c.relrowsecurity) THEN ALTER TABLE link_transitions ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS link_relationships (@@ -2781,7 +2763,7 @@ CREATE INDEX IF NOT EXISTS link_relationships_to_idx ON link_relationships (to_pCREATE INDEX IF NOT EXISTS link_relationships_source_idx ON link_relationships (source_id, status_now);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_relationships ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_relationships' AND c.relrowsecurity) THEN ALTER TABLE link_relationships ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS link_edge_proposals (@@ -2808,7 +2790,7 @@ CREATE TABLE IF NOT EXISTS link_edge_proposals (CREATE INDEX IF NOT EXISTS link_edge_proposals_status_idx ON link_edge_proposals (source_id, status, created_at);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_edge_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_edge_proposals' AND c.relrowsecurity) THEN ALTER TABLE link_edge_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE SEQUENCE IF NOT EXISTS graph_generation_seq;@@ -2831,7 +2813,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'core_edit_notices' AND c.relrowsecurity) THEN ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;-- END GENERATED from src/core/core-memory-schema.ts (CORE_EDIT_NOTICES_SCHEMA_SQL)@@ -2851,7 +2833,7 @@ CREATE TABLE IF NOT EXISTS fact_purges ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE fact_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'fact_purges' AND c.relrowsecurity) THEN ALTER TABLE fact_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS take_purges (@@ -2864,7 +2846,7 @@ CREATE TABLE IF NOT EXISTS take_purges ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE take_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'take_purges' AND c.relrowsecurity) THEN ALTER TABLE take_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS page_purges (@@ -2877,7 +2859,7 @@ CREATE TABLE IF NOT EXISTS page_purges ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE page_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'page_purges' AND c.relrowsecurity) THEN ALTER TABLE page_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS derivation_inputs (@@ -2892,7 +2874,7 @@ CREATE TABLE IF NOT EXISTS derivation_inputs (CREATE INDEX IF NOT EXISTS idx_derivation_inputs_input ON derivation_inputs (input_table, input_id);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE derivation_inputs ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'derivation_inputs' AND c.relrowsecurity) THEN ALTER TABLE derivation_inputs ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;CREATE TABLE IF NOT EXISTS needs_rederive (@@ -2906,7 +2888,7 @@ CREATE TABLE IF NOT EXISTS needs_rederive ();DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE needs_rederive ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'needs_rederive' AND c.relrowsecurity) THEN ALTER TABLE needs_rederive ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;-- END GENERATED from src/core/facts/purge-schema.ts (MEMORY_PURGE_SCHEMA_SQL)@@ -2961,8 +2943,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS write_gate_holds_dedupe_idx ON write_gate_holdCREATE INDEX IF NOT EXISTS write_gate_holds_status_idx ON write_gate_holds (status, source_id, id);DO \$rls\$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY;- ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_receipts' AND c.relrowsecurity) THEN ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY; END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_holds' AND c.relrowsecurity) THEN ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY; END IF;END IF;END \$rls\$;-- END GENERATED from src/core/write-gate-schema.ts (WRITE_GATE_SCHEMA_SQL)diff --git a/src/core/shared-skills/access-schema.ts b/src/core/shared-skills/access-schema.tsindex e7eadcf611..da20ea6e78 100644--- a/src/core/shared-skills/access-schema.ts+++ b/src/core/shared-skills/access-schema.ts@@ -7,7 +7,10 @@ BEGINFOREACH target IN ARRAY ARRAY['shared_skill_state','shared_skill_policies','shared_skill_packs','shared_skill_policy_audit','shared_skill_heads','shared_skill_revisions','shared_skill_revision_leases','shared_skill_members','shared_skill_delivery_batches','persistence_writer_protocols'] LOOP- EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relrowsecurity) THEN+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ END IF;END LOOP;END IF;END $$;`;diff --git a/src/core/write-gate-schema.ts b/src/core/write-gate-schema.tsindex 9261da9161..7fe329ab47 100644--- a/src/core/write-gate-schema.ts+++ b/src/core/write-gate-schema.ts@@ -71,8 +71,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS write_gate_holds_dedupe_idx ON write_gate_holdCREATE INDEX IF NOT EXISTS write_gate_holds_status_idx ON write_gate_holds (status, source_id, id);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY;- ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_receipts' AND c.relrowsecurity) THEN ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY; END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_holds' AND c.relrowsecurity) THEN ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;`;diff --git a/src/schema.sql b/src/schema.sqlindex 61285eccc9..9e4b6332f9 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1758,49 +1758,28 @@ CREATE TRIGGER minion_job_notify AFTER INSERT OR UPDATE OF status ON minion_jobsDO $$DECLAREhas_bypass BOOLEAN;+ target TEXT;BEGIN-- #1385: recognize superuser + inherited-role BYPASSRLS, not just the role's-- own rolbypassrls (alias `pr` avoids any plpgsql record-variable collision).SELECT EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) INTO has_bypass;IF has_bypass THEN- ALTER TABLE pages ENABLE ROW LEVEL SECURITY;- ALTER TABLE content_chunks ENABLE ROW LEVEL SECURITY;- ALTER TABLE links ENABLE ROW LEVEL SECURITY;- ALTER TABLE wanted_links ENABLE ROW LEVEL SECURITY;- ALTER TABLE tags ENABLE ROW LEVEL SECURITY;- ALTER TABLE raw_data ENABLE ROW LEVEL SECURITY;- ALTER TABLE timeline_entries ENABLE ROW LEVEL SECURITY;- ALTER TABLE page_versions ENABLE ROW LEVEL SECURITY;- ALTER TABLE ingest_log ENABLE ROW LEVEL SECURITY;- ALTER TABLE config ENABLE ROW LEVEL SECURITY;- ALTER TABLE files ENABLE ROW LEVEL SECURITY;- ALTER TABLE minion_jobs ENABLE ROW LEVEL SECURITY;- ALTER TABLE sources ENABLE ROW LEVEL SECURITY;- ALTER TABLE file_migration_ledger ENABLE ROW LEVEL SECURITY;- ALTER TABLE access_tokens ENABLE ROW LEVEL SECURITY;- ALTER TABLE mcp_request_log ENABLE ROW LEVEL SECURITY;- ALTER TABLE minion_inbox ENABLE ROW LEVEL SECURITY;- ALTER TABLE minion_attachments ENABLE ROW LEVEL SECURITY;- ALTER TABLE subagent_messages ENABLE ROW LEVEL SECURITY;- ALTER TABLE subagent_tool_executions ENABLE ROW LEVEL SECURITY;- ALTER TABLE subagent_rate_leases ENABLE ROW LEVEL SECURITY;- ALTER TABLE gbrain_cycle_locks ENABLE ROW LEVEL SECURITY;- ALTER TABLE dream_verdicts ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_candidates ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_capture_failures ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_takes_quality_runs ENABLE ROW LEVEL SECURITY;- -- v0.32.6 contradiction probe tables- ALTER TABLE eval_contradictions_cache ENABLE ROW LEVEL SECURITY;- ALTER TABLE eval_contradictions_runs ENABLE ROW LEVEL SECURITY;- -- v0.36.1.0 Hindsight calibration wave tables- ALTER TABLE calibration_profiles ENABLE ROW LEVEL SECURITY;- ALTER TABLE take_proposals ENABLE ROW LEVEL SECURITY;- ALTER TABLE take_grade_cache ENABLE ROW LEVEL SECURITY;- ALTER TABLE take_nudge_log ENABLE ROW LEVEL SECURITY;- -- v0.26 OAuth 2.1 tables- ALTER TABLE oauth_clients ENABLE ROW LEVEL SECURITY;- ALTER TABLE oauth_tokens ENABLE ROW LEVEL SECURITY;- ALTER TABLE oauth_codes ENABLE ROW LEVEL SECURITY;+ -- #5227 (W14 P1.6): conditional enables. ALTER TABLE ... ENABLE ROW LEVEL SECURITY takes an+ -- ACCESS EXCLUSIVE lock even when RLS is already on, so re-running this block on a live brain+ -- queued behind every open transaction; a table whose relrowsecurity is already set is skipped.+ FOREACH target IN ARRAY ARRAY[+ 'pages','content_chunks','links','wanted_links','tags','raw_data','timeline_entries',+ 'page_versions','ingest_log','config','files','minion_jobs','sources','file_migration_ledger',+ 'access_tokens','mcp_request_log','minion_inbox','minion_attachments','subagent_messages',+ 'subagent_tool_executions','subagent_rate_leases','gbrain_cycle_locks','dream_verdicts',+ 'eval_candidates','eval_capture_failures','eval_takes_quality_runs','eval_contradictions_cache',+ 'eval_contradictions_runs','calibration_profiles','take_proposals','take_grade_cache',+ 'take_nudge_log','oauth_clients','oauth_tokens','oauth_codes'] LOOP+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relrowsecurity) THEN+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);+ END IF;+ END LOOP;RAISE NOTICE 'RLS enabled on all tables (role % has BYPASSRLS)', current_user;ELSERAISE WARNING 'Skipping RLS: role % does not have BYPASSRLS privilege. Run as postgres role to enable.', current_user;@@ -2507,7 +2486,10 @@ BEGINFOREACH target IN ARRAY ARRAY['shared_skill_state','shared_skill_policies','shared_skill_packs','shared_skill_policy_audit','shared_skill_heads','shared_skill_revisions','shared_skill_revision_leases','shared_skill_members','shared_skill_delivery_batches','persistence_writer_protocols'] LOOP- EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relrowsecurity) THEN+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',target);+ END IF;END LOOP;END IF;END $$;@@ -2572,17 +2554,17 @@ CREATE TABLE IF NOT EXISTS decide_state ();DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decision_receipts ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decision_receipts' AND c.relrowsecurity) THEN ALTER TABLE decision_receipts ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_spend ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_spend' AND c.relrowsecurity) THEN ALTER TABLE decide_spend ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_state ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_state' AND c.relrowsecurity) THEN ALTER TABLE decide_state ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;@@ -2616,7 +2598,7 @@ CREATE TABLE IF NOT EXISTS decide_calibrations (CREATE INDEX IF NOT EXISTS decide_calibrations_lookup_idx ON decide_calibrations (slot, provider, model_resolved, created_at DESC);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_calibrations ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_calibrations' AND c.relrowsecurity) THEN ALTER TABLE decide_calibrations ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;@@ -2652,12 +2634,12 @@ CREATE TABLE IF NOT EXISTS decide_sweep_deferred ();DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_proposals' AND c.relrowsecurity) THEN ALTER TABLE decide_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_sweep_deferred' AND c.relrowsecurity) THEN ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;@@ -2695,12 +2677,12 @@ CREATE TABLE IF NOT EXISTS decide_review_proposals (CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_review_queue' AND c.relrowsecurity) THEN ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'decide_review_proposals' AND c.relrowsecurity) THEN ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;-- END GENERATED from src/core/ai/decide/schema.ts (DECIDE_SCHEMA_SQL)@@ -2722,7 +2704,7 @@ CREATE TABLE IF NOT EXISTS fact_relink_attempts (CREATE INDEX IF NOT EXISTS fact_relink_attempts_outcome_idx ON fact_relink_attempts (source_id, outcome, attempted_at);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE fact_relink_attempts ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'fact_relink_attempts' AND c.relrowsecurity) THEN ALTER TABLE fact_relink_attempts ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;-- END GENERATED from src/core/facts/relink-schema.ts (FACT_RELINK_SCHEMA_SQL)@@ -2749,7 +2731,7 @@ CREATE INDEX IF NOT EXISTS link_transitions_relationship_idx ON link_transitionsCREATE INDEX IF NOT EXISTS link_transitions_origin_idx ON link_transitions (origin_page_id);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_transitions ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_transitions' AND c.relrowsecurity) THEN ALTER TABLE link_transitions ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE TABLE IF NOT EXISTS link_relationships (@@ -2777,7 +2759,7 @@ CREATE INDEX IF NOT EXISTS link_relationships_to_idx ON link_relationships (to_pCREATE INDEX IF NOT EXISTS link_relationships_source_idx ON link_relationships (source_id, status_now);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_relationships ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_relationships' AND c.relrowsecurity) THEN ALTER TABLE link_relationships ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE TABLE IF NOT EXISTS link_edge_proposals (@@ -2804,7 +2786,7 @@ CREATE TABLE IF NOT EXISTS link_edge_proposals (CREATE INDEX IF NOT EXISTS link_edge_proposals_status_idx ON link_edge_proposals (source_id, status, created_at);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE link_edge_proposals ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'link_edge_proposals' AND c.relrowsecurity) THEN ALTER TABLE link_edge_proposals ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE SEQUENCE IF NOT EXISTS graph_generation_seq;@@ -2827,7 +2809,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'core_edit_notices' AND c.relrowsecurity) THEN ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;-- END GENERATED from src/core/core-memory-schema.ts (CORE_EDIT_NOTICES_SCHEMA_SQL)@@ -2847,7 +2829,7 @@ CREATE TABLE IF NOT EXISTS fact_purges ();DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE fact_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'fact_purges' AND c.relrowsecurity) THEN ALTER TABLE fact_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE TABLE IF NOT EXISTS take_purges (@@ -2860,7 +2842,7 @@ CREATE TABLE IF NOT EXISTS take_purges ();DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE take_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'take_purges' AND c.relrowsecurity) THEN ALTER TABLE take_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE TABLE IF NOT EXISTS page_purges (@@ -2873,7 +2855,7 @@ CREATE TABLE IF NOT EXISTS page_purges ();DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE page_purges ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'page_purges' AND c.relrowsecurity) THEN ALTER TABLE page_purges ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE TABLE IF NOT EXISTS derivation_inputs (@@ -2888,7 +2870,7 @@ CREATE TABLE IF NOT EXISTS derivation_inputs (CREATE INDEX IF NOT EXISTS idx_derivation_inputs_input ON derivation_inputs (input_table, input_id);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE derivation_inputs ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'derivation_inputs' AND c.relrowsecurity) THEN ALTER TABLE derivation_inputs ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;CREATE TABLE IF NOT EXISTS needs_rederive (@@ -2902,7 +2884,7 @@ CREATE TABLE IF NOT EXISTS needs_rederive ();DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE needs_rederive ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'needs_rederive' AND c.relrowsecurity) THEN ALTER TABLE needs_rederive ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;-- END GENERATED from src/core/facts/purge-schema.ts (MEMORY_PURGE_SCHEMA_SQL)@@ -2957,8 +2939,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS write_gate_holds_dedupe_idx ON write_gate_holdCREATE INDEX IF NOT EXISTS write_gate_holds_status_idx ON write_gate_holds (status, source_id, id);DO $rls$ BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY;- ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_receipts' AND c.relrowsecurity) THEN ALTER TABLE write_gate_receipts ENABLE ROW LEVEL SECURITY; END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = 'write_gate_holds' AND c.relrowsecurity) THEN ALTER TABLE write_gate_holds ENABLE ROW LEVEL SECURITY; END IF;END IF;END $rls$;-- END GENERATED from src/core/write-gate-schema.ts (WRITE_GATE_SCHEMA_SQL)diff --git a/test/e2e/init-schema-lock-blocked.test.ts b/test/e2e/init-schema-lock-blocked.test.tsnew file mode 100644index 0000000000..abe8e0db2d--- /dev/null+++ b/test/e2e/init-schema-lock-blocked.test.ts@@ -0,0 +1,106 @@+/**+ * #5227 (W14 P1.6, [R8]): `gbrain init` / `upgrade` no longer hang behind an+ * open transaction. The schema replay runs under a session-level+ * `lock_timeout` on the reserved DDL backend (restored afterwards), SQLSTATE+ * 55P03 becomes the typed `schema_lock_blocked` refusal naming the blocking+ * sessions sampled while the wait was active (query text redacted), a+ * transaction-wrapped migration binds the same wait with SET LOCAL, and the+ * RLS block skips tables whose RLS is already on, so a re-run takes no+ * ACCESS EXCLUSIVE lock for them.+ *+ * Postgres only: lock semantics do not exist on PGLite. Runs in the direct and+ * PgBouncer E2E passes; under the pooler the restored setting must never leak+ * to another pooled client.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import { PostgresEngine, getPostgresSchema } from '../../src/core/postgres-engine.ts';+import { runMigrationSQL } from '../../src/core/migrate.ts';+import { withSchemaLockTimeout } from '../../src/core/postgres-engine/schema-lock-timeout.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+if (!databaseUrl) throw new Error('DATABASE_URL is required for the E2E tier');++describe('#5227 schema DDL waits are bounded and typed', () => {+ let engine: PostgresEngine, url: string, close: () => Promise<void>;+ beforeAll(async () => { ({ engine, databaseUrl: url, close } = await isolatedPersistencePostgres(databaseUrl!, 'instance', 4)); }, 180_000);+ afterAll(async () => { await close(); });++ /** An open transaction holding a SHARE lock on `pages` from another session, named so the refusal can be checked for it. */+ async function blocker(run: (holder: ReturnType<typeof postgres>) => Promise<void>) {+ const holder = postgres(url, { max: 1, prepare: false, onnotice: () => {}, connection: { application_name: 'gbrain-test-blocker' } });+ try {+ await holder.unsafe('BEGIN');+ await holder.unsafe('LOCK TABLE pages IN SHARE MODE');+ await run(holder);+ } finally {+ await holder.unsafe('ROLLBACK').catch(() => {});+ await holder.end({ timeout: 5 });+ }+ }++ test('init under a blocker fails typed within the injected timeout, naming the blocking session without its query text', () => blocker(async () => {+ const started = Date.now();+ const error = await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '2' }, () => engine.initSchema()).catch((e: Error) => e) as Error & Record<string, string>;+ expect(Date.now() - started).toBeLessThan(20_000);+ expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'replay' });+ expect(error.message).toContain('gbrain-test-blocker');+ expect(error.message).toMatch(/Blocked by pid \d+/);+ expect(error.message).toContain('idle in transaction');+ expect(error.message).not.toContain('sampled after the cancel');+ expect(error.message).not.toContain('LOCK TABLE');+ expect(error.suggestion).toContain('pg_terminate_backend');+ expect(error.suggestion).not.toContain('LOCK TABLE');+ }), 60_000);++ test('the session lock_timeout is set on the DDL connection and restored on release; the pool default is unchanged', async () => {+ const seen: string[] = [];+ const conn = { unsafe: async (query: string, params?: unknown[]) => { const rows = await engine.executeRaw(query, params as unknown[]); if (query === 'SHOW lock_timeout') seen.push((rows[0] as { lock_timeout: string }).lock_timeout); return rows; } };+ await engine.executeRaw("SET lock_timeout = '0'");+ await engine.withReservedConnection(async reserved => {+ const q = { unsafe: async (query: string, params?: unknown[]) => reserved.executeRaw(query, params as unknown[]) };+ const before = (await reserved.executeRaw('SHOW lock_timeout'))[0] as { lock_timeout: string };+ let during = '';+ await withSchemaLockTimeout(q, async () => { during = ((await reserved.executeRaw('SHOW lock_timeout'))[0] as { lock_timeout: string }).lock_timeout; }, { step: 'probe', timeoutMs: 1500 });+ const after = (await reserved.executeRaw('SHOW lock_timeout'))[0] as { lock_timeout: string };+ expect(during).toBe('1500ms');+ expect(after.lock_timeout).toBe(before.lock_timeout);+ }, { selfContained: true });+ expect(((await conn.unsafe('SHOW lock_timeout'))[0] as { lock_timeout: string }).lock_timeout).toBe('0');+ // A second, independent client sees the server default: nothing leaked past the connection that set it.+ const other = postgres(url, { max: 1, prepare: false, onnotice: () => {} });+ try { expect(((await other.unsafe('SHOW lock_timeout'))[0] as unknown as { lock_timeout: string }).lock_timeout).toBe('0'); }+ finally { await other.end({ timeout: 5 }); }+ }, 60_000);++ test('a transaction-wrapped migration under a blocker fails with the same typed code (SET LOCAL inside the real transaction)', () => blocker(async () => {+ const migration = { version: 999_999, name: 'w14_p16_probe', sql: 'ALTER TABLE pages ADD COLUMN IF NOT EXISTS w14_probe_column INTEGER' };+ const error = await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => runMigrationSQL(engine, migration, migration.sql)).catch((e: Error) => e) as Error & Record<string, string>;+ expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'migration v999999' });+ expect((await engine.executeRaw("SELECT 1 FROM information_schema.columns WHERE table_name='pages' AND column_name='w14_probe_column'")).length).toBe(0);+ }), 60_000);++ test('the RLS block is idempotent: with RLS already on, a re-run issues no ENABLE and does not wait behind an open reader', () => blocker(async () => {+ const schema = getPostgresSchema(1024, 'probe-model');+ const start = schema.indexOf('DO $$\nDECLARE\n has_bypass BOOLEAN;');+ const end = schema.indexOf('END $$;', start) + 'END $$;'.length;+ const block = schema.slice(start, end);+ expect(block).toContain('relrowsecurity');+ expect(block).toContain("'pages'");+ const before = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind='r' AND c.relrowsecurity");+ // The blocker holds SHARE on pages: an unconditional ENABLE on pages would need ACCESS EXCLUSIVE and hit the 1 s bound.+ await engine.withReservedConnection(async reserved => {+ await withSchemaLockTimeout({ unsafe: (query: string) => reserved.executeRaw(query) }, () => reserved.executeRaw(block), { step: 'rls', timeoutMs: 1000 });+ }, { selfContained: true });+ const after = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind='r' AND c.relrowsecurity");+ expect(after[0].n).toBe(before[0].n);+ }), 60_000);++ test('an unconditional ENABLE on pages would have blocked (the forced probe the conditional block avoids)', () => blocker(async () => {+ const error = await engine.withReservedConnection(async reserved => withSchemaLockTimeout({ unsafe: (query: string) => reserved.executeRaw(query) },+ () => reserved.executeRaw('ALTER TABLE pages ENABLE ROW LEVEL SECURITY'), { step: 'rls', timeoutMs: 1000 }), { selfContained: true }).catch((e: Error) => e) as Error & Record<string, string>;+ expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'rls' });+ }), 60_000);+});diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.tsindex f0d5a0981f..b55f00e06d 100644--- a/test/e2e/mechanical.test.ts+++ b/test/e2e/mechanical.test.ts@@ -23,6 +23,8 @@ import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';import { configureGateway } from '../../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { runMigrationSQL } from '../../src/core/migrate.ts';+import { v024 } from '../../src/core/schema-migrations/v024-rls-backfill-missing-tables.ts';// Skip all E2E tests if no database is configuredconst skip = !hasDatabase();@@ -51,6 +53,30 @@ afterAll(() => {try { if (_tmpHome) rmSync(_tmpHome, { recursive: true, force: true }); } catch { /* best-effort */ }});+/**+ * #5227 (W14 P1.6): spawn `gbrain init` with a budget. When the child is still+ * running at half the budget, dump pg_stat_activity (pid, state, wait event,+ * transaction age, application; never query text) to stderr, so a hang behind+ * a lock shows its blocker instead of a bare exit 143. Returns the spawnSync+ * shape the call sites already read.+ */+async function spawnInit(input: { cmd: string[]; cwd: string; env: Record<string, string | undefined>; timeout: number }): Promise<{ exitCode: number; stdout: Uint8Array; stderr: Uint8Array }> {+ const child = Bun.spawn({ cmd: input.cmd, cwd: input.cwd, env: input.env as Record<string, string>, stdout: 'pipe', stderr: 'pipe' });+ let done = false;+ const probe = setTimeout(async () => {+ if (done) return;+ try {+ const rows = await getConn().unsafe(`SELECT pid, state, wait_event_type, application_name, EXTRACT(EPOCH FROM now() - xact_start)::int AS xact_age_s,+ pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() ORDER BY pid`);+ process.stderr.write(`[spawnInit] child still running at half its ${input.timeout}ms budget; pg_stat_activity:\n${JSON.stringify(rows, null, 1)}\n`);+ } catch (error) { process.stderr.write(`[spawnInit] pg_stat_activity probe failed: ${error instanceof Error ? error.message : String(error)}\n`); }+ }, Math.floor(input.timeout / 2));+ const kill = setTimeout(() => { if (!done) child.kill(); }, input.timeout);+ const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).arrayBuffer(), new Response(child.stderr).arrayBuffer(), child.exited]);+ done = true; clearTimeout(probe); clearTimeout(kill);+ return { exitCode: exitCode ?? -1, stdout: new Uint8Array(stdout), stderr: new Uint8Array(stderr) };+}+function makeCtx(opts: { remote?: boolean; storage?: { backend: 'local'; localPath: string } } = {},): OperationContext {@@ -848,14 +874,14 @@ describeE2E('E2E: Setup Journey', () => {const cliCwd = join(import.meta.dir, '../..');const cliEnv = () => ({ ...process.env, DATABASE_URL: process.env.DATABASE_URL! });- test('gbrain init --non-interactive connects and initializes', () => {+ test('gbrain init --non-interactive connects and initializes', async () => {// v0.37.10.0: pass --embedding-model explicitly. Tier-1 CI runs without// any embedding-provider env var, and the v0.37 fail-loud-no-key gate// (D3) would otherwise exit 1 here. The provider is offline-resolved// (preflight validates dim against recipe; no HTTP call), so this works// without a real API key. After this init writes config, subsequent// inits in the file honor persisted config per D5 (no flag needed).- const result = Bun.spawnSync({+ const result = await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!,'--embedding-model', LEGACY_EMBEDDING_CONFIG.embedding_model,'--embedding-dimensions', String(LEGACY_EMBEDDING_CONFIG.embedding_dimensions)],@@ -920,11 +946,11 @@ describeE2E('E2E: Setup Journey', () => {describeE2E('E2E: Init Edge Cases', () => {afterAll(teardownDB);- test('init --non-interactive without URL fails gracefully', () => {+ test('init --non-interactive without URL fails gracefully', async () => {const env = { ...process.env };delete env.DATABASE_URL;delete env.GBRAIN_DATABASE_URL;- const result = Bun.spawnSync({+ const result = await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive'],cwd: join(import.meta.dir, '../..'),env,@@ -1120,7 +1146,7 @@ describeE2E('E2E: RLS Verification', () => {const conn = getConn();const tbl = `gbrain_rls_plain_pg_${suffix}`;try {- Bun.spawnSync({+ await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],cwd: cliCwd, env: cliEnv(), timeout: 15_000,});@@ -1151,7 +1177,7 @@ describeE2E('E2E: RLS Verification', () => {// (e.g. while debugging) and creates a public table without RLS.// doctor's existing rls check must still flag it. The new// rls_event_trigger check warns separately about the missing trigger.- Bun.spawnSync({+ await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],cwd: cliCwd, env: cliEnv(), timeout: 15_000,});@@ -1194,7 +1220,7 @@ describeE2E('E2E: RLS Verification', () => {await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);await conn.unsafe(`COMMENT ON TABLE public.${tbl} IS 'GBRAIN:RLS_EXEMPT reason=e2e test fixture, anon-readable ok'`);- Bun.spawnSync({+ await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],cwd: cliCwd, env: cliEnv(), timeout: 15_000,});@@ -1222,7 +1248,7 @@ describeE2E('E2E: RLS Verification', () => {// Missing the `reason=<...>` segment — prefix alone is not enough.await conn.unsafe(`COMMENT ON TABLE public.${tbl} IS 'GBRAIN:RLS_EXEMPT'`);- Bun.spawnSync({+ await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],cwd: cliCwd, env: cliEnv(), timeout: 15_000,});@@ -1249,7 +1275,7 @@ describeE2E('E2E: RLS Verification', () => {await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);await conn.unsafe(`COMMENT ON TABLE public.${tbl} IS 'Regular docs comment, not an exemption'`);- Bun.spawnSync({+ await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],cwd: cliCwd, env: cliEnv(), timeout: 15_000,});@@ -1280,50 +1306,25 @@ describeE2E('E2E: RLS Verification', () => {// same failure forever.test('v24 self-heals when budget_ledger + budget_reservations are missing', async () => {const conn = getConn();- let priorVersion: string | null = null;try {- // Capture current version so we can restore after the test.- const verRows = await conn.unsafe(`SELECT value FROM config WHERE key = 'version'`);- priorVersion = (verRows[0] as any)?.value ?? null;-// Simulate an operator who dropped the budget_* tables for any reason// (cleanup, migration from an older gbrain, etc).await conn.unsafe(`DROP TABLE IF EXISTS public.budget_ledger CASCADE`);await conn.unsafe(`DROP TABLE IF EXISTS public.budget_reservations CASCADE`);- // Roll the version back to 23 so v24 re-runs on the next initSchema.- // UPSERT so this works whether the key exists or not.- await conn.unsafe(`- INSERT INTO config (key, value) VALUES ('version', '23')- ON CONFLICT (key) DO UPDATE SET value = '23'- `);-- // Re-trigger initSchema via the CLI. With the guard, this should- // apply v24 cleanly and advance version to 24. Without the guard,- // this would error out with 42P01 and leave version at 23.- const result = Bun.spawnSync({- cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],- cwd: cliCwd, env: cliEnv(), timeout: 30_000,- });- const stdout = new TextDecoder().decode(result.stdout);- const stderr = new TextDecoder().decode(result.stderr);-- // Must succeed — no 42P01, no transaction rollback.- expect(result.exitCode).toBe(0);- expect(stderr + stdout).not.toMatch(/42P01|does not exist.*budget/i);-- // Version must have advanced PAST 24. Since v0.18.1, v25-v29 (v0.19.0- // + v0.21.0 Cathedral II) and v30 (OAuth) have shipped. init runs every- // pending migration, so after rolling back to 23 the version advances- // to LATEST_VERSION. The test's intent is to prove v24 didn't crash on- // missing budget_* tables — assert version >= 24.- const afterRows = await conn.unsafe(`SELECT value FROM config WHERE key = 'version'`);- const finalVersion = parseInt((afterRows[0] as any).value, 10);- expect(finalVersion).toBeGreaterThanOrEqual(24);-- // The tables stayed dropped (v12 didn't re-run because current=23 > 12- // was already true before this test ran). That's intentional — we're- // proving v24 doesn't require those tables to exist.+ // #5227 (W14 P1.6): call the migration handler directly instead of+ // spawning `gbrain init`. The spawn replayed schema.sql plus every+ // pending migration on a 30 s budget and timed out whenever another+ // test's open transaction held a table lock, which is the bug the+ // lock_timeout work fixes; it also proved nothing about v24 that the+ // handler call does not. runMigrationSQL is the exact path initSchema+ // takes for a transaction-wrapped migration. With the guard, v24+ // applies cleanly; without it, this rejects with 42P01.+ await runMigrationSQL(getEngine(), v024, v024.sql);++ // The tables stayed dropped: v24 skipped them instead of failing, and+ // nothing else re-created them. That's intentional — we're proving+ // v24 doesn't require those tables to exist.const tblRows = await conn.unsafe(`SELECT tablename FROM pg_tablesWHERE schemaname = 'public'@@ -1364,14 +1365,6 @@ describeE2E('E2E: RLS Verification', () => {// RLS" assertion earlier in this block stays green if re-run.await conn.unsafe(`ALTER TABLE budget_ledger ENABLE ROW LEVEL SECURITY`);await conn.unsafe(`ALTER TABLE budget_reservations ENABLE ROW LEVEL SECURITY`);- // Restore version so we don't leave the DB at a weird state for- // subsequent test blocks.- if (priorVersion !== null) {- await conn.unsafe(- `UPDATE config SET value = $1 WHERE key = 'version'`,- [priorVersion],- );- }}}, 60_000);});@@ -1421,12 +1414,12 @@ describeE2E('E2E: Doctor Command', () => {GBRAIN_HOME: gbrainHome,});- test('gbrain doctor exits 0 on healthy DB', () => {+ test('gbrain doctor exits 0 on healthy DB', async () => {// Init first so config exists for CLI. Pin --embedding-model explicitly// so the spawned doctor doesn't pick a different default (e.g. Voyage-1024d// when VOYAGE_API_KEY is in env) that mismatches the fixture's// 1536d schema. Mirrors the same pattern in 'Setup Journey'.- const init = Bun.spawnSync({+ const init = await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive','--url', doctorUrl,'--embedding-model', LEGACY_EMBEDDING_CONFIG.embedding_model,@@ -1487,8 +1480,8 @@ describeE2E('E2E: Parallel Import', () => {const cliCwd = join(import.meta.dir, '../..');const cliEnv = () => ({ ...process.env, DATABASE_URL: process.env.DATABASE_URL!, GBRAIN_DATABASE_URL: process.env.DATABASE_URL! });- function initCli() {- Bun.spawnSync({+ async function initCli() {+ await spawnInit({cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],cwd: cliCwd, env: cliEnv(), timeout: 15_000,});@@ -1501,7 +1494,7 @@ describeE2E('E2E: Parallel Import', () => {test('sequential baseline: import all fixtures', async () => {await setupDB();- initCli();+ await initCli();const result = Bun.spawnSync({cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', FIXTURES_PATH],cwd: cliCwd,@@ -1523,7 +1516,7 @@ describeE2E('E2E: Parallel Import', () => {test('parallel import with --workers 2 matches sequential page count', async () => {await setupDB();- initCli();+ await initCli();const result = Bun.spawnSync({cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', '--workers', '2', FIXTURES_PATH],cwd: cliCwd,@@ -1568,7 +1561,7 @@ describeE2E('E2E: Parallel Import', () => {test('parallel import with --workers 4 also works', async () => {await setupDB();- initCli();+ await initCli();const result = Bun.spawnSync({cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', '--workers', '4', FIXTURES_PATH],cwd: cliCwd,diff --git a/test/migrate-retry.test.ts b/test/migrate-retry.test.tsindex ed70a0af1d..211ab336f8 100644--- a/test/migrate-retry.test.ts+++ b/test/migrate-retry.test.ts@@ -96,6 +96,29 @@ describe('runInitSchemaWithRetry', () => {expect(logs[0]).toContain('statement_timeout');});+ test('#5227: a schema_lock_blocked refusal (or raw 55P03) retries with the short lock backoff, bounded', async () => {+ let initCalls = 0;+ const sleeps: number[] = [];+ const logs: string[] = [];+ const blocked = Object.assign(new Error('Schema replay waited 1s for a table lock another session holds'), { code: 'schema_lock_blocked' });+ // Blocker released after attempt 1: success on attempt 2.+ const result = await runInitSchemaWithRetry(fakeEngine, {+ maxAttempts: 5, backoffMs: 15_000, lockBackoffMs: 250, log: line => logs.push(line),+ _hooks: { sleep: async ms => { sleeps.push(ms); }, initSchema: async () => { initCalls++; if (initCalls < 2) throw blocked; } },+ });+ expect(result.attempts).toBe(2);+ expect(sleeps).toEqual([250]);+ expect(logs[0]).toContain('schema_lock_blocked');+ // Never released: a bounded failure with the typed error, not a hang.+ let calls = 0; const waits: number[] = [];+ await expect(runInitSchemaWithRetry(fakeEngine, {+ maxAttempts: 3, backoffMs: 15_000, lockBackoffMs: 250, log: () => {},+ _hooks: { sleep: async ms => { waits.push(ms); }, initSchema: async () => { calls++; throw { code: '55P03', message: 'canceling statement due to lock timeout' }; } },+ })).rejects.toMatchObject({ code: '55P03' });+ expect(calls).toBe(3);+ expect(waits).toEqual([250, 250]);+ });+test('does not double-wrap an exhausted migration retry envelope', async () => {const exhausted = new MigrationRetryExhausted(16,