Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7183): open Postgres transactions READ WRITE; classify 25006 as connection_inherited_read_only

garrytan08fa937ee623
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 98f3d3c923..6878fd21ec 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -55,7 +55,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.
- `src/core/schema-migrations/v245-page-search-vector-bounded-timeline.ts` — Large pages, handler-only and idempotent: recreates the pages search_vector trigger function under `getFtsLanguage()` with the bounded timeline (`PAGE_TIMELINE_FTS_MAX_CHARS`) and entries (`PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS`) cuts, then rebuilds only pages whose timeline is longer than half the timeline cap through `search-vector-backfill.ts` (checkpoint `page_vector_bounded_timeline`, cleared at the end); shorter timelines index byte-identically and are not touched. Pinned by `test/large-pages/page-timeline-tsvector-bound.test.ts` and `test/e2e/page-timeline-tsvector-bound-postgres.test.ts`.
-- `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/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/keyword-timeout-cache.ts` (#6495 negative cache: `KeywordTimeoutNegativeCache.run(enabled, db, keyParts, exec)` wraps `searchKeyword`'s strict and relaxed statements when hybrid's keyword arm opts in with `SearchOpts.keywordTimeoutCache`; the key hashes the statement text, its parameters, the RLS source scope and the statement timeout, so only the exact statement is skipped; a genuine statement-timeout 57014, never a user cancel, records an entry for `search.keyword_timeout_negative_cache_seconds` (default 600, 0 = off, read once on the first timeout) and later identical runs throw `KeywordSkippedAfterTimeoutError` (code `keyword_skipped_after_timeout`, arm reason `skipped_after_timeout`) without a statement; at most 256 entries per engine; each timeout writes one bounded `search.keyword_timeout_stats` row that doctor `keyword_plan` reads; pinned by `test/keyword-timeout-negative-cache-6495.test.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`; `withSearchSettings` applies a read's settings in one statement and restores a caller's values when nested), `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), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort calls the begin handle's `cancelAndDiscard()`, which sends the running fenced statement's CancelRequest, keeps successors out until it settles (bounded by `GBRAIN_CANCEL_SETTLE_MS`), then discards the connection, so a statement blocked on a lock stops instead of waiting out its statement timeout (#6598) and the server rolls the transaction back; the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause` and, when the cancel could not be confirmed (unfenced statement, transport failure, settle timeout), the `CANCEL_UNCONFIRMED` rejection as `cancelFailure`; an abort after COMMIT keeps the committed result; an already-aborted signal rejects before BEGIN; pinned offline by `test/postgres-transaction-cancel-order.test.ts` and on direct Postgres and PgBouncer by `test/e2e/transaction-cancel-held-lock.test.ts`); 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/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/keyword-timeout-cache.ts` (#6495 negative cache: `KeywordTimeoutNegativeCache.run(enabled, db, keyParts, exec)` wraps `searchKeyword`'s strict and relaxed statements when hybrid's keyword arm opts in with `SearchOpts.keywordTimeoutCache`; the key hashes the statement text, its parameters, the RLS source scope and the statement timeout, so only the exact statement is skipped; a genuine statement-timeout 57014, never a user cancel, records an entry for `search.keyword_timeout_negative_cache_seconds` (default 600, 0 = off, read once on the first timeout) and later identical runs throw `KeywordSkippedAfterTimeoutError` (code `keyword_skipped_after_timeout`, arm reason `skipped_after_timeout`) without a statement; at most 256 entries per engine; each timeout writes one bounded `search.keyword_timeout_stats` row that doctor `keyword_plan` reads; pinned by `test/keyword-timeout-negative-cache-6495.test.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`; `withSearchSettings` applies a read's settings in one statement and restores a caller's values when nested), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN READ WRITE and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/read-write-transactions.ts` (#7183: a server connection whose `default_transaction_read_only` is on, from a session SET left on a pooled connection or a role or database default, refuses writes with 25006; `beginReadWrite` / `readWriteTransactions` open every pool transaction `BEGIN READ WRITE`, falling back to a plain BEGIN on a hot standby that refuses it, and `retryReadOnlyAutocommit` reruns an autocommit statement refused with 25006 once inside one; explicit `begin('read only')` and `SET TRANSACTION ... READ ONLY` stay read-only; pinned by `test/inherited-read-only-7183.test.ts` and, on direct Postgres and PgBouncer, `test/e2e/pooler-inherited-read-only-7183.test.ts`), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort calls the begin handle's `cancelAndDiscard()`, which sends the running fenced statement's CancelRequest, keeps successors out until it settles (bounded by `GBRAIN_CANCEL_SETTLE_MS`), then discards the connection, so a statement blocked on a lock stops instead of waiting out its statement timeout (#6598) and the server rolls the transaction back; the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause` and, when the cancel could not be confirmed (unfenced statement, transport failure, settle timeout), the `CANCEL_UNCONFIRMED` rejection as `cancelFailure`; an abort after COMMIT keeps the committed result; an already-aborted signal rejects before BEGIN; pinned offline by `test/postgres-transaction-cancel-order.test.ts` and on direct Postgres and PgBouncer by `test/e2e/transaction-cancel-held-lock.test.ts`); 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/analyze-lock.ts` — #7083: `lockTableForAnalyze` takes a table's SHARE UPDATE EXCLUSIVE lock with NOWAIT before every ANALYZE gbrain runs on Postgres on its own (the projection and chunk refreshes, `repair planner-stats`, `analyzeAfterIndexBuild` through `analyzeYieldingToVacuum`), and `analyzeDeferred` recognizes its 55P03 refusal. An ANALYZE that waited `deadlock_timeout` on a running autovacuum made Postgres cancel it, so a refresh after every embed drain kept a 10M-chunk content_chunks from ever being vacuumed; a request that never waits never signals a vacuum, and the caller defers its ANALYZE. Doctor `planner_stats_stale` reports a hot table whose autovacuum stays starved (`readVacuumStarvation`). Test: `test/e2e/analyze-yields-to-autovacuum-postgres.test.ts`.
- `src/core/migration-preludes.ts` — #7108 runner-side preludes for published migrations whose SQL rewrites a large table in one transaction (published migration files never change; restamp refuses an edit). `runMigrationPrelude(engine, version)` runs right before that migration's SQL inside the runner's retry wrapper: `batchedUpdate` repeats the migration's own SET and predicate over id-ordered batches (5,000 rows, inlined so a generic prepared plan cannot scan the table per batch; `__setBackfillBatchRowsForTests`), each its own transaction with the migration statement budget and the schema lock timeout, so progress is the data itself and a rerun resumes; a column the migration adds first is added first, in the migration's column order (fresh and upgraded ordinals stay equal). Preludes: v011 legacy `links.link_source` (skipped below PG15, where the migration refuses), v028 chunk keyword vectors, v033 request-log agent names (NULL-token rows stay the migration's own), v116 code-edge `source_id`, v161 (Postgres) the partial pages index built concurrently under the budget on a reserved connection (the migration caps its own build at 30 s; another session's build or an invalid result stops the run), v221 `embedding_pending_since` (v221's active-column choice; the first stamping batch writes `embedding_pending_since_backfilled_at` in its transaction). Pinned by `test/e2e/migration-v221-batched-backfill-7108.test.ts`. Migrations that cannot be moved here are listed in docs/guides/troubleshooting.md#migration-statement-timeout.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7ca67e4726..849bb07e94 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -729,6 +729,16 @@ More: [docs/guides/write-refusals.md#concurrent_write](../../docs/guides/write-r
|---|---|---|---|---|---|---|
| --source and --all-sources were both given. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### connection_inherited_read_only
+
+<a id="connection_inherited_read_only"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The database refused a write as read-only (SQLSTATE 25006): the server connection defaults to read-only transactions, so nothing was written. | default_transaction_read_only is on for that server connection: session state another client set on a connection a transaction-mode pooler shares, a role or database default, or a read-only server. gbrain opens its transactions READ WRITE and runs a refused autocommit statement once more inside one, so a session default alone no longer stops it; a read-only server (a hot standby) still refuses. | Ask the database operator to reset the pooler's server connections (PgBouncer: RECONNECT, or server_reset_query = DISCARD ALL with server_reset_query_always = 1), find the client that issues session-level SET through the pooler (read-only audits belong in BEGIN READ ONLY ... COMMIT), and check ALTER ROLE / ALTER DATABASE ... SET default_transaction_read_only; then retry. Run: gbrain doctor --json | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/troubleshooting.md#inherited-read-only-connections](../../docs/guides/troubleshooting.md#inherited-read-only-connections)
+
### connection_lost
<a id="connection_lost"></a>
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index f9b4146294..ac89be067c 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -180,6 +180,7 @@ Every hold and error has three fields, from one table
| `owner_unavailable` | systemic | none | yes | always |
| `writer_coordinator_required` | systemic | none | yes | always |
| `permission_denied` | systemic | none | yes | always |
+| `connection_inherited_read_only` | systemic | none | yes | always: only the database operator clears read-only server state |
| `write_quota_exhausted` | systemic | none | yes | always |
| `write_quota_insufficient` | systemic | none | yes | always |
| `plan_stale` | systemic | none | yes | always |
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index f2155e7851..19d57ff858 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -68,6 +68,7 @@
| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and rerun the plain sync (`--retry-failed` is a deprecated alias), or commit an ignored file | agent | none | `gbrain sources status --json` |
| [Sync with the deprecated `--retry-failed` alias says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` |
| [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 …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
+| [Writes fail with `connection_inherited_read_only` or `cannot execute INSERT in a read-only transaction` (SQLSTATE 25006)](#inherited-read-only-connections) | on the database or pooler host, reset the pooler's server connections and stop the client that issues session-level `SET` through the pooler; check `ALTER ROLE` / `ALTER DATABASE` defaults | brain host | none (`destructive` only in that it changes server state) | `gbrain doctor --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` |
@@ -157,6 +158,8 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.
+<a id="inherited-read-only-connections"></a>**Writes fail with `connection_inherited_read_only` (SQLSTATE 25006, `cannot execute INSERT in a read-only transaction` or `... SELECT FOR SHARE ...`)?** The server connection defaults to read-only transactions. On a transaction-mode pooler (PgBouncer `pool_mode = transaction`, Supavisor) the usual cause is another client that ran a session-level `SET default_transaction_read_only = on`: the pooler shares server connections, so that setting stays on the connection and later clients inherit it until the connection closes. A role or database default (`ALTER ROLE ... SET default_transaction_read_only = on`) or a read-only server (a hot standby) has the same effect. gbrain opens its own transactions `BEGIN READ WRITE` and runs an autocommit statement the server refused this way once more inside one, so an inherited session default no longer stops its writes; the code remains for a read-only server and for any write path outside those seams. On the database or pooler host: reset the pooler's server connections (PgBouncer `RECONNECT <db>` on the admin console, or `server_reset_query = DISCARD ALL` with `server_reset_query_always = 1` so no session state survives a transaction), find the client that issues session-level `SET` through the pooler, and check the role and database defaults (`SELECT setrole::regrole, setdatabase, setconfig FROM pg_db_role_setting`). Run read-only audits as `BEGIN READ ONLY; ...; COMMIT;` or under a read-only role, never as a session-level `SET` through a transaction pooler.
+
<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
diff --git a/llms-full.txt b/llms-full.txt
index 876bf92711..7d7e9fd8ce 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10449,6 +10449,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and rerun the plain sync (`--retry-failed` is a deprecated alias), or commit an ignored file | agent | none | `gbrain sources status --json` |
| [Sync with the deprecated `--retry-failed` alias says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` |
| [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 …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
+| [Writes fail with `connection_inherited_read_only` or `cannot execute INSERT in a read-only transaction` (SQLSTATE 25006)](#inherited-read-only-connections) | on the database or pooler host, reset the pooler's server connections and stop the client that issues session-level `SET` through the pooler; check `ALTER ROLE` / `ALTER DATABASE` defaults | brain host | none (`destructive` only in that it changes server state) | `gbrain doctor --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` |
@@ -10538,6 +10539,8 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.
+<a id="inherited-read-only-connections"></a>**Writes fail with `connection_inherited_read_only` (SQLSTATE 25006, `cannot execute INSERT in a read-only transaction` or `... SELECT FOR SHARE ...`)?** The server connection defaults to read-only transactions. On a transaction-mode pooler (PgBouncer `pool_mode = transaction`, Supavisor) the usual cause is another client that ran a session-level `SET default_transaction_read_only = on`: the pooler shares server connections, so that setting stays on the connection and later clients inherit it until the connection closes. A role or database default (`ALTER ROLE ... SET default_transaction_read_only = on`) or a read-only server (a hot standby) has the same effect. gbrain opens its own transactions `BEGIN READ WRITE` and runs an autocommit statement the server refused this way once more inside one, so an inherited session default no longer stops its writes; the code remains for a read-only server and for any write path outside those seams. On the database or pooler host: reset the pooler's server connections (PgBouncer `RECONNECT <db>` on the admin console, or `server_reset_query = DISCARD ALL` with `server_reset_query_always = 1` so no session state survives a transaction), find the client that issues session-level `SET` through the pooler, and check the role and database defaults (`SELECT setrole::regrole, setdatabase, setconfig FROM pg_db_role_setting`). Run read-only audits as `BEGIN READ ONLY; ...; COMMIT;` or under a read-only role, never as a session-level `SET` through a transaction pooler.
+
<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index 26fe1dc56c..dc4ba7e7a3 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -70,3 +70,4 @@ test/e2e/entity-names-parity-postgres.test.ts
test/e2e/segment-gc-parity.test.ts
test/e2e/doctor-entry-deadline-postgres.test.ts
test/e2e/s-sync-queue-wake-postgres.test.ts
+test/e2e/pooler-inherited-read-only-7183.test.ts
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index d0ff90fd0b..1a91a620df 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -18,6 +18,7 @@ import { StructuredAgentError } from './errors.ts';
import { canonicalCodeFor, codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';
import { VERB_NAMES } from './verbs.ts';
import { classifyPgAccessError, formatDbAccessMarker } from './pg-access-classify.ts';
+import { isReadOnlyTransactionError } from './postgres-engine/read-write-transactions.ts';
import { redactConnectionInfo } from './audit/redact-connection-info.ts';
import { redactUrlsInText } from './url-redact.ts';
import { parseRepoBase } from './repo-base.ts';
@@ -583,6 +584,11 @@ const ROWS: Row[] = [
suggestion: e.envelope.hint, docs: e.envelope.docs_url,
}),
},
+ {
+ match: isReadOnlyTransactionError,
+ map: (e: Error) => ({ error: 'connection_inherited_read_only', code: 'connection_inherited_read_only', message: e.message,
+ fix: registryTemplateFix('connection_inherited_read_only', {}) }),
+ },
{
match: e => e instanceof Error && (e as { tag?: unknown }).tag === 'BUDGET_EXHAUSTED',
map: (e: Error & { reason: string; cap: number; pricing?: { model: string; units: string[]; lookup: string; register_command: string } }, ctx) => {
diff --git a/src/core/backfill-base.ts b/src/core/backfill-base.ts
index 82cc6afd3c..0a3c38d2e9 100644
--- a/src/core/backfill-base.ts
+++ b/src/core/backfill-base.ts
@@ -27,6 +27,7 @@ import { GBrainError } from './types.ts';
import { redactConnectionInfo } from './audit/redact-connection-info.ts';
import { classifyItemFailure, ItemRun } from './item-failure.ts';
import { OperationError } from './ops/contract.ts';
+import { READ_WRITE_BEGIN } from './postgres-engine/read-write-transactions.ts';
import { heldUnchanged, noteSkip, parseSkipLedger, readSkipLedgerRaw, reportSkips, restoreSkipLedger, rowRevision, type BackfillSkip } from './backfill-skips.ts';
function brief(err: unknown): string {
@@ -293,7 +294,7 @@ export async function runBackfill<TRow = Record<string, unknown>>(
const writeBatch = async (computedUpdates: Array<{ id: number; updates: Record<string, unknown> }>): Promise<number> => {
if (opts.dryRun || computedUpdates.length === 0) return 0;
return engine.withReservedConnection(async conn => {
- await conn.executeRaw(`BEGIN`);
+ await conn.executeRaw(engine.kind === 'postgres' ? READ_WRITE_BEGIN : 'BEGIN');
let batchUpdated = 0;
let stage: 'setup' | 'update' | 'commit' = 'setup';
try {
diff --git a/src/core/db-lock.ts b/src/core/db-lock.ts
index a5fda12fbf..69e8907189 100644
--- a/src/core/db-lock.ts
+++ b/src/core/db-lock.ts
@@ -24,6 +24,7 @@
import { hostname } from 'os';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from './engine.ts';
+import { retryReadOnlyAutocommit } from './postgres-engine/read-write-transactions.ts';
export interface DbLockHandle {
id: string;
@@ -250,7 +251,7 @@ export async function tryAcquireDbLock(
// `gbrain sync --break-lock --max-age <s>` uses last_refreshed_at (not
// acquired_at) to identify wedged-but-alive holders without stealing
// healthy long-running holders that are actively refreshing.
- const rows: Array<{ id: string; fence: string }> = await sql`
+ const rows: Array<{ id: string; fence: string }> = await retryReadOnlyAutocommit(sql, (sql: any) => sql`
INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)
VALUES (${lockId}, ${pid}, ${host}, NOW(), NOW() + ${ttl}::interval, NOW(), ${acquisitionToken}::uuid)
ON CONFLICT (id) DO UPDATE
@@ -264,17 +265,17 @@ export async function tryAcquireDbLock(
AND (gbrain_cycle_locks.last_refreshed_at IS NULL
OR gbrain_cycle_locks.last_refreshed_at < NOW() - ${stealGraceSeconds} * INTERVAL '1 second')
RETURNING id, extract(epoch from acquired_at)::text AS fence
- `;
+ `);
if (rows.length === 0) return null;
// The UUID is the fence; the epoch text rides on the handle for
// diagnostics (migration-orchestration-lock.ts reports it when a lease
// is lost) and is never compared (#6028).
const fence = rows[0].fence;
const deregister = registerCleanup(`db-lock:${lockId}`, async () => {
- await (maybePG.sql as any)`
+ await retryReadOnlyAutocommit(maybePG.sql as any, (sql: any) => sql`
DELETE FROM gbrain_cycle_locks
WHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid
- `;
+ `);
});
return {
id: lockId,
@@ -298,10 +299,10 @@ export async function tryAcquireDbLock(
},
release: async () => {
deregister();
- await (maybePG.sql as any)`
+ await retryReadOnlyAutocommit(maybePG.sql as any, (sql: any) => sql`
DELETE FROM gbrain_cycle_locks
WHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid
- `;
+ `);
},
};
}
@@ -660,11 +661,11 @@ export async function deleteLockRow(
if (engine.kind === 'postgres' && maybePG.sql) {
const sql = maybePG.sql as any;
- const rows: Array<{ id: string }> = await sql`
+ const rows: Array<{ id: string }> = await retryReadOnlyAutocommit(sql, (sql: any) => sql`
DELETE FROM gbrain_cycle_locks
WHERE id = ${lockId} AND holder_pid = ${holderPid} AND acquisition_token = ${acquisitionToken}::uuid
RETURNING id
- `;
+ `);
return { deleted: rows.length > 0 };
}
if (engine.kind === 'pglite' && maybePGLite.db) {
@@ -731,7 +732,7 @@ export async function deleteLockRowIfStale(
if (engine.kind === 'postgres' && maybePG.sql) {
const sql = maybePG.sql as any;
- const rows: Array<{ id: string; last_refreshed_at: Date | string | null }> = await sql`
+ const rows: Array<{ id: string; last_refreshed_at: Date | string | null }> = await retryReadOnlyAutocommit(sql, (sql: any) => sql`
DELETE FROM gbrain_cycle_locks
WHERE id = ${lockId}
AND holder_pid = ${holderPid}
@@ -739,7 +740,7 @@ export async function deleteLockRowIfStale(
AND last_refreshed_at IS NOT NULL
AND last_refreshed_at < NOW() - ${maxAgeSeconds} * INTERVAL '1 second'
RETURNING id, last_refreshed_at
- `;
+ `);
if (rows.length === 0) return { deleted: false, lastRefreshedAt: null };
const lr = rows[0].last_refreshed_at;
const lastRefreshed = lr == null ? null : (lr instanceof Date ? lr : new Date(lr));
diff --git a/src/core/db.ts b/src/core/db.ts
index a6f1126e69..a3e4bc372e 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,6 +1,7 @@
import postgres from '#postgres'
import { claimOwner } from './persistence/claim-phase.ts';
import { traceSqlOptions } from './sql-trace.ts';
+import { beginReadWrite } from './postgres-engine/read-write-transactions.ts';
import { GBrainError, type EngineConfig } from './types.ts';
import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
@@ -592,10 +593,7 @@ export async function initSchema(): Promise<void> {
export { verifySchema } from './schema-verify.ts';
export async function withTransaction<T>(fn: (tx: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {
- const conn = getConnection();
- return conn.begin(async (tx) => {
- return fn(tx as unknown as ReturnType<typeof postgres>);
- }) as Promise<T>;
+ return beginReadWrite(getConnection(), async (tx) => fn(tx as unknown as ReturnType<typeof postgres>));
}
// issue #1720 (proposal 4): the startup connect matcher and the runtime
diff --git a/src/core/engine-sql/dialect-postgres.ts b/src/core/engine-sql/dialect-postgres.ts
index a6c57ee801..904631523a 100644
--- a/src/core/engine-sql/dialect-postgres.ts
+++ b/src/core/engine-sql/dialect-postgres.ts
@@ -24,6 +24,7 @@
import type postgres from '#postgres';
import type { CheckoutGauge } from '../pool-gauge.ts';
import { renderFragment, type SqlFragment } from './fragment.ts';
+import { readWriteTransactions } from '../postgres-engine/read-write-transactions.ts';
import {
isJsonbParam,
type DialectCapabilities,
@@ -87,7 +88,7 @@ export function postgresExecutor(conn: PgConn, deps: PostgresExecutorDeps): SqlE
return envelope<R>(await conn.unsafe(sql, bind(conn, params) as never[]));
},
transaction<T>(fn: (tx: SqlExecutor) => Promise<T>): Promise<T> {
- return conn.begin((tx) => fn(postgresExecutor(tx as unknown as PgConn, deps))) as Promise<T>;
+ return readWriteTransactions(conn).begin((tx) => fn(postgresExecutor(tx as unknown as PgConn, deps))) as Promise<T>;
},
};
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index d53a36762c..b6e4d82ca2 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -150,6 +150,12 @@ export const CODES = {
config_error: { class: 'caller', summary: "A required configuration value or directory is missing or invalid." },
confirmation_required: { class: 'consent', summary: "The command needs the user's authorization before it runs; nothing was changed.", exit: 3 },
conflicting_source_scope: { class: 'caller', summary: "--source and --all-sources were both given." },
+ connection_inherited_read_only: { class: 'host_only', retryable: false, actor: 'host_admin',
+ summary: "The database refused a write as read-only (SQLSTATE 25006): the server connection defaults to read-only transactions, so nothing was written.",
+ why: "default_transaction_read_only is on for that server connection: session state another client set on a connection a transaction-mode pooler shares, a role or database default, or a read-only server. gbrain opens its transactions READ WRITE and runs a refused autocommit statement once more inside one, so a session default alone no longer stops it; a read-only server (a hot standby) still refuses.",
+ docs: 'docs/guides/troubleshooting.md#inherited-read-only-connections',
+ suggestion: "Ask the database operator to reset the pooler's server connections (PgBouncer: RECONNECT, or server_reset_query = DISCARD ALL with server_reset_query_always = 1), find the client that issues session-level SET through the pooler (read-only audits belong in BEGIN READ ONLY ... COMMIT), and check ALTER ROLE / ALTER DATABASE ... SET default_transaction_read_only; then retry.",
+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: reports the database connection and what is blocked on it.', requires_exclusive: false } },
connection_lost: { class: 'retryable', retryable: true, actor: 'agent',
summary: "The managed sync drain lost its database connection three times in a row without committing a page in between, so it stopped where the cursor stands; nothing is recorded against the source.",
why: "A pooler drop (ECONNABORTED, ECONNRESET, ETIMEDOUT, EPIPE) is a transport fault, not a page fault: the drain reconnects and retries at 5, 15 and 45 seconds, and the frozen manifest and cursor stay as they are. Three consecutive drops with no progress mean the database is unreachable from here for now.",
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index 1a4dff618d..a6bc55a0ac 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -79,6 +79,7 @@ export const RUN_SCOPED_CODES: ReadonlySet<string> = new Set([
'permission_denied', 'schema_owner_required', 'scope_denied', 'config', 'auth', 'connector_holds_exhausted', 'transfer_in_progress', 'disk_full',
'invalid_token', 'insufficient_scope', 'trusted_local_only', 'requires_local_engine', 'not_owner_host', 'host_identity_mismatch',
'recovery_required', 'cancelled', 'persistence_restart_required', 'writer_regrant_required', 'writer_manifest_rescope_required',
+ 'connection_inherited_read_only',
]);
/** Item codes that fail the same way until the item changes. Every other item code is transient. */
@@ -94,6 +95,7 @@ function sqlstateFailure(state: string): { code: string; scope: 'run' | 'item';
|| state.startsWith('58') || state.startsWith('XX')) return { code: 'database_contention', scope: 'run', class: 'transient' };
if (state === '42P01' || state === '42703' || state === '42883') return { code: 'schema_behind', scope: 'run', class: 'transient' };
if (state === '42501') return { code: 'permission_denied', scope: 'run', class: 'transient' };
+ if (state === '25006') return { code: 'connection_inherited_read_only', scope: 'run', class: 'transient' };
if (state.startsWith('28')) return { code: 'auth', scope: 'run', class: 'transient' };
if (state === '57014') return { code: 'statement_timeout', scope: 'item', class: 'transient' };
if (state === '55P03') return { code: 'lock_timeout', scope: 'item', class: 'transient' };
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
index 9e6cf1d770..1a16055fae 100644
--- a/src/core/persistence/bounded-reads.ts
+++ b/src/core/persistence/bounded-reads.ts
@@ -32,6 +32,7 @@
*/
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import { PoolCapacityError } from '../pool-budget.ts';
+import { READ_WRITE_BEGIN } from '../postgres-engine/read-write-transactions.ts';
import { recordClaimSql, type ClaimPhaseClock } from './claim-phase.ts';
import { registerEngineView, viewedEngine } from './switches.ts';
@@ -163,7 +164,7 @@ class BoundedReadSession {
const steps: Promise<unknown>[] = [];
if (!this.open) {
this.open = true;
- steps.push(this.conn.executeRaw('BEGIN'));
+ steps.push(this.conn.executeRaw(READ_WRITE_BEGIN));
steps.push(this.conn.executeRaw(`SET LOCAL statement_timeout = ${ms}`));
this.boundMs = ms;
} else if (Math.abs(this.boundMs - ms) > BOUNDED_SESSION_SLACK_MS) {
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 25ce75c225..501b532881 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -50,6 +50,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
write_capacity_backpressure: 'transient', capacity_paused: 'transient', sync_drain_lease_held: 'transient', graduation_in_progress: 'transient',
storage_error: 'storage', recovery_required: 'storage',
permission_denied: 'permission',
+ connection_inherited_read_only: 'config',
owner_unavailable: 'config', writer_coordinator_required: 'config', write_quota_exhausted: 'config', write_quota_insufficient: 'config', plan_stale: 'config',
slug_root_mode_mismatch: 'config', invalid_params: 'config',
// GBRA-133 (#6712 PR 4b lane F): a file whose text holds NUL bytes, and a committed file whose Git object is gone.
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 356cdb1bea..c65379a7bb 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -5,6 +5,7 @@ import type { FenceFailureDetail } from '../fence-repair/refusal.ts';
import type { WithdrawalFailureDetail } from '../facts/withdrawal.ts';
import type { Action } from '../agent-output.ts';
import { classifyPgAccessError } from '../pg-access-classify.ts';
+import { READ_ONLY_SQLSTATE } from '../postgres-engine/read-write-transactions.ts';
/**
* #5974: a database refusal during preparation or publication becomes a
@@ -124,6 +125,8 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {
if (sqlstate && SCHEMA_MISSING_SQLSTATES.has(sqlstate) && classifyPgAccessError(error).reason === 'schema_missing') {
return schemaMissing(sqlstate, typeof e.message === 'string' && e.routine !== 'exec_stmt_raise' ? e.message : '');
}
+ if (sqlstate === READ_ONLY_SQLSTATE) return { code: 'connection_inherited_read_only', detail: { origin: 'database', sqlstate },
+ message: `The database refused this write as read-only (SQLSTATE ${sqlstate}${typeof e.message === 'string' ? `: ${e.message}` : ''}), so nothing was committed: the server connection defaults to read-only transactions (pooler session state left by another client, a role or database default, or a read-only server).` };
if (sqlstate !== 'P0001' && sqlstate !== GRADUATION_SQLSTATE) return null;
const where = typeof e.where === 'string' ? e.where : '';
const raiser = ident(/PL\/pgSQL function (?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)[( ]/.exec(where)?.[1]);
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 8ffbb08ae1..21d87ece8a 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -171,6 +171,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
{ code: 'owner_unavailable', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The write owner is gone; start or restart it on the brain host.' },
{ code: 'writer_coordinator_required', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'Managed persistence is not active for this source; activate it or sync unmanaged.' },
{ code: 'permission_denied', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'This principal may not sync the source; the owner grants it.' },
+ // #7183: the server connection defaults to read-only transactions (pooler session state another client left, or a read-only server).
+ { code: 'connection_inherited_read_only', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: only the database operator clears read-only server state',
+ human_reason: 'The database refused writes as read-only: a pooled server connection inherited default_transaction_read_only from another client, or the role, database or server is read-only. The database operator resets the pooler\'s server connections and finds the client issuing session-level SET; then sync again.' },
// #6696 (A6/A7): a cumulative cap is full, or too small for the run; only the brain host's reversible config raise clears it.
{ code: 'write_quota_exhausted', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always',
human_reason: 'A cumulative write cap is full; the brain host runs the gbrain config set the error prints (gbrain doctor --only persistence_capacity --json names the value), then the same sync resumes.' },
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index cbfbea5f24..72d6fbf8b3 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -20,7 +20,7 @@ export const WRITE_ERROR_CODES = [
'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
'timeline_rows_would_be_removed', 'purged_content', 'preparation_stalled',
'fence_unrenderable', 'page_body_segmented', 'revision_changed', 'tail_changed',
- 'write_outcome_unknown', 'write_interrupted',
+ 'write_outcome_unknown', 'write_interrupted', 'connection_inherited_read_only',
] as const;
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af1b260aba..44b26e8430 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -65,6 +65,7 @@ import type {
} from './types.ts';
import { DREAM_VERDICT_TTL_SECONDS, clampSearchLimit, type TransactionOptions } from './engine.ts';
import { transactionAborted, withTransactionAbort, type Discardable } from './postgres-engine/transaction-abort.ts';
+import { readWriteTransactions, retryReadOnlyAutocommit } from './postgres-engine/read-write-transactions.ts';
import { searchLimitCap } from './search/eval-pool-depth.ts';
import { executeRawJsonb, type SqlValue } from './sql-query.ts';
import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
@@ -660,6 +661,7 @@ export class PostgresEngine implements BrainEngine {
private async transactionOn<T>(conn: ReturnType<typeof postgres>, fn: (engine: BrainEngine) => Promise<T>, opts?: TransactionOptions): Promise<T> {
if (opts?.signal?.aborted) throw transactionAborted(opts.signal);
+ conn = readWriteTransactions(conn);
// try/finally, not .finally on the chained promise: begin() can throw
// SYNCHRONOUSLY (e.g. nested transaction on a tx clone whose conn has no
// .begin), which would skip a chained .finally and leak the counter.
@@ -2844,7 +2846,12 @@ export class PostgresEngine implements BrainEngine {
* Cancellable statements retain an exclusive connection through query and
* cancellation settlement so a late CancelRequest cannot hit its successor.
*/
- private runUnsafe<T>(
+ private runUnsafe<T>(conn: ReturnType<typeof postgres>, sql: string, params?: unknown[], opts?: RunUnsafeOpts): Promise<T[]> {
+ if (opts?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
+ return retryReadOnlyAutocommit(conn, c => this.runUnsafeOnce<T>(c, sql, params, opts));
+ }
+
+ private runUnsafeOnce<T>(
conn: ReturnType<typeof postgres>,
sql: string,
params?: unknown[],
diff --git a/src/core/postgres-engine/bounded-statement.ts b/src/core/postgres-engine/bounded-statement.ts
index 1ec51e598a..0ebd312a3e 100644
--- a/src/core/postgres-engine/bounded-statement.ts
+++ b/src/core/postgres-engine/bounded-statement.ts
@@ -4,7 +4,7 @@
* so a preparation read outside the publication transaction had no
* server-side bound and a relation lock held elsewhere pinned its connection
* for as long as the lock lasted. A reserved connection runs `BEGIN; SET LOCAL
- * statement_timeout`, the statement and `COMMIT` as one pipelined round trip:
+ * statement_timeout` (`BEGIN READ WRITE`, #7183), the statement and `COMMIT` as one pipelined round trip:
* the pooler pins the transaction to one server connection, `SET LOCAL` ends
* with it, and a statement past the bound ends server-side with 57014 (a lock
* wait counts toward it). `COMMIT` after a failed statement is a rollback,
@@ -21,6 +21,7 @@
*/
import type postgres from '#postgres';
import { reserveWithCancellation } from './cancellation.ts';
+import { READ_WRITE_BEGIN } from './read-write-transactions.ts';
type Sql = ReturnType<typeof postgres>;
export type RunStatement = <T>(conn: Sql, sql: string, params: unknown[] | undefined, opts: { signal?: AbortSignal; prepare?: boolean }) => Promise<T[]>;
@@ -37,7 +38,7 @@ export async function runBoundedStatement<T>(conn: Sql, sql: string, params: unk
settings.push(`SET LOCAL statement_timeout = ${ms}`);
}
try {
- const open = reserved.unsafe(['BEGIN', ...settings].join('; ')).simple().execute();
+ const open = reserved.unsafe([READ_WRITE_BEGIN, ...settings].join('; ')).simple().execute();
// A cancellable statement is issued through `run`, which awaits the query and so enqueues it a microtask
// later than `execute()` would: COMMIT then waits for it to settle instead of being pipelined ahead of it.
const cancellable = opts.timeoutMs === undefined && opts.signal && run;
diff --git a/src/core/postgres-engine/read-write-transactions.ts b/src/core/postgres-engine/read-write-transactions.ts
new file mode 100644
index 0000000000..e3afa217e8
--- /dev/null
+++ b/src/core/postgres-engine/read-write-transactions.ts
@@ -0,0 +1,73 @@
+/**
+ * #7183: every transaction gbrain opens on Postgres declares itself read-write, and an autocommit statement the server
+ * refuses as read-only runs once more inside such a transaction.
+ *
+ * A transaction-mode pooler (PgBouncer `pool_mode=transaction`, Supavisor) shares server connections between clients.
+ * A client that runs a session-level `SET default_transaction_read_only = on` leaves that default on the server
+ * connection, and a pooler that does not restore it hands it to every later client of that connection; a role or
+ * database default does the same to every connection. gbrain's writes then fail with SQLSTATE 25006 (`cannot execute
+ * INSERT in a read-only transaction`, `... SELECT FOR SHARE ...`). A transaction's own characteristics outrank the
+ * session default, so:
+ *
+ * - `beginReadWrite` opens `BEGIN READ WRITE` (postgres.js `begin('read write', fn)`). A hot standby refuses read-write
+ * mode at BEGIN (0A000, before `fn` runs); the transaction then opens without it, as before, so reads keep working there.
+ * - `READ_WRITE_BEGIN` is the statement for the raw envelopes on reserved connections.
+ * - `retryReadOnlyAutocommit` runs an autocommit statement on a pool and, when the server refused it with 25006, runs it
+ * once more inside `beginReadWrite`. The first run changed nothing: an autocommit statement is its own implicit
+ * transaction, which the error rolled back. Nothing is spent until a statement is refused. A statement that cannot run
+ * in a transaction block (25001) reports the original refusal.
+ *
+ * A session-level `SET default_transaction_read_only = off` cannot fix this: through a transaction pooler it lands on
+ * whichever server connection that statement gets, and is itself session state left for other clients.
+ */
+import type postgres from '#postgres';
+
+type Sql = ReturnType<typeof postgres>;
+
+/** SQLSTATE `read_only_sql_transaction`. */
+export const READ_ONLY_SQLSTATE = '25006';
+export const READ_WRITE_BEGIN = 'BEGIN READ WRITE';
+
+const codeOf = (error: unknown) => (error as { code?: unknown } | null)?.code;
+
+export function isReadOnlyTransactionError(error: unknown): boolean {
+ return codeOf(error) === READ_ONLY_SQLSTATE;
+}
+
+/** A pool opens transactions on its own connections; transaction and reserved handles have no `reserve`. */
+function isPool(conn: unknown): conn is Sql {
+ return typeof (conn as { reserve?: unknown }).reserve === 'function' && typeof (conn as { begin?: unknown }).begin === 'function';
+}
+
+function standbyRefusal(error: unknown): boolean {
+ return codeOf(error) === '0A000' && /read-write mode during recovery/i.test(String((error as { message?: unknown }).message ?? ''));
+}
+
+export async function beginReadWrite<T>(pool: Sql, fn: (tx: postgres.TransactionSql) => Promise<T>): Promise<T> {
+ let entered = false;
+ try {
+ return await pool.begin('read write', tx => { entered = true; return fn(tx); }) as T;
+ } catch (error) {
+ if (entered || !standbyRefusal(error)) throw error;
+ return await pool.begin(fn) as T;
+ }
+}
+
+/** A pool whose `begin` opens read-write transactions; a transaction or reserved handle is returned unchanged. */
+export function readWriteTransactions(conn: Sql): Sql {
+ if (!isPool(conn)) return conn;
+ return { begin: (fn: (tx: postgres.TransactionSql) => Promise<unknown>) => beginReadWrite(conn, fn) } as unknown as Sql;
+}
+
+export async function retryReadOnlyAutocommit<T>(conn: Sql, run: (conn: Sql) => Promise<T>): Promise<T> {
+ try {
+ return await run(conn);
+ } catch (error) {
+ if (!isReadOnlyTransactionError(error) || !isPool(conn)) throw error;
+ try {
+ return await beginReadWrite(conn, tx => run(tx as unknown as Sql));
+ } catch (retryError) {
+ throw codeOf(retryError) === '25001' ? error : retryError;
+ }
+ }
+}
diff --git a/src/core/postgres-engine/reserved-transactions.ts b/src/core/postgres-engine/reserved-transactions.ts
index 00deb3f67c..bb613f205c 100644
--- a/src/core/postgres-engine/reserved-transactions.ts
+++ b/src/core/postgres-engine/reserved-transactions.ts
@@ -1,5 +1,6 @@
import type postgres from '#postgres';
import type { BrainEngine } from '../engine.ts';
+import { READ_WRITE_BEGIN } from './read-write-transactions.ts';
/**
* Phase 4.4: what `PostgresEngine.withReservedConnection` adds to its
@@ -12,7 +13,7 @@ export interface ReservedTransactions { transaction<T>(fn: (engine: BrainEngine)
/**
* Phase 4.4: `begin` for one reserved postgres.js connection, as `sql.begin`
- * runs it on a pooled one: BEGIN, the callback with a handle whose
+ * runs it on a pooled one: BEGIN READ WRITE (#7183), the callback with a handle whose
* `savepoint` nests (rolled back to on error, like postgres.js), COMMIT, and
* ROLLBACK on failure. BEGIN and SAVEPOINT are sent with the statements that
* follow them instead of a round trip ahead (the server still runs them
@@ -36,7 +37,7 @@ export function reservedTransactions(reserved: postgres.ReservedSql): ReturnType
catch (error) { if (await marker.then(() => true, () => false)) await reserved.unsafe(`rollback to ${name}`); throw error; }
},
});
- const opened = reserved.unsafe('begin').execute();
+ const opened = reserved.unsafe(READ_WRITE_BEGIN).execute();
let result: unknown;
try { result = await settle(opened, Promise.resolve().then(() => fn(handle))); }
catch (error) { await reserved.unsafe('rollback').catch(() => reserved.discard()); throw error; }
diff --git a/test/backfill-base.test.ts b/test/backfill-base.test.ts
index d21aa6f628..3caa85c0d5 100644
--- a/test/backfill-base.test.ts
+++ b/test/backfill-base.test.ts
@@ -161,7 +161,7 @@ class TransactionalFakeEngine extends FakeEngine {
this.fail.delete(injected[0]);
throw injected[1];
}
- if (sql === 'BEGIN') { this.pending = []; return []; }
+ if (sql === 'BEGIN' || sql === 'BEGIN READ WRITE') { this.pending = []; return []; }
if (sql === 'ROLLBACK') { this.pending = null; return []; }
if (sql === 'COMMIT') {
for (const id of this.pending ?? []) await super.executeRaw(`UPDATE pages`, [id]);
diff --git a/test/e2e/pooler-inherited-read-only-7183.test.ts b/test/e2e/pooler-inherited-read-only-7183.test.ts
new file mode 100644
index 0000000000..b746885c9f
--- /dev/null
+++ b/test/e2e/pooler-inherited-read-only-7183.test.ts
@@ -0,0 +1,129 @@
+/**
+ * #7183 / #7187: gbrain writes through server connections whose transactions default to read-only.
+ *
+ * A client that runs a session-level `SET default_transaction_read_only = on` through a transaction-mode pooler can
+ * leave that default on a server connection other clients then borrow; a role or database default does the same for
+ * every connection. This file reproduces that server state with a database-level default on a scratch database (the
+ * session leak itself depends on the pooler build: PgBouncer 1.26 restores this setting per client), connects a fresh
+ * engine (through PgBouncer in the backend matrix's pooled pass), and checks that the engine's transactions, its
+ * autocommit statements, the database lease and the Minions queue still write, and that the stall detector reclaims an
+ * `active` job left with an expired lock by a worker that died on the refused writes (#7187).
+ *
+ * Listed in scripts/e2e-backend-matrix.txt: run once on direct Postgres and once through transaction-mode PgBouncer.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { tryAcquireDbLock } from '../../src/core/db-lock.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { MinionWorker } from '../../src/core/minions/worker.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+
+const target = process.env.DATABASE_URL;
+const pooled = process.env.GBRAIN_TEST_BACKEND === 'pgbouncer';
+const adminUrl = pooled ? process.env.GBRAIN_PGBOUNCER_DIRECT_URL : target;
+const available = Boolean(target && adminUrl);
+const describeDb = available ? describe : describe.skip;
+
+let database = '';
+let admin: ReturnType<typeof postgres> | undefined;
+let engine: PostgresEngine | undefined;
+let queue: MinionQueue;
+
+const withDatabase = (url: string) => { const u = new URL(url); u.pathname = `/${database}`; return u.toString(); };
+
+beforeAll(async () => {
+ if (!available) return;
+ assertSafeE2eDatabaseUrl(adminUrl!);
+ database = `gbrain_test_ro_default_${randomUUID().replaceAll('-', '')}`;
+ admin = postgres(adminUrl!, { max: 1, prepare: false, onnotice: () => undefined });
+ await admin.unsafe(`CREATE DATABASE ${database}`);
+ // Schema on a direct connection first: the pooler must open its server connections only after the default is set.
+ const setup = new PostgresEngine();
+ await setup.connect({ database_url: withDatabase(adminUrl!), poolSize: 2 });
+ await setup.initSchema();
+ await setup.disconnect();
+ await admin.unsafe(`ALTER DATABASE ${database} SET default_transaction_read_only = on`);
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: withDatabase(target!), poolSize: 4 });
+ queue = new MinionQueue(engine);
+}, 180_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (admin) {
+ try { if (database) await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); }
+ finally { await admin.end(); }
+ }
+});
+
+describeDb(`writes on read-only-default server connections (${pooled ? 'pgbouncer' : 'postgres-direct'})`, () => {
+ test('precondition: the borrowed server connection defaults to read-only, so the probe is not vacuous', async () => {
+ const [row] = await engine!.executeRaw<{ v: string }>('SELECT current_setting($1) AS v', ['default_transaction_read_only']);
+ expect(row.v).toBe('on');
+ });
+
+ test('an engine transaction writes', async () => {
+ const id = `ro-${randomUUID().slice(0, 8)}`;
+ await engine!.transaction(async tx => {
+ await tx.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1)', [id]);
+ await tx.executeRaw('SELECT id FROM sources WHERE id = $1 FOR SHARE', [id]);
+ });
+ expect(await engine!.executeRaw('SELECT 1 FROM sources WHERE id = $1', [id])).toHaveLength(1);
+ });
+
+ test('an autocommit write outside any transaction writes', async () => {
+ const id = `ro-${randomUUID().slice(0, 8)}`;
+ await engine!.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1)', [id]);
+ expect(await engine!.executeRaw('SELECT 1 FROM sources WHERE id = $1', [id])).toHaveLength(1);
+ });
+
+ test('a deliberately read-only transaction still refuses a write', async () => {
+ await expect(engine!.sql.begin('read only', tx => tx.unsafe("INSERT INTO sources(id, name) VALUES ('ro-never', 'ro-never')")))
+ .rejects.toMatchObject({ code: '25006' });
+ });
+
+ test('the database lease is taken and released', async () => {
+ const lockId = `ro-lease-${randomUUID().slice(0, 8)}`;
+ const handle = await tryAcquireDbLock(engine!, lockId, 1);
+ expect(handle).not.toBeNull();
+ await handle!.release();
+ expect(await engine!.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id = $1', [lockId])).toHaveLength(0);
+ });
+
+ test('a Minions job is queued, claimed, run and recorded failed by a worker', async () => {
+ const job = await queue.add('ro-probe', {}, { max_attempts: 1 });
+ const worker = new MinionWorker(engine!, { pollInterval: 50 });
+ worker.register('ro-probe', async () => { throw new Error('handler failure'); });
+ const running = worker.start();
+ try {
+ await waitFor(async () => (await queue.getJob(job.id))?.status === 'dead', { timeoutMs: 30_000, label: 'probe job recorded dead' });
+ } finally {
+ worker.stop();
+ await running;
+ }
+ expect((await queue.getJob(job.id))!.error_text).toBe('handler failure');
+ }, 60_000);
+
+ test('#7187: the stall detector reclaims a job and drops a drain-lease holder row left active with expired locks', async () => {
+ const job = await queue.add('ro-stuck', {}, { max_attempts: 3 });
+ const claimed = await queue.claim('dead-worker:1', 60_000, 'default', ['ro-stuck']);
+ expect(claimed?.id).toBe(job.id);
+ // The worker died on refused writes: its error is on the row, its lock stopped renewing and expired.
+ await engine!.executeRaw(
+ `UPDATE minion_jobs SET lock_until = now() - interval '5 minutes', error_text = 'cannot execute INSERT in a read-only transaction' WHERE id = $1`,
+ [job.id]);
+ const stuck = { id: job.id };
+ const [beacon] = await engine!.executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs(name, queue, status, submission_authority, data, max_attempts, max_stalled, lock_token, lock_until, started_at, remove_on_complete, remove_on_fail)
+ VALUES ('sync', 'gbrain-drain-lease', 'active', '{"version":1,"kind":"application"}'::jsonb, '{"sourceId":"source-a"}'::jsonb, 1, 0,
+ 'dead-lease-token', now() - interval '5 minutes', now() - interval '10 minutes', true, true) RETURNING id`);
+ const { requeued, released } = await queue.handleStalled(0);
+ expect(requeued.map(j => j.id)).toEqual([stuck.id]);
+ expect(released.map(j => j.id)).toEqual([Number(beacon.id)]);
+ expect(await queue.getJob(stuck.id)).toMatchObject({ status: 'waiting', stalled_counter: 1, lock_token: null });
+ expect(await queue.getJob(Number(beacon.id))).toBeNull();
+ });
+});
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index a0cd35f1de..daa0d819ab 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -11,7 +11,7 @@
"out-of-scope:dream-verdicts": 3,
"out-of-scope:eval-capture": 5,
"out-of-scope:ingest-log": 2,
- "out-of-scope:internal-helper (private; exercised through public callers)": 19,
+ "out-of-scope:internal-helper (private; exercised through public callers)": 20,
"out-of-scope:lifecycle (connection, pool, transaction, raw seams)": 16,
"out-of-scope:no-sql-stub": 1,
"out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)": 11,
@@ -198,6 +198,7 @@
"rlsScopeBindingEnabled": "out-of-scope:internal-helper (private; exercised through public callers)",
"runMigration": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
"runUnsafe": "out-of-scope:internal-helper (private; exercised through public callers)",
+ "runUnsafeOnce": "out-of-scope:internal-helper (private; exercised through public callers)",
"runVectorAttempt": "out-of-scope:internal-helper (private; exercised through public callers)",
"searchKeyword": "cjk-search",
"searchKeywordChunks": "cjk-search",
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index faf4d6ffbc..eb95524627 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -67,6 +67,7 @@ export const DOMAIN_OF: Record<string, string> = {
'onCheckout': OOS.lifecycle,
'reconnect': OOS.lifecycle,
'runUnsafe': OOS.helper,
+ 'runUnsafeOnce': OOS.helper,
'executeRaw': OOS.lifecycle,
'executeRawDirect': OOS.lifecycle,
'keywordBoundedRead': OOS.lifecycle,
diff --git a/test/inherited-read-only-7183.test.ts b/test/inherited-read-only-7183.test.ts
new file mode 100644
index 0000000000..99ee416a43
--- /dev/null
+++ b/test/inherited-read-only-7183.test.ts
@@ -0,0 +1,120 @@
+/**
+ * #7183: a write the server refuses as read-only (SQLSTATE 25006) is named `connection_inherited_read_only` in the write
+ * receipt, the sync fault table, item failures and the agent envelope, and the engine's transaction and autocommit seams
+ * declare read-write. The end-to-end probe through a read-only server connection is
+ * test/e2e/pooler-inherited-read-only-7183.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { cliRenderContext, toAgentError } from '../src/core/agent-output.ts';
+import { classifyItemFailure } from '../src/core/item-failure.ts';
+import { databaseRefusal } from '../src/core/persistence/publication-failure.ts';
+import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';
+import { isWriteErrorCode } from '../src/core/persistence/types.ts';
+import { reservedTransactions } from '../src/core/postgres-engine/reserved-transactions.ts';
+import {
+ beginReadWrite, isReadOnlyTransactionError, readWriteTransactions, READ_WRITE_BEGIN, retryReadOnlyAutocommit,
+} from '../src/core/postgres-engine/read-write-transactions.ts';
+
+const readOnly = (statement = 'INSERT') => Object.assign(new Error(`cannot execute ${statement} in a read-only transaction`), { code: '25006' });
+
+/** A pool double: `begin(options, fn)` records its options and runs `fn` on a transaction handle. */
+function fakePool(opts: { beginError?: unknown } = {}) {
+ const begins: string[] = [];
+ const tx = { tag: 'tx' };
+ const pool = {
+ reserve: () => { throw new Error('unused'); },
+ begin: async (options: unknown, fn?: (tx: unknown) => Promise<unknown>) => {
+ const run = typeof options === 'function' ? options as (tx: unknown) => Promise<unknown> : fn!;
+ begins.push(typeof options === 'string' ? options : '');
+ if (opts.beginError && typeof options === 'string') throw opts.beginError;
+ return run(tx);
+ },
+ };
+ return { pool: pool as never, begins, tx };
+}
+
+describe('#7183 read-write transaction seams', () => {
+ test('beginReadWrite opens BEGIN READ WRITE on a pool', async () => {
+ const { pool, begins, tx } = fakePool();
+ expect(await beginReadWrite(pool, async handle => handle)).toBe(tx as never);
+ expect(begins).toEqual(['read write']);
+ });
+
+ test('a hot standby that refuses read-write mode at BEGIN gets the plain transaction (reads keep working)', async () => {
+ const refusal = Object.assign(new Error('cannot set transaction read-write mode during recovery'), { code: '0A000' });
+ const { pool, begins } = fakePool({ beginError: refusal });
+ expect(await beginReadWrite(pool, async () => 'read')).toBe('read');
+ expect(begins).toEqual(['read write', '']);
+ });
+
+ test('a transaction or reserved handle is not wrapped (a savepoint keeps its parent transaction)', () => {
+ const handle = { begin: () => undefined } as never;
+ expect(readWriteTransactions(handle)).toBe(handle);
+ });
+
+ test('an autocommit statement refused with 25006 runs once more inside BEGIN READ WRITE', async () => {
+ const { pool, begins, tx } = fakePool();
+ const seen: unknown[] = [];
+ const rows = await retryReadOnlyAutocommit(pool, async conn => {
+ seen.push(conn);
+ if (conn === pool) throw readOnly();
+ return ['row'];
+ });
+ expect(rows).toEqual(['row']);
+ expect(seen).toEqual([pool, tx]);
+ expect(begins).toEqual(['read write']);
+ });
+
+ test('no retry for other errors, inside a transaction, or for a statement that cannot run in a transaction block', async () => {
+ const { pool, begins } = fakePool();
+ await expect(retryReadOnlyAutocommit(pool, async () => { throw Object.assign(new Error('dup'), { code: '23505' }); })).rejects.toMatchObject({ code: '23505' });
+ const handle = { begin: () => undefined } as never;
+ await expect(retryReadOnlyAutocommit(handle, async () => { throw readOnly(); })).rejects.toMatchObject({ code: '25006' });
+ expect(begins).toEqual([]);
+ const original = readOnly('CREATE INDEX');
+ await expect(retryReadOnlyAutocommit(pool, async conn => {
+ throw conn === pool ? original : Object.assign(new Error('CREATE INDEX CONCURRENTLY cannot run inside a transaction block'), { code: '25001' });
+ })).rejects.toBe(original);
+ });
+
+ test('a reserved connection transaction opens with BEGIN READ WRITE', async () => {
+ const sent: string[] = [];
+ const reserved = {
+ unsafe: (text: string) => {
+ sent.push(text);
+ const done = Promise.resolve(Object.assign([], { command: text === 'commit' ? 'COMMIT' : 'BEGIN' }));
+ return Object.assign(done, { execute: () => done });
+ },
+ discard: () => undefined,
+ };
+ await reservedTransactions(reserved as never).begin(async () => 'ok');
+ expect(sent).toEqual([READ_WRITE_BEGIN, 'commit']);
+ });
+});
+
+describe('#7183 connection_inherited_read_only classification', () => {
+ test('the write receipt names it, not storage_error', () => {
+ const failure = databaseRefusal(readOnly());
+ expect(failure).toMatchObject({ code: 'connection_inherited_read_only', detail: { origin: 'database', sqlstate: '25006' } });
+ expect(failure!.message).toContain('read-only');
+ expect(isWriteErrorCode('connection_inherited_read_only')).toBe(true);
+ });
+
+ test('a sync item failure stops the run with the classified code', () => {
+ expect(classifyItemFailure(readOnly('SELECT FOR SHARE'))).toMatchObject({ code: 'connection_inherited_read_only', scope: 'run' });
+ });
+
+ test('sync status names it systemic and needing the database operator', () => {
+ const fault = classifySyncFault({ code: 'connection_inherited_read_only' });
+ expect(fault).toMatchObject({ class: 'systemic', safe_actions: ['none'], needs_human: true });
+ expect(fault.human_reason).toContain('default_transaction_read_only');
+ });
+
+ test('a raw 25006 becomes a typed envelope, not internal_error', () => {
+ expect(isReadOnlyTransactionError(readOnly())).toBe(true);
+ const env = toAgentError(readOnly(), { transport: 'cli', command: 'sync', render: cliRenderContext() });
+ expect(env).toMatchObject({ code: 'connection_inherited_read_only', class: 'host_only', retryable: false });
+ expect(env.suggestion).toContain('pooler');
+ expect(env.fix?.argv).toEqual(['gbrain', 'doctor', '--json']);
+ });
+});
diff --git a/test/persistence-bounded-read-session.test.ts b/test/persistence-bounded-read-session.test.ts
index 6f3e79bffa..3fb89f41b5 100644
--- a/test/persistence-bounded-read-session.test.ts
+++ b/test/persistence-bounded-read-session.test.ts
@@ -52,7 +52,7 @@ test('a session runs its bounded reads in one transaction; unbounded statements
await reads.executeRaw('SELECT 3 AS c');
await session.executeRaw('SELECT 4 AS unbounded');
});
- expect(conn.slice(0, 2)).toEqual(['BEGIN', expect.stringMatching(/^SET LOCAL statement_timeout = (5\d{4}|60000)$/)]);
+ expect(conn.slice(0, 2)).toEqual(['BEGIN READ WRITE', expect.stringMatching(/^SET LOCAL statement_timeout = (5\d{4}|60000)$/)]);
expect(conn.slice(2)).toEqual(['SELECT 1 AS a', 'SELECT 2 AS b', 'SELECT 3 AS c', 'COMMIT']);
expect(direct).toEqual([{ sql: 'SELECT 4 AS unbounded', timeoutMs: undefined }]);
// A read issued after the session settled (an abandoned preparation) runs on its own bounded transaction.
@@ -68,7 +68,7 @@ test('the bound in force is set again once it differs from a read\'s own bound b
await session.executeRaw('SELECT 3', [], { timeoutMs: 10_000 - BOUNDED_SESSION_SLACK_MS - 1 });
await session.executeRaw('SELECT 4', [], { timeoutMs: 20_000 });
});
- expect(conn).toEqual(['BEGIN', 'SET LOCAL statement_timeout = 10000', 'SELECT 1', 'SELECT 2',
+ expect(conn).toEqual(['BEGIN READ WRITE', 'SET LOCAL statement_timeout = 10000', 'SELECT 1', 'SELECT 2',
`SET LOCAL statement_timeout = ${10_000 - BOUNDED_SESSION_SLACK_MS - 1}`, 'SELECT 3', 'SET LOCAL statement_timeout = 20000', 'SELECT 4', 'COMMIT']);
});
@@ -86,7 +86,7 @@ test('a failed read rolls the transaction back, the reads it aborted run again,
expect(queued).toEqual({ status: 'fulfilled', value: [{ sql: 'SELECT queued' }] });
expect(await reads.executeRaw('SELECT after')).toEqual([{ sql: 'SELECT after' }]);
});
- expect(conn.filter(sql => /^(BEGIN|ROLLBACK|COMMIT)$/.test(sql))).toEqual(['BEGIN', 'ROLLBACK', 'BEGIN', 'COMMIT']);
+ expect(conn.filter(sql => /^(BEGIN READ WRITE|ROLLBACK|COMMIT)$/.test(sql))).toEqual(['BEGIN READ WRITE', 'ROLLBACK', 'BEGIN READ WRITE', 'COMMIT']);
expect(conn.filter(sql => sql === 'SELECT queued')).toHaveLength(2);
});
@@ -102,7 +102,7 @@ test('a screen inside a waiver run\'s session joins it: one transaction for both
await withBoundedReadSession(run, async screen => { expect(screen).toBe(run); await screen.executeRaw('SELECT 2', [], { timeoutMs: 10_000 }); });
});
expect(reserved).toBe(1);
- expect(conn).toEqual(['BEGIN', 'SET LOCAL statement_timeout = 10000', 'SELECT 1', 'SELECT 2', 'COMMIT']);
+ expect(conn).toEqual(['BEGIN READ WRITE', 'SET LOCAL statement_timeout = 10000', 'SELECT 1', 'SELECT 2', 'COMMIT']);
expect(prepared).toEqual([true, true]);
});