Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres): serve no longer wedges on a Supabase transaction pooler; deep health reports restart_required (#6543)
garrytanc3eabc2d656b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e34757e38e..71c4ba9c75 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,26 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.185.0] - 2026-10-12++**`gbrain serve` on a Supabase transaction pooler (:6543) no longer wedges. Answers stop landing on the wrong statement, and a persistence owner that needs a restart says so in `/health?deep=1` (#6543).** The vendored postgres driver sent several statements down one connection without waiting for each answer (pipelining). Supavisor's transaction mode can't carry pipelined statements across transaction boundaries. On a local Supavisor 2.5.1, 8 workers on a pool of 3 for 20 s gave 13 to 22 statements another statement's rows, plus connections that hung until the in-flight watchdog fired at 330 s. With pipelining off: 6078 ok, 0 errors. The two `pg_statement_build_failed UNDEFINED_VALUE` lines in the report were symptoms: each statement bound a column from a row that belonged to another statement. Three driver defects made it worse, and each is fixed here. Same-day mitigation for an older install: `PGMAX_PIPELINE=0` in serve's environment.++### Itemized changes++- **No pipelining on transaction-pooler URLs.** Read-side pools (module, engine instance, connection manager) default to `max_pipeline: 0` when the URL is on port 6543 or carries `?prepare=false`, or when `GBRAIN_PREPARE=0`. `resolveReadPoolPipeline` reads the URL itself, so `GBRAIN_PREPARE=1` can't hide a 6543 URL. Your explicit `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins. Direct connections and the Supabase session pooler on :5432 keep the driver default. PgBouncer transaction mode carries pipelining correctly. Turning it off measured no cost there. A new PgBouncer E2E pins `?max_pipeline=100` so pipelined-through-a-pooler coverage stays.+- **Driver: a dropped connection's error no longer poisons its replacement.** `closed()` now clears the saved error, result and row state on every close, not only during startup. Before, the next connection's first statement got the dead socket's `57P01` (direct) or `XX000 DbHandler exited` (Supavisor).+- **Driver: a statement that fails to build respects the pipeline limit.** Before, the connection always reported itself ready, so statements were sent behind the failed one even with `max_pipeline: 0`. `begin`'s `onexecute` runs once, after a successful build.+- **Driver: `UNDEFINED_VALUE` names the parameter.** The `pg_statement_build_failed` warn line now prints `param=$n`, and its text says that on a transaction pooler a build failure usually means a misrouted row. Every driver edit goes through `patches/[email protected]`. `test/postgres-driver-vendor.test.ts` checks all three vendored copies offline.+- **`/health?deep=1` stays report-only, with stable codes.** Each 503 carries `code`, `fix` and `docs`:+ - `persistence_restart_required` comes from the in-process consumer state and is checked before the pooled probe.+ - `pool_inflight_over_budget` covers a statement older than the pool budget.++ A `transport` block, read once at startup, shows `prepare`, `max_pipeline` and why, the server `statement_timeout` (`session_timeouts_not_applied` with the `ALTER ROLE` fix when the pooler drops it), and the backend `application_name` when it is Supavisor. Serve logs the same line at startup. The body never carries request ids, hostnames or credentials.+- **Opt-in self-exit: `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (n >= 120).** Serve exits with code 69 (`serve_unhealthy_exit`) after `restart_required` has held continuously for n seconds, so a `Restart=always` supervisor recovers it. The hold resets when the condition clears. Cleanup is bounded at 5 s. After 3 self-exits within an hour (recorded in `serve-self-exit.json` under the gbrain home), serve stops exiting, logs `serve_self_exit_suppressed`, and deep health asks for a manual restart. Off by default.+- **`--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` runs the sync's own consumer.** `forceOwnConsumer()` had no production caller, so with `persistence.single_consumer` on, an opted-out sync waited behind a wedged serve. Opt-out, a serve that doesn't answer its IPC socket, and a genuinely stale serve now force the sync's own consumer. A healthy current serve with delegation disabled (`unsupported_kind`, `unsupported_flag`, `kill_switch`) does not. Fallback lines stop claiming "uses its own consumer" on rungs that wait behind serve.+- **Read-only misroute audit: `scripts/audit-pooler-misroute.ts`.** Self-contained, so it runs from a v0.60.180.0 global install. It refuses a transaction-pooler URL and takes an explicit `--url` (direct or session pooler). Each bounded batch is one `REPEATABLE READ READ ONLY` transaction on a single connection. It reports `verified_ok`, `mismatch` and `unknown`, and rows changed during the audit or with missing history count as `unknown`, never as clean. Guide: `docs/guides/pooler-misroute-audit.md`. Any corrective write is a separate, approved step.+- **Corrected docs.** The claim that a server-side `statement_timeout` bounds every statement is corrected in `db.ts`, `consumer.ts`, `docs/ENGINES.md` and the error registry, since Supavisor drops the startup parameter. `docs/architecture/postgres-cancellation.md`, `docs/mcp/DEPLOY.md`, `docs/guides/exit-codes.md` and the error-code docs are updated. `GBRAIN_SUPAVISOR_URL` passes through `scripts/run-e2e.sh`.+## [0.60.184.0] - 2026-10-12**Unit and serial CI shards are packed from clean timings again.** CI splits each test lane across several machines using the recorded run time of every test file. The unit timings recorded before v0.60.183.0 carried a cold-boot penalty: three test files cleared the PGLite snapshot for every file after them in the same shard, so those files looked several minutes slower than they are. This release re-measures the unit and serial lanes from the first green master run after that fix. No product behaviour changes.diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex ff1c214e92..dc4183f10d 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -729,11 +729,14 @@ statement waited past the pool's `statement_timeout` plus a grace with nothingcoming back from the server, so the vendored driver retired that connection:the statement and every statement queued behind it failed with the driver error`CONNECTION_STUCK`, the connection left the pool before its socket closed, and-the pool reconnected on its own (#6383). A legitimate statement cannot outlive-the server-side timeout, so only a wedged connection reaches the budget: a-pipeline the client and server no longer agree on, a transaction-mode pooler-that swallowed a `CancelRequest` and left the backend in `ClientRead`, or a-dead peer. The budget is the pool's own startup `statement_timeout` (5 min on+the pool reconnected on its own (#6383). Usually only a wedged connection+reaches the budget: a pipeline the client and server no longer agree on, a+transaction-mode pooler that swallowed a `CancelRequest` and left the backend+in `ClientRead`, or a dead peer. It is not proof: behind a transaction-mode+pooler (port 6543) the startup `statement_timeout` never reaches the backend+(`SHOW statement_timeout` reads `0`; `/health?deep=1` reports it as+`transport.session_timeouts_not_applied`), so a legitimately slow statement can+reach the budget too (#6543). The budget is the pool's own startup `statement_timeout` (5 min onthe read pool, 30 min on the direct pool, `GBRAIN_STATEMENT_TIMEOUT` for theread pool) plus `GBRAIN_PG_STUCK_GRACE_MS` (default `30000`); it follows theconfigured timeout even through a pooler that drops the startup parameter, so a@@ -766,15 +769,22 @@ statement could not be built from its parameters (`error=UNDEFINED_VALUE`: aparameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534parameters). It was answered in its place in the pipeline by a query the serverrefuses, so only it failed and a transaction it was part of was aborted rather-than committed without it. No other statement was affected: before #6383 the same failure, when the statement was+than committed without it. Before #6383 the same failure, when the statement waspipelined behind another on its connection, rejected that other statement withits error, left the culprit queued with nothing on the wire, and delivered everylater reply one statement late until the process restarted (the`null is not an object (evaluating 'query.statement.types')` line and a backendstuck `active / ClientRead` were that desync). The line names the pool and the-statement by first keyword and table; the call site that bound `undefined` is a-gbrain bug, so report the line. `getPoolDiagnostics().buildFailures` counts-them.+statement by first keyword and table, and an `UNDEFINED_VALUE` line names the+parameter (`param=$2`, or `param=?` for an array element). Behind a+transaction-mode pooler (port 6543, `?prepare=false`) a build failure usually+means a misrouted answer: the statement bound a value read from a row that+belonged to another statement, so earlier reads on that pool are suspect too.+Check `/health?deep=1` `transport.max_pipeline` (gbrain sends `0` there since+v0.60.185.0; `PGMAX_PIPELINE=0` forces it) and audit the window with+[the pooler misroute audit](guides/pooler-misroute-audit.md). Elsewhere the+call site that bound `undefined` is a gbrain bug, so report the line.+`getPoolDiagnostics().buildFailures` counts them.<a id="pg-pool-stalled"></a>**`pg_pool_stalled`** (warn, resident processes).`gbrain serve` reads its pool every 30 s; when connections are checked out or@@ -789,7 +799,7 @@ the only trace a wedged pool leaves. A line that keeps repeating with norecovery means the database or pooler is unreachable from the process:`gbrain doctor --json` from a fresh process, then restart the stalled one.-**`/health?deep=1`** (`gbrain serve --http`). Plain `/health` stays the fast+<a id="serve-deep-health"></a>**`/health?deep=1`** (`gbrain serve --http`). Plain `/health` stays the fastliveness probe, and it runs its `SELECT 1` on a reserved connection, which thedriver only ever claims from idle connections; a wedged connection sits in thebusy queue where handler statements are routed, so `/health` answered 200@@ -804,6 +814,62 @@ same pool numbers ride the persistence consumer's heartbeat row, so`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.+Every 503 body carries a stable `code` with `fix` and `docs` from the error+registry (#6543):++- `persistence_restart_required`: this serve's persistence consumer reports+ `restart_required` (an abandoned preparation or a publication past its+ deadline), so it claims no write until the process restarts. Restart serve.+- `pool_inflight_over_budget`: a pooled statement has waited past the read+ pool's in-flight budget. Restart serve; behind a transaction-mode pooler read+ `transport` first and set `PGMAX_PIPELINE=0` if `max_pipeline` is not `0`.+ No request id or statement text reaches either body: the endpoint is+ unauthenticated.+- `deep_health_probe_failed` with `reason` `pending`, `timeout` or `error`: the+ pooled `SELECT 1` did not answer. Retry; if it persists, `gbrain doctor --json`.++Both 200 and 503 bodies carry `transport`, read once at startup through the+read pool and logged as a `[gbrain serve] transport` line:+`{ pooler_mode, prepare, max_pipeline, max_pipeline_reason, statement_timeout,+session_timeouts_not_applied, fix?, application_name? }`. `prepare` and+`max_pipeline` are the live pool's options; `max_pipeline_reason` says why+(`transaction_pooler_port`, `url_prepare_false`, `gbrain_prepare_off`,+`url_max_pipeline`, `env_pgmax_pipeline` or `default`): gbrain builds the read+pools with `max_pipeline: 0` for a transaction-mode URL (port 6543 or+`?prepare=false`) or `GBRAIN_PREPARE=0` since v0.60.185.0, and a URL+`?max_pipeline=` or a non-empty `PGMAX_PIPELINE` always wins.+`application_name: "Supavisor"` appears when the backend names Supavisor.+`session_timeouts_not_applied: true` means gbrain configured a+`statement_timeout` but it reads `0` through the pool (a transaction-mode+pooler drops startup parameters), so no server-side timeout bounds an+autocommit statement; `fix` is the same `ALTER ROLE` the+doctor's `persistence_session_timeouts` check prints+([troubleshooting](guides/troubleshooting.md#session-timeouts-not-applied)).+The endpoint is unauthenticated, so it only reports: it never retires a+connection or restarts anything.++<a id="serve-unhealthy-exit"></a>To let a supervisor recover a wedged serve+without a human, set `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (off by default;+`n` must be a whole number of at least `120`, and a smaller value refuses to+start with `invalid_params`). When `persistence_restart_required` has held+continuously for `n` seconds (read in-process; the hold restarts whenever the+stuck work settles and the flag clears), serve logs+`[gbrain serve] error code=serve_unhealthy_exit cause=persistence_restart_required`,+disconnects under a 5 s deadline (the consumer's stop waits on the stuck work,+so the exit never depends on it draining) and exits `69`.+`pool_inflight_over_budget` never triggers the exit (the variable is named for+its one trigger): restart serve yourself or from your health check. A loop+guard records each self-exit in `serve-self-exit.json` under the gbrain home;+after 3 self-exits within an hour serve stops exiting, logs+`serve_self_exit_suppressed`, and the deep-health 503 carries+`self_exit_suppressed: true` with a fix that asks for a manual restart and a+look at `gbrain sources writer status --json`.+The service `gbrain mcp expose` installs restarts it (systemd `Restart=always`,+launchd `KeepAlive`), so a fresh serve comes up; the floor keeps a restart loop+under the systemd unit's start limit (10 starts per 300 s). For the installed service put the variable+in `~/.gbrain/env`; for a foreground serve set it in the shell or your own+supervisor's environment. A foreground serve with no supervisor just exits.+<a id="backfill-rollback-failed"></a>**`backfill_rollback_failed`** (error).A `gbrain backfill` batch failed, and its `ROLLBACK` failed too. The run stopsrather than retrying on a connection whose transaction state is unknown; thediff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 88a9b58d86..44c85ff2f7 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -24,7 +24,7 @@- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve read: the stamp or frozen record, else the brain's cwd chain once (frozen, tier `engine`); legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`); doctor `memory_writeback` reports `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.-- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) keeps the CLI's own consumer with one actionable line. Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).+- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-only `labeled_credential` rule (`ScanOpts.labeledCredentials`) lives in `secret-scan-labeled.ts` (Security). The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex c3285aa038..36fb720034 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. OAuth discovery's `scopes_supported` (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from `scopesSupportedForDiscovery({ enableDcr })` in `src/core/scope.ts`: with `--enable-dcr` it is exactly the self-registration ceiling (`read write`), so a client that copies discovery into its `/register` request succeeds; without DCR it is every scope except operator-only `agent`. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and per-IP `express-rate-limit` buckets: the MCP SDK's defaults on `/authorize` (100 / 15 min), `/register` (20 / hour) and `/token` (50 / 15 min) because `authRouterOptions` passes no `rateLimit: false`, the custom `client_credentials` handler's `ccRateLimiter`, and independent owner limits: 60 total authentication requests/min/IP, 10 failed authentications/min/IP (verified authority, independent of response status), and 60 consent requests/min/authenticated session in `serve-http-admin-limits.ts`. Admin no-store, no-referrer and framing headers precede login/link handlers. Explicit pending IDs survive fresh-browser links; invalid or restarted requests require native authorization to restart. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` in `serve-http-registration.ts` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging. DCR startup copy: the SECURITY WARNING states self-registered clients are limited to read/write (read-only for `client_credentials` under `--enable-dcr-insecure`) and that every authorization_code connection needs owner approval in the admin UI; banner `DCR:` values are `enabled (consent; DCR max read write)` / `enabled (INSECURE: read-only M2M)` / `disabled`.Layout: `runServeHttp` binds through `listenOrRefuse` (`serve-http-listen.ts`: `serve_port_in_use` on a taken port; with `options.adoptServer` from status-only recovery it hands the app to the already-bound listener instead of binding). `buildServeHttpApp` builds one shared `ServeHttpContext` (sessions, nonce stores, limiters, `requireAdmin`, SSE fan-out, OAuth provider, resource verifier, non-`localOnly` op list) and mounts in registration order `serve-http-oauth.ts` (CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent), `serve-http-metrics.ts` (`/health`, `/metrics`, probes), `serve-http-admin-api.ts` (`requireAdmin`, `/admin/login`, `/admin/api/*`, `/admin/events`), `serve-http-spa.ts`, `serve-http-mcp.ts` (`/mcp`; writes `[gbrain-serve] dispatch op=<name> args_sha256=<16 hex>` to stderr before each tool call so a stall's last line names its request, never the arguments) and `serve-http-webhooks.ts` (`/ingest`, which maps a legacy-authority `permission_denied` from submission to 409 `{error, message, hint, docs_url}` (`test/serve-http-ingest-legacy.test.ts`) and every other submission error to 500, `/webhooks/github`); `runServeHttp` keeps listen, banner, resolve-IPC binding and shutdown, and the façade re-exports moved symbols. Order is pinned by `test/serve-http-route-golden.test.ts` (AST) and `test/serve-http-route-runtime-golden.test.ts` (router stack). Size ceiling: `scripts/module-size-limits.tsv`.-- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block).+- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block). #6543: after the pool stall watch, `recordServeTransport` (`src/commands/serve-health.ts`) reads the read pool's transport once (live `prepare`/`max_pipeline` with `max_pipeline_reason`, the doctor probe's `SHOW statement_timeout` and its ALTER ROLE fix when a configured timeout reads 0, `application_name` when Supavisor), logs one `[gbrain serve] transport` line and caches it for `/health?deep=1` (never re-read per probe). `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (>= 120, else `invalid_params` at start) arms `installRestartRequiredExit`: an in-process `restart_required` held continuously for n seconds (the hold resets when it clears) disconnects under a 5 s deadline and exits `SERVE_UNHEALTHY_EXIT_CODE` (69, `serve_unhealthy_exit`); a durable ledger (`serve-self-exit.json` under the gbrain home) suppresses the exit after 3 within an hour (`serve_self_exit_suppressed`, `self_exit_suppressed` in the deep 503). `probeDeepHealth` (`serve-http-metrics.ts`) answers 503 `persistence_restart_required` before its pooled probe, `pool_inflight_over_budget` or `deep_health_probe_failed` (`reason`), each with `fix`/`docs` from the registry and the cached `transport`, no request ids. Pinned by `test/serve-health-6543.test.ts` (a real `PersistenceConsumer` driven to restart_required).- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex b7dd8234c8..c8734a9b3e 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/db-repair-receipts.ts` — the shared seam between `gbrain db-repair` (writer) and doctor's `db_repair_recurrence` check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at `~/.gbrain/db-repair-receipts.jsonl`; row shape `{ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'}` — only `applied` rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT `applied` rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns `rewriteCooldownBlocked` (24h per (reason, action), rewrite tier only).-- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`. `resolveUrlConnectTimeout(url)` supplies `connect_timeout` to the same four call sites from each pool's own URL query (postgres.js lets the explicit option win over the URL, so the URL value is honoured only through this resolver): whole seconds, capped at the runtime's 2^31-1 ms timer limit; `0`, junk or no parameter means 10s. Pinned by `test/db-connect-timeout.test.ts`. `connectWithRetry` retries the `isRetryableConnError` set (3 attempts, 1s/2s backoff; `GBRAIN_NO_RETRY_CONNECT=1` makes it one); `retryConnectTimeout: true` adds postgres.js `CONNECT_TIMEOUT` (`isConnectTimeoutError` in `retry-matcher.ts`) and is passed only by the per-worker pools of parallel import and incremental sync, whose URL the parent engine already reached (#5946), so a first connect still fails fast on a timeout. Pinned by `test/worker-pool-connect-retry.test.ts`.+- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`. `resolveUrlConnectTimeout(url)` supplies `connect_timeout` to the same four call sites from each pool's own URL query (postgres.js lets the explicit option win over the URL, so the URL value is honoured only through this resolver): whole seconds, capped at the runtime's 2^31-1 ms timer limit; `0`, junk or no parameter means 10s. Pinned by `test/db-connect-timeout.test.ts`. `connectWithRetry` retries the `isRetryableConnError` set (3 attempts, 1s/2s backoff; `GBRAIN_NO_RETRY_CONNECT=1` makes it one); `retryConnectTimeout: true` adds postgres.js `CONNECT_TIMEOUT` (`isConnectTimeoutError` in `retry-matcher.ts`) and is passed only by the per-worker pools of parallel import and incremental sync, whose URL the parent engine already reached (#5946), so a first connect still fails fast on a timeout. Pinned by `test/worker-pool-connect-retry.test.ts`. #6543: `resolveReadPoolPipeline(url)` returns `{ value, reason }` for the three read-side pools (module singleton, instance pool, connection-manager read pool; `readPoolPipelineOptions` spreads it): `0` for a transaction-mode URL (port 6543 or `?prepare=false`, read from the URL because `GBRAIN_PREPARE` wins inside `resolvePrepare`) or `GBRAIN_PREPARE=0`, the key omitted (driver default 100, never `undefined`) for a session pooler or direct URL, and omitted whenever the URL names `max_pipeline` or `PGMAX_PIPELINE` is non-empty, since the driver lets the options object outrank both; pinned by `test/read-pool-pipeline-6543.test.ts` and `test/e2e/pgbouncer-pipelined-read-pool.test.ts`.- `src/core/degraded-engine.ts` + `src/core/degraded-marker.ts` — degraded-mode serve, STARTUP-SCOPED by design: when Postgres is unreachable at `gbrain serve` startup, serve boots on `createDegradedEngine` (a concrete object whose method set is enumerated from PostgresEngine's prototype at construction — no dynamic `get` trap; `kind` is an explicit getter, read synchronously at ~29 branch sites; `disconnect()` is a no-op while dead so shutdown never triggers a reconnect) instead of dying. Every tool call attempts ONE reconnect (single-flight across concurrent callers, min-interval gated ~5s — no connect storms against a dying pooler); calls inside the window throw the STORED original error (stale-but-honest, refreshed on every real attempt) so MCP dispatch classifies the REAL error shape into the `database_error` envelope + marker. The `reconnect` callback is the FULL deferred connectEngine (config merge, gateway, migrations — guarded in cli.ts: a vanished config.json throws instead of connectEngine's process.exit killing the live server); first success swaps in the live engine permanently and fires recovery callbacks (serve re-runs deferred boot + sends `tools/list_changed` — clients that handshook degraded hold the reduced gate-hidden catalog and must refresh; the callback is a no-op once shutdown has started) — but the TRIGGERING call gets `DegradedRecoveredRetryError`, never a result: its source scope was resolved under the degraded fallback, so one client retry buys scope correctness (no call ever executes under the fallback scope against a live engine). Callers waiting on an in-flight attempt are latency-capped (`callerWaitMs`, default 2s — they get the stored error while the attempt finishes in the background, so a timeout-class failure can't stall the MCP handshake). Prototype GETTERS delegate too (throw the stored error while dead — never a silent `undefined`); `DEGRADED_LAST_ERROR` is a read-only accessor for the stored diagnosis (drives the HTTP `/health` degraded reason without consuming a reconnect). Serve-side degraded posture: source scope honors a validated `GBRAIN_SOURCE` (tier `env`) before seed_default, and `stdioVisibleTools` fail-closes every gated op WITHOUT touching the engine. The degraded gate keys on the RESOLVED brain's engine (a PGLite mount on a postgres host keeps die-on-startup). Mid-session outages ride `PostgresEngine.reconnect()` + per-call classified envelopes — degraded mode adds no mid-session state; PGLite startup failures keep die-on-startup (single-writer lock makes a lazy proxy wrong there; that lane's repair is pglite-repair). Kill switch `GBRAIN_SERVE_DEGRADED=0` (or `false`); structured `[gbrain-serve] DEGRADED/RECOVERED` stderr lines. `degraded-marker.ts` is the dependency-free seam (`Symbol.for`-registered markers + `isEngineDegraded`/`onEngineRecovered`/`degradedLastError`) so server.ts/serve.ts/http-transport.ts can ask about degraded state without importing the heavy Postgres engine module.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 45964b940b..11d835d5af 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -38,7 +38,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. `withReservedConnection(fn, { selfContained: true })` (migration DDL, `buildIndexOnline`, backfill batches: `fn` touches only its reserved connection, like a transaction) may take the only connection of a one-connection ordinary pool, never the only direct session; pinned by `test/pool-budget.test.ts` and `test/e2e/pool-size-one-migrations.test.ts`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.-- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`).+- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`). `formatBuildFailureWarning` appends `param=$n` (or `param=?` for an array element) to an `UNDEFINED_VALUE` line from the driver's `onbuilderror(code, statement, parameter)` (#6543).- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.diff --git a/docs/architecture/postgres-cancellation.md b/docs/architecture/postgres-cancellation.mdindex 6f7178426e..a6a559ba86 100644--- a/docs/architecture/postgres-cancellation.md+++ b/docs/architecture/postgres-cancellation.md@@ -28,7 +28,7 @@ Direct PostgreSQL closes the cancellation connection after handling the request.`test/e2e/persistence-chaos.test.ts` exercises active, queued, delayed and failed cancellation; transaction siblings; stale ownership; atomic reservation settlement; reconnects; completed cursors; and real socket backpressure in both module formats. Its optional PgBouncer case requires `GBRAIN_PGBOUNCER_URL` and `GBRAIN_PGBOUNCER_DIRECT_URL`, uses a dedicated test database, and verifies another client can reuse the same server backend without receiving a late cancellation.-Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation.+Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation. The one place pipelining is off is transport, not cancellation: since v0.60.185.0 the read pools of a transaction-mode pooler URL (port 6543, `?prepare=false`, `GBRAIN_PREPARE=0`) are built with `max_pipeline: 0`, because a transaction pooler cannot carry pipelined statements across transaction boundaries (#6543; `db.resolveReadPoolPipeline`, the reason is in `/health?deep=1` `transport`). A URL `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins, and the direct pool keeps the driver default.## Worker admission and configuration shutdowndiff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex f49588dd3a..babdad98cc 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -719,6 +719,18 @@ More: [docs/guides/core-memory.md#remote-edits](../../docs/guides/core-memory.md|---|---|---|---|---|---|---|| The brain database could not be reached or refused the operation. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |+### deep_health_probe_failed++<a id="deep_health_probe_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The pooled `SELECT 1` of `/health?deep=1` did not answer: an earlier probe is still pending, it timed out, or it failed. | The deep probe runs through the ordinary pooled dispatch, where handler statements wait, so a saturated or wedged pool fails it while plain /health (a reserved idle connection) may still answer 200. One deep probe runs per engine at a time. | Retry in a few seconds; if it keeps failing, run gbrain doctor --json from a fresh process to check the database and pooler, then restart this gbrain serve. | agent | `repeat the read that failed` | 1 | yes |++Reasons: `pending`, `timeout`, `error`.++More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-health)+### delta_cursor_upgrade_required<a id="delta_cursor_upgrade_required"></a>@@ -2045,6 +2057,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| This caller is not authorized for the operation. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+### persistence_restart_required++<a id="persistence_restart_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This gbrain serve's persistence consumer reports restart_required, so it claims no write until the process restarts; `/health?deep=1` answers 503 with this code. | A preparation abandoned past the ceiling (a zombie) or a publication that never settled past its deadline makes the owner stop claiming on every root, because the abandoned work may still hold locks or write files; only a process exit releases it. The deep health probe reports it so a supervisor can restart serve; it never acts on its own (GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS opts into an exit). | Restart this gbrain serve (systemctl --user restart gbrain-serve, or stop and start the foreground process); to let a supervisor do it unattended, set GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=300 in the serve environment (~/.gbrain/env for the installed service). Then run gbrain sources writer status --json. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-health)+### persistence_write_stall<a id="persistence_write_stall"></a>@@ -2061,7 +2083,7 @@ More: [docs/guides/troubleshooting.md#persistence-write-stall](../../docs/guides| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| 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. | 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. | 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. Run: gbrain doctor --json | agent | `repeat the read that failed` | 1 | yes |+| 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. | Nothing arriving for that long usually means the connection 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. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too, and the clock restarts on every byte, so a statement that keeps streaming is never retired. 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. | 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. Run: gbrain doctor --json | agent | `repeat the read that failed` | 1 | yes |More: [docs/ENGINES.md#pg-connection-stuck](../../docs/ENGINES.md#pg-connection-stuck)@@ -2081,7 +2103,7 @@ More: [docs/ENGINES.md#pg-pool-stalled](../../docs/ENGINES.md#pg-pool-stalled)| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| 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. | 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. | 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. | host_admin | `gbrain doctor --json` | 1 | no |+| 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; it failed, and a transaction it was part of was aborted rather than committed without it. | Either a gbrain programming error at the call site the warn line names by keyword and table (and by `param=$n`), or, behind a transaction-mode pooler (port 6543, prepare off), a value read from a row that belonged to another statement: a pooler that misroutes pipelined answers hands a statement someone else's row, and binding one of its missing columns fails here. 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. | On a transaction-mode pooler, check /health?deep=1 transport (max_pipeline should be 0; PGMAX_PIPELINE=0 on the serve environment forces it) and treat earlier reads as suspect (docs/guides/pooler-misroute-audit.md); otherwise report the warn line (it names the statement and parameter) as a gbrain bug so the call site gets a null where it bound undefined. | host_admin | `gbrain doctor --json` | 1 | no |More: [docs/ENGINES.md#pg-statement-build-failed](../../docs/ENGINES.md#pg-statement-build-failed)@@ -2121,6 +2143,16 @@ More: [docs/ENGINES.md#pglite-vector-index-ceiling](../../docs/ENGINES.md#pglite|---|---|---|---|---|---|---|| The saved plan has no valid repository identity. | 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 |+### pool_inflight_over_budget++<a id="pool_inflight_over_budget"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A pooled statement of this gbrain serve has waited longer than the read pool's in-flight budget (statement_timeout plus grace); `/health?deep=1` answers 503 with this code. | The in-flight watchdog retires a connection only after nothing arrives for the budget, so a statement that keeps receiving bytes, or one behind a transaction-mode pooler where no server statement_timeout applies, can sit past it while every statement queued behind it waits. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated. | Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-health)+### port_in_use<a id="port_in_use"></a>@@ -2579,6 +2611,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| gbrain serve --http could not listen: another process already holds that host and port. | A capability this request needs is not configured or not reachable on this brain. | Stop the process on that port, or start the server with another --port and point the harnesses at it. | agent | `gbrain doctor --json` | 1 | no |+### serve_self_exit_suppressed++<a id="serve_self_exit_suppressed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain serve stayed at restart_required past GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS but did not exit, because it had already exited on its own 3 times within the hour; `/health?deep=1` reports self_exit_suppressed. | The opt-in self-exit keeps a durable ledger (serve-self-exit.json under the gbrain home). A serve that reaches restart_required again right after every restart has a cause a restart does not fix, so after 3 self-exits in an hour it keeps serving reads and leaves the decision to a human instead of looping. | Run gbrain sources writer status --json and gbrain doctor --json, report both with the serve log lines, then restart serve by hand. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/ENGINES.md#serve-unhealthy-exit](../../docs/ENGINES.md#serve-unhealthy-exit)+### serve_status_only<a id="serve_status_only"></a>@@ -2589,6 +2631,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cReasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_unopenable`, `repair_failed`, `unavailable`.+### serve_unhealthy_exit++<a id="serve_unhealthy_exit"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS. | Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner. | Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line. | agent | `gbrain doctor --json` | 69 | no |++More: [docs/ENGINES.md#serve-unhealthy-exit](../../docs/ENGINES.md#serve-unhealthy-exit)+### setup_harness_unsupported<a id="setup_harness_unsupported"></a>diff --git a/docs/guides/exit-codes.md b/docs/guides/exit-codes.mdindex 2458c172b6..0e8d15c95e 100644--- a/docs/guides/exit-codes.md+++ b/docs/guides/exit-codes.md@@ -16,6 +16,7 @@ the exit code first, then reads the JSON document (`--json`) for the details:| 3 | `confirmation_required`: nothing ran | consent payload (`effects`, `user_message`, `fix`) | stop, relay `user_message` to the user, run `fix.command` only after they agree || 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0 || 11 | partial, resumable budget stop | result with `remaining_*` and `resume_command` | run `resume_command` (it is safe to re-run) |+| 69 | `gbrain serve` exited on its own after its persistence consumer reported `restart_required` for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` (`serve_unhealthy_exit`; opt-in) | `[gbrain serve] error code=serve_unhealthy_exit` line on stderr | nothing: the supervisor (the installed service restarts on failure) starts a fresh serve; if it repeats, follow [the unhealthy exit](../ENGINES.md#serve-unhealthy-exit) || 75 | another runner holds the migration lock, or an engine graduation owns the brain (`graduation_in_progress`) | error envelope | wait for the other runner, then retry || 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) || 130 | interrupted (SIGINT) | error envelope | ask the user whether to re-run |diff --git a/docs/guides/pooler-misroute-audit.md b/docs/guides/pooler-misroute-audit.mdnew file mode 100644index 0000000000..22e4e1b996--- /dev/null+++ b/docs/guides/pooler-misroute-audit.md@@ -0,0 +1,77 @@+# Pooler misroute audit++A brain whose `gbrain serve` read pool pipelined statements through a+transaction-mode pooler (Supavisor or PgBouncer on port 6543, or a URL with+`?prepare=false`) before v0.60.185.0 could hand a statement another+statement's rows (#6543). Most of the time that failed loudly+(`pg_statement_build_failed` with `error=UNDEFINED_VALUE`, `pg_connection_stuck`),+but a statement that bound a value from someone else's row and succeeded+leaves a persistence row whose identity belongs to another row.+`scripts/audit-pooler-misroute.ts` looks for those rows. It only reads.++**Say to your agent:** *"Run the gbrain pooler misroute audit for the window+the serve ran through the transaction pooler, and show me the result before+changing anything."*++## When to run it++Run it once after upgrading if, before the upgrade, any of these held for a+serve or worker on the brain:++- the database URL used port 6543 or `?prepare=false`;+- the log carried `pg_statement_build_failed`, `pg_connection_stuck` or+ `pg_connection_desync` lines;+- `/health?deep=1` showed `transport.max_pipeline` other than `0` behind such a+ URL.++The window is from the first such serve start (or the first warn line) until+the upgraded serve started.++## Run++The script is one self-contained file: it needs no checkout and imports+nothing from gbrain, only the postgres driver your install already ships+(`vendor/postgres` under the gbrain install; set+`GBRAIN_AUDIT_POSTGRES_DRIVER=<path to vendor/postgres/src/index.js>` if it is+not found). On a host without a checkout, copy `scripts/audit-pooler-misroute.ts`+from the gbrain repository at this version or later, then:++```bash+bun audit-pooler-misroute.ts \+ --url 'postgresql://postgres:<password>@db.<project>.supabase.co:5432/postgres' \+ --since 2026-10-01T00:00:00Z --until 2026-10-12T18:00:00Z --json > audit.json+```++- `--url` is explicit (never read from the environment) and must be the direct+ URL or the session pooler (Supabase: port 5432). A transaction-mode URL (port+ 6543 or `?prepare=false`) is refused: the audit must not read through the+ transport it audits. It opens one connection.+- Each batch (`--batch-size`, default 500 rows) is one+ `REPEATABLE READ READ ONLY` transaction with a transaction-local timeout+ (`--batch-timeout-ms`, default 15000). There is no snapshot across batches;+ a row written while the audit runs is reported `unknown`+ (`changed_during_audit`). Running it beside a live serve is safe.+- Exit `0`: no mismatch. Exit `1`: at least one mismatch. Exit `2`: usage error+ or refused URL.++## Read the result++- `verified_ok` counts requests and effects whose identity values all agree.+- `mismatch` lists each row and field whose value belongs to another row:+ an effect whose `source_id`, `source_incarnation` or `worktree_id` differs+ from its own request (they are copied in one statement), a request whose+ `source_incarnation` is another source's (`belongs_to`), or a request whose+ `page_id` names a page in another source.+- `unknown` lists rows the audit cannot judge, with `reasons`+ (`unknown_by_reason` counts them): `changed_during_audit`,+ `compacted_history`, `token_reclaimed` (the claim stamp names another+ execution token), `source_removed`, `source_reincarnated`, `page_removed`,+ `page_slug_differs` (usually a later move) and `effect_identity_unset` (rows+ from before those columns). Unknown is not clean: it is a coverage gap.++## After a mismatch++Do not repair anything from the audit alone. A corrective write is a one-way+door: send `audit.json` (it holds row ids and identity values, no page+content) with the serve logs of the window to the brain's owner, and decide+the fix together from a preview. Re-running the audit is always safe.diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.mdindex 79ed8f3286..5a30203230 100644--- a/docs/mcp/DEPLOY.md+++ b/docs/mcp/DEPLOY.md@@ -690,7 +690,18 @@ Retry-After: 5(`checked_out`, `waiters`, `inflight_oldest_ms`, `stuck_discards`, …) andanswers 503 when the probe times out or a statement is past the pool'sin-flight budget ([pool diagnostics](../ENGINES.md#pg-connection-stuck)). A- two-minute interval is fine; one deep probe runs at a time.+ two-minute interval is fine; one deep probe runs at a time. Every 503 names a+ stable `code` (`persistence_restart_required`, `pool_inflight_over_budget`,+ `deep_health_probe_failed`) with `fix` and `docs`, and both answers carry the+ `transport` block (pooler mode, `max_pipeline`, the server+ `statement_timeout`); the probe only reports+ ([serve deep health](../ENGINES.md#serve-deep-health)).+- To have serve restart itself when it stays unhealthy, set+ `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (at least `120`; in `~/.gbrain/env`+ for the service `gbrain mcp expose` installs). After `n` continuous seconds+ of `persistence_restart_required` it exits `69` (`serve_unhealthy_exit`,+ cleanup bounded at 5 s; at most 3 self-exits per hour) and the supervisor starts a fresh one+ ([unhealthy exit](../ENGINES.md#serve-unhealthy-exit)).- A second `gbrain serve --http` on a port another server already holds exitswith `serve_port_in_use`. A Postgres connect failure keeps the degraded-enginepath (`GBRAIN_DB_ACCESS` marker, `gbrain db-repair`).diff --git a/llms-full.txt b/llms-full.txtindex 4ae3aad621..68116cecba 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5837,11 +5837,14 @@ statement waited past the pool's `statement_timeout` plus a grace with nothingcoming back from the server, so the vendored driver retired that connection:the statement and every statement queued behind it failed with the driver error`CONNECTION_STUCK`, the connection left the pool before its socket closed, and-the pool reconnected on its own (#6383). A legitimate statement cannot outlive-the server-side timeout, so only a wedged connection reaches the budget: a-pipeline the client and server no longer agree on, a transaction-mode pooler-that swallowed a `CancelRequest` and left the backend in `ClientRead`, or a-dead peer. The budget is the pool's own startup `statement_timeout` (5 min on+the pool reconnected on its own (#6383). Usually only a wedged connection+reaches the budget: a pipeline the client and server no longer agree on, a+transaction-mode pooler that swallowed a `CancelRequest` and left the backend+in `ClientRead`, or a dead peer. It is not proof: behind a transaction-mode+pooler (port 6543) the startup `statement_timeout` never reaches the backend+(`SHOW statement_timeout` reads `0`; `/health?deep=1` reports it as+`transport.session_timeouts_not_applied`), so a legitimately slow statement can+reach the budget too (#6543). The budget is the pool's own startup `statement_timeout` (5 min onthe read pool, 30 min on the direct pool, `GBRAIN_STATEMENT_TIMEOUT` for theread pool) plus `GBRAIN_PG_STUCK_GRACE_MS` (default `30000`); it follows theconfigured timeout even through a pooler that drops the startup parameter, so a@@ -5874,15 +5877,22 @@ statement could not be built from its parameters (`error=UNDEFINED_VALUE`: aparameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534parameters). It was answered in its place in the pipeline by a query the serverrefuses, so only it failed and a transaction it was part of was aborted rather-than committed without it. No other statement was affected: before #6383 the same failure, when the statement was+than committed without it. Before #6383 the same failure, when the statement waspipelined behind another on its connection, rejected that other statement withits error, left the culprit queued with nothing on the wire, and delivered everylater reply one statement late until the process restarted (the`null is not an object (evaluating 'query.statement.types')` line and a backendstuck `active / ClientRead` were that desync). The line names the pool and the-statement by first keyword and table; the call site that bound `undefined` is a-gbrain bug, so report the line. `getPoolDiagnostics().buildFailures` counts-them.+statement by first keyword and table, and an `UNDEFINED_VALUE` line names the+parameter (`param=$2`, or `param=?` for an array element). Behind a+transaction-mode pooler (port 6543, `?prepare=false`) a build failure usually+means a misrouted answer: the statement bound a value read from a row that+belonged to another statement, so earlier reads on that pool are suspect too.+Check `/health?deep=1` `transport.max_pipeline` (gbrain sends `0` there since+v0.60.185.0; `PGMAX_PIPELINE=0` forces it) and audit the window with+[the pooler misroute audit](guides/pooler-misroute-audit.md). Elsewhere the+call site that bound `undefined` is a gbrain bug, so report the line.+`getPoolDiagnostics().buildFailures` counts them.<a id="pg-pool-stalled"></a>**`pg_pool_stalled`** (warn, resident processes).`gbrain serve` reads its pool every 30 s; when connections are checked out or@@ -5897,7 +5907,7 @@ the only trace a wedged pool leaves. A line that keeps repeating with norecovery means the database or pooler is unreachable from the process:`gbrain doctor --json` from a fresh process, then restart the stalled one.-**`/health?deep=1`** (`gbrain serve --http`). Plain `/health` stays the fast+<a id="serve-deep-health"></a>**`/health?deep=1`** (`gbrain serve --http`). Plain `/health` stays the fastliveness probe, and it runs its `SELECT 1` on a reserved connection, which thedriver only ever claims from idle connections; a wedged connection sits in thebusy queue where handler statements are routed, so `/health` answered 200@@ -5912,6 +5922,62 @@ same pool numbers ride the persistence consumer's heartbeat row, so`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.+Every 503 body carries a stable `code` with `fix` and `docs` from the error+registry (#6543):++- `persistence_restart_required`: this serve's persistence consumer reports+ `restart_required` (an abandoned preparation or a publication past its+ deadline), so it claims no write until the process restarts. Restart serve.+- `pool_inflight_over_budget`: a pooled statement has waited past the read+ pool's in-flight budget. Restart serve; behind a transaction-mode pooler read+ `transport` first and set `PGMAX_PIPELINE=0` if `max_pipeline` is not `0`.+ No request id or statement text reaches either body: the endpoint is+ unauthenticated.+- `deep_health_probe_failed` with `reason` `pending`, `timeout` or `error`: the+ pooled `SELECT 1` did not answer. Retry; if it persists, `gbrain doctor --json`.++Both 200 and 503 bodies carry `transport`, read once at startup through the+read pool and logged as a `[gbrain serve] transport` line:+`{ pooler_mode, prepare, max_pipeline, max_pipeline_reason, statement_timeout,+session_timeouts_not_applied, fix?, application_name? }`. `prepare` and+`max_pipeline` are the live pool's options; `max_pipeline_reason` says why+(`transaction_pooler_port`, `url_prepare_false`, `gbrain_prepare_off`,+`url_max_pipeline`, `env_pgmax_pipeline` or `default`): gbrain builds the read+pools with `max_pipeline: 0` for a transaction-mode URL (port 6543 or+`?prepare=false`) or `GBRAIN_PREPARE=0` since v0.60.185.0, and a URL+`?max_pipeline=` or a non-empty `PGMAX_PIPELINE` always wins.+`application_name: "Supavisor"` appears when the backend names Supavisor.+`session_timeouts_not_applied: true` means gbrain configured a+`statement_timeout` but it reads `0` through the pool (a transaction-mode+pooler drops startup parameters), so no server-side timeout bounds an+autocommit statement; `fix` is the same `ALTER ROLE` the+doctor's `persistence_session_timeouts` check prints+([troubleshooting](guides/troubleshooting.md#session-timeouts-not-applied)).+The endpoint is unauthenticated, so it only reports: it never retires a+connection or restarts anything.++<a id="serve-unhealthy-exit"></a>To let a supervisor recover a wedged serve+without a human, set `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (off by default;+`n` must be a whole number of at least `120`, and a smaller value refuses to+start with `invalid_params`). When `persistence_restart_required` has held+continuously for `n` seconds (read in-process; the hold restarts whenever the+stuck work settles and the flag clears), serve logs+`[gbrain serve] error code=serve_unhealthy_exit cause=persistence_restart_required`,+disconnects under a 5 s deadline (the consumer's stop waits on the stuck work,+so the exit never depends on it draining) and exits `69`.+`pool_inflight_over_budget` never triggers the exit (the variable is named for+its one trigger): restart serve yourself or from your health check. A loop+guard records each self-exit in `serve-self-exit.json` under the gbrain home;+after 3 self-exits within an hour serve stops exiting, logs+`serve_self_exit_suppressed`, and the deep-health 503 carries+`self_exit_suppressed: true` with a fix that asks for a manual restart and a+look at `gbrain sources writer status --json`.+The service `gbrain mcp expose` installs restarts it (systemd `Restart=always`,+launchd `KeepAlive`), so a fresh serve comes up; the floor keeps a restart loop+under the systemd unit's start limit (10 starts per 300 s). For the installed service put the variable+in `~/.gbrain/env`; for a foreground serve set it in the shell or your own+supervisor's environment. A foreground serve with no supervisor just exits.+<a id="backfill-rollback-failed"></a>**`backfill_rollback_failed`** (error).A `gbrain backfill` batch failed, and its `ROLLBACK` failed too. The run stopsrather than retrying on a connection whose transaction state is unknown; the@@ -10333,6 +10399,7 @@ the exit code first, then reads the JSON document (`--json`) for the details:| 3 | `confirmation_required`: nothing ran | consent payload (`effects`, `user_message`, `fix`) | stop, relay `user_message` to the user, run `fix.command` only after they agree || 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0 || 11 | partial, resumable budget stop | result with `remaining_*` and `resume_command` | run `resume_command` (it is safe to re-run) |+| 69 | `gbrain serve` exited on its own after its persistence consumer reported `restart_required` for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` (`serve_unhealthy_exit`; opt-in) | `[gbrain serve] error code=serve_unhealthy_exit` line on stderr | nothing: the supervisor (the installed service restarts on failure) starts a fresh serve; if it repeats, follow [the unhealthy exit](../ENGINES.md#serve-unhealthy-exit) || 75 | another runner holds the migration lock, or an engine graduation owns the brain (`graduation_in_progress`) | error envelope | wait for the other runner, then retry || 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) || 130 | interrupted (SIGINT) | error envelope | ask the user whether to re-run |diff --git a/patches/[email protected] b/patches/[email protected]index 7d5dbabcdf..22d13e2f2a 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -1,5 +1,5 @@diff --git a/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js-index 07f67167..1d6ea0a5 100644+index 07f67167..ad0cbd0c 100644--- a/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -73,7 +73,12 @@ index 07f67167..1d6ea0a5 100644} catch (error) {reject(error)}-@@ -167,21 +179,72 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -163,22 +175,78 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ if (q.cancelled)+ return+++ let mayPipeline = !q.options.onexecute+ try {q.state = backendquery? sent.push(q)@@ -81,9 +86,9 @@ index 07f67167..1d6ea0a5 100644+ : (query = q, query.active = true, armInflight())build(q)++ mayPipeline = mayPipeline || q.options.onexecute(connection)+ lastWritten = q+ lastExecuted = q-+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn@@ -93,6 +98,7 @@ index 07f67167..1d6ea0a5 100644} catch (error) {- sent.length === 0 && write(Sync)- errored(error)+- return true+ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of+ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's+ // current query with q's error and left q waiting, so every later answer went to the wrong query.@@ -104,15 +110,19 @@ index 07f67167..1d6ea0a5 100644+ q.retried = error+ q.describeFirst = false+ q.cursorFn = null++ // GBrain (#6543): the stock `return true` let the pool route more statements behind q whatever max_pipeline and++ // onexecute said, so a pool built not to pipeline (a transaction-mode pooler) pipelined after every build failure.++ // onexecute (a transaction's begin) ran only if q built; a begin that failed to build is never pipelined behind.+ options.onbuilderror && reportBuildError(q, error)-+ write(Unbuildable)- return true- }- }-++ return write(Unbuildable)++ && sent.length < max_pipeline++ && mayPipeline++ }++ }+++ function reportBuildError(q, error) {+ try {-+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))++ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q), error && error.parameter)+ } catch (_) {}+ }+@@ -144,13 +154,10 @@ index 07f67167..1d6ea0a5 100644+ if (s && !s.destroyed) {+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)+ t.unref && t.unref()-+ }-+ }-+- function toBuffer(q) {- if (q.parameters.length >= 65534)- throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')-@@ -235,10 +298,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ }+ }++@@ -235,10 +303,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -168,7 +175,7 @@ index 07f67167..1d6ea0a5 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +363,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +368,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -181,7 +188,7 @@ index 07f67167..1d6ea0a5 100644if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,15 +448,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,15 +453,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -203,7 +210,7 @@ index 07f67167..1d6ea0a5 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +513,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,19 +518,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -239,11 +246,16 @@ index 07f67167..1d6ea0a5 100644+ }!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))-+ query = null++ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged++ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that++ // error to its first statement, and a stale row count left holes at the start of the next result.++ query = errorResponse = results = null++ result = new Result()++ rows = 0closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -459,6 +553,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -459,6 +563,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {@@ -254,7 +266,7 @@ index 07f67167..1d6ea0a5 100644(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d-@@ -489,6 +587,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -489,6 +597,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}@@ -291,7 +303,7 @@ index 07f67167..1d6ea0a5 100644function DataRow(x) {let index = 7let length-@@ -533,13 +661,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -533,13 +671,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -316,7 +328,7 @@ index 07f67167..1d6ea0a5 100644} else {query.resolve(results || result)}-@@ -550,6 +688,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -550,6 +698,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()@@ -324,7 +336,7 @@ index 07f67167..1d6ea0a5 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +703,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +713,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -367,7 +379,7 @@ index 07f67167..1d6ea0a5 100644: connection.reserved(): ending? terminate()-@@ -630,7 +782,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +792,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -379,7 +391,7 @@ index 07f67167..1d6ea0a5 100644}function RowDescription(x) {-@@ -767,14 +923,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +933,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -409,7 +421,7 @@ index 07f67167..1d6ea0a5 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +984,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +994,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -861,8 +873,21 @@ index 8438f5da..c444310f 100644shift: () => {const out = xs[index++]+diff --git a/cjs/src/types.js b/vendor/postgres/cjs/src/types.js+index 0578284c..e80a868e 100644+--- a/cjs/src/types.js++++ b/vendor/postgres/cjs/src/types.js+@@ -80,7 +80,7 @@ module.exports.handleValue = handleValue;function handleValue(x, parameters, typ+ : value = x = options.transform.undefined++ if (value === undefined)+- throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')++ throw Object.assign(Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed (parameter $' + (types.length + 1) + ')'), { parameter: types.length + 1 })+ }++ return '$' + (types.push(diff --git a/src/connection.js b/vendor/postgres/src/connection.js-index 1b1cccde..37824bf4 100644+index 1b1cccde..84f8a587 100644--- a/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -936,7 +961,12 @@ index 1b1cccde..37824bf4 100644} catch (error) {reject(error)}-@@ -167,21 +179,72 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -163,22 +175,78 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ if (q.cancelled)+ return+++ let mayPipeline = !q.options.onexecute+ try {q.state = backendquery? sent.push(q)@@ -944,9 +974,9 @@ index 1b1cccde..37824bf4 100644+ : (query = q, query.active = true, armInflight())build(q)++ mayPipeline = mayPipeline || q.options.onexecute(connection)+ lastWritten = q+ lastExecuted = q-+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn@@ -956,6 +986,7 @@ index 1b1cccde..37824bf4 100644} catch (error) {- sent.length === 0 && write(Sync)- errored(error)+- return true+ // GBrain (#6383), the approach of porsager/postgres#1236: q already has its place in the queue of+ // queries awaiting an answer, but nothing of it was written. The stock catch rejected the connection's+ // current query with q's error and left q waiting, so every later answer went to the wrong query.@@ -967,15 +998,19 @@ index 1b1cccde..37824bf4 100644+ q.retried = error+ q.describeFirst = false+ q.cursorFn = null++ // GBrain (#6543): the stock `return true` let the pool route more statements behind q whatever max_pipeline and++ // onexecute said, so a pool built not to pipeline (a transaction-mode pooler) pipelined after every build failure.++ // onexecute (a transaction's begin) ran only if q built; a begin that failed to build is never pipelined behind.+ options.onbuilderror && reportBuildError(q, error)-+ write(Unbuildable)- return true- }- }-++ return write(Unbuildable)++ && sent.length < max_pipeline++ && mayPipeline++ }++ }+++ function reportBuildError(q, error) {+ try {-+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))++ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q), error && error.parameter)+ } catch (_) {}+ }+@@ -1007,13 +1042,10 @@ index 1b1cccde..37824bf4 100644+ if (s && !s.destroyed) {+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)+ t.unref && t.unref()-+ }-+ }-+- function toBuffer(q) {- if (q.parameters.length >= 65534)- throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')-@@ -235,10 +298,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ }+ }++@@ -235,10 +303,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -1031,7 +1063,7 @@ index 1b1cccde..37824bf4 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +363,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +368,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -1044,7 +1076,7 @@ index 1b1cccde..37824bf4 100644if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,15 +448,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,15 +453,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -1066,7 +1098,7 @@ index 1b1cccde..37824bf4 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +513,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,19 +518,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -1102,11 +1134,16 @@ index 1b1cccde..37824bf4 100644+ }!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))-+ query = null++ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged++ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that++ // error to its first statement, and a stale row count left holes at the start of the next result.++ query = errorResponse = results = null++ result = new Result()++ rows = 0closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -459,6 +553,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -459,6 +563,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {@@ -1117,7 +1154,7 @@ index 1b1cccde..37824bf4 100644(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d-@@ -489,6 +587,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -489,6 +597,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}@@ -1154,7 +1191,7 @@ index 1b1cccde..37824bf4 100644function DataRow(x) {let index = 7let length-@@ -533,13 +661,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -533,13 +671,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -1179,7 +1216,7 @@ index 1b1cccde..37824bf4 100644} else {query.resolve(results || result)}-@@ -550,6 +688,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -550,6 +698,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()@@ -1187,7 +1224,7 @@ index 1b1cccde..37824bf4 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +703,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +713,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -1230,7 +1267,7 @@ index 1b1cccde..37824bf4 100644: connection.reserved(): ending? terminate()-@@ -630,7 +782,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +792,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -1242,7 +1279,7 @@ index 1b1cccde..37824bf4 100644}function RowDescription(x) {-@@ -767,14 +923,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +933,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -1272,7 +1309,7 @@ index 1b1cccde..37824bf4 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +984,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +994,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -1724,11 +1761,24 @@ index c4ef9716..8fba891b 100644shift: () => {const out = xs[index++]+diff --git a/src/types.js b/vendor/postgres/src/types.js+index 7c7c2b93..d462498a 100644+--- a/src/types.js++++ b/vendor/postgres/src/types.js+@@ -80,7 +80,7 @@ export function handleValue(x, parameters, types, options) {+ : value = x = options.transform.undefined++ if (value === undefined)+- throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')++ throw Object.assign(Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed (parameter $' + (types.length + 1) + ')'), { parameter: types.length + 1 })+ }++ return '$' + (types.push(diff --git a/types/index.d.ts b/vendor/postgres/types/index.d.ts-index 13c3432f..53127d62 100644+index 13c3432f..b77d74e1 100644--- a/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts-@@ -119,6 +119,37 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {+@@ -119,6 +119,38 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {*/publications: stringonclose: (connId: number) => void;@@ -1748,9 +1798,10 @@ index 13c3432f..53127d62 100644+ onstuck: (stuck: { age_ms: number; queued: number; statement: string }) => void;+ /**+ * GBrain: called when a statement fails to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`);-+ * `statement` is its text with `$n` placeholders, never parameter values.++ * `statement` is its text with `$n` placeholders, never parameter values; `parameter` is the 1-based++ * index of an undefined parameter value, undefined when the failure names none (an array element).+ */-+ onbuilderror: (code: string, statement: string) => void;++ onbuilderror: (code: string, statement: string, parameter?: number) => void;+ /**+ * GBrain: called once per connection retired because a statement's answer arrived with no statement+ * waiting for it; `statement` is the last statement written on it, with `$n` placeholders.@@ -1766,7 +1817,7 @@ index 13c3432f..53127d62 100644backoff: boolean | ((attemptNum: number) => number);max_lifetime: number | null;keep_alive: number | null;-@@ -605,7 +636,7 @@ declare namespace postgres {+@@ -605,7 +637,7 @@ declare namespace postgres {writable(): Promise<Writable>;execute(): this;@@ -1775,7 +1826,7 @@ index 13c3432f..53127d62 100644/*** @deprecated `.stream` has been renamed to `.forEach`-@@ -659,6 +690,7 @@ declare namespace postgres {+@@ -659,6 +691,7 @@ declare namespace postgres {| Fragment[]interface UnsafeQueryOptions {@@ -1783,7 +1834,7 @@ index 13c3432f..53127d62 100644/*** When executes query as prepared statement.* @default false-@@ -705,6 +737,8 @@ declare namespace postgres {+@@ -705,6 +738,8 @@ declare namespace postgres {options: ParsedOptions<TTypes>;parameters: ConnectionParameters;@@ -1792,7 +1843,7 @@ index 13c3432f..53127d62 100644end(options?: { timeout?: number | undefined } | undefined): Promise<void>;-@@ -717,10 +751,11 @@ declare namespace postgres {+@@ -717,10 +752,11 @@ declare namespace postgres {begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;@@ -1805,7 +1856,7 @@ index 13c3432f..53127d62 100644savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;-@@ -728,6 +763,7 @@ declare namespace postgres {+@@ -728,6 +764,7 @@ declare namespace postgres {}interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {diff --git a/scripts/audit-pooler-misroute.ts b/scripts/audit-pooler-misroute.tsnew file mode 100644index 0000000000..9213cda777--- /dev/null+++ b/scripts/audit-pooler-misroute.ts@@ -0,0 +1,258 @@+#!/usr/bin/env bun+/**+ * #6543 (I1): read-only integrity audit for a brain that served writes through+ * a transaction-mode pooler (Supavisor :6543) while pipelined answers could be+ * misrouted. It lists persistence rows touched in a window whose identity+ * values belong to another row, separately from rows it verified and rows it+ * cannot judge. It never writes and never repairs: any corrective write is a+ * separate, preview-bound decision for the brain's owner.+ *+ * Usage:+ * bun audit-pooler-misroute.ts --url <direct or session-pooler URL> \+ * --since <iso> --until <iso> [--json] [--batch-size 500] [--batch-timeout-ms 15000]+ *+ * Self-contained, so it runs beside any install (a v0.60.180.0 global install+ * included) with no checkout: copy this one file anywhere and run it with bun.+ * It imports nothing from gbrain's src/, only the postgres driver, from the+ * first of: $GBRAIN_AUDIT_POSTGRES_DRIVER (a path to postgres's src/index.js),+ * ../vendor/postgres/src/index.js next to this file (a checkout),+ * ~/.bun/install/global/node_modules/gbrain/vendor/postgres/src/index.js (a+ * `bun install -g` gbrain), or a `postgres` package node_modules resolves.+ *+ * Connection: one connection to the URL given with --url (never read from the+ * environment). A direct URL or the session pooler (Supabase :5432) is+ * accepted; a transaction-mode URL (port 6543 or ?prepare=false) is refused,+ * because the audit must not read through the transport it is auditing.+ *+ * Reads: bounded batches, each one REPEATABLE READ READ ONLY transaction with+ * a transaction-local statement timeout, so every comparison inside a batch is+ * made against one snapshot. There is NO global snapshot across batches. A row+ * whose updated_at is at or after the audit's start was written while the+ * audit ran and is reported `unknown` (changed_during_audit), never judged.+ * Only columns present at schema v239 are read.+ *+ * Checks (all identity values a misrouted row could have carried):+ * persistence_effects: source_id, source_incarnation and worktree_id are+ * copied from their request in the same statement, so a difference is a+ * `mismatch`; all three unset (rows from before those columns) is unknown.+ * persistence_requests: a source_incarnation owned by another source (it is+ * unique per source) and a page_id whose page lives in another source are+ * `mismatch`. A removed source, a re-created source, a removed page, a page+ * whose slug differs (a later move), compacted history and a claim stamp+ * from another execution token (a reclaimed claim) are coverage gaps:+ * `unknown`, never clean.+ *+ * Output (--json): { verified_ok: { requests, effects }, mismatch: [...],+ * unknown: [...], unknown_by_reason, ... }. Exit 0 when nothing mismatched, 1+ * when a mismatch was found, 2 on a usage error or a refused URL.+ * Runbook: docs/guides/pooler-misroute-audit.md.+ */+import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';++type Sql = {+ begin<T>(options: string, fn: (tx: Sql) => Promise<T>): Promise<T>;+ unsafe<T = Record<string, unknown>[]>(query: string, params?: unknown[]): Promise<T>;+ end(opts?: { timeout?: number }): Promise<void>;+};+type PostgresFactory = (url: string, options: Record<string, unknown>) => Sql;++export interface AuditOptions {+ since: Date;+ until: Date;+ batchSize?: number;+ batchTimeoutMs?: number;+ /** Test seam: runs after each committed batch, before the next one opens. */+ onBatch?: (index: number) => Promise<void> | void;+}++export interface AuditMismatch { table: 'persistence_requests' | 'persistence_effects'; id: string; request_id: string | null; field: string; value: string | null; expected: string | null; belongs_to?: { table: string; id: string } }+export interface AuditUnknown { table: 'persistence_requests' | 'persistence_effects'; id: string; request_id: string | null; reasons: string[] }+export interface AuditReport {+ window: { since: string; until: string };+ audit_started_at: string;+ snapshot: 'per_batch';+ disclaimer: string;+ batches: number;+ scanned: { requests: number; effects: number };+ verified_ok: { requests: number; effects: number };+ mismatch: AuditMismatch[];+ unknown: AuditUnknown[];+ unknown_by_reason: Record<string, number>;+}++const DISCLAIMER = 'Each batch reads one REPEATABLE READ READ ONLY snapshot; there is no global snapshot across batches. '+ + 'Rows written after the audit started are reported unknown (changed_during_audit). Unknown rows are not verified.';++/** Refuses a transaction-mode URL; returns null when the URL is acceptable. */+export function refuseTransactionPoolerUrl(url: string): string | null {+ let parsed: URL;+ try { parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://')); } catch { return 'the --url is not a valid postgres URL'; }+ if (parsed.port === '6543') return 'the --url is a transaction-mode pooler (port 6543); give the direct URL or the session pooler (Supabase: port 5432)';+ if (parsed.searchParams.get('prepare') === 'false') return 'the --url has ?prepare=false (a transaction-mode pooler); give the direct URL or the session pooler (Supabase: port 5432)';+ return null;+}++async function loadPostgres(): Promise<PostgresFactory> {+ const candidates = [+ process.env.GBRAIN_AUDIT_POSTGRES_DRIVER,+ fileURLToPath(new URL('../vendor/postgres/src/index.js', import.meta.url)),+ join(homedir(), '.bun/install/global/node_modules/gbrain/vendor/postgres/src/index.js'),+ ].filter((path): path is string => !!path && existsSync(path));+ for (const specifier of [...candidates, 'postgres']) {+ try { return ((await import(specifier)) as { default: PostgresFactory }).default; } catch { /* next candidate */ }+ }+ throw new Error('no postgres driver found: set GBRAIN_AUDIT_POSTGRES_DRIVER to the path of a postgres src/index.js (a gbrain install has one under vendor/postgres)');+}++const REQUESTS_SQL = `SELECT r.sequence::text AS seq, r.id::text AS id, r.request_id::text AS request_id, r.source_id, r.source_incarnation::text AS source_incarnation,+ r.page_id::text AS page_id, r.slug, r.compacted, r.execution_token::text AS execution_token, r.claim_phase->>'token' AS stamp_token,+ (r.updated_at >= $3::timestamptz) AS changed,+ s.id AS source_now, s.incarnation::text AS source_incarnation_now, o.id AS incarnation_owner,+ p.id::text AS page_now, p.source_id AS page_source_id, p.slug AS page_slug+ FROM persistence_requests r+ LEFT JOIN sources s ON s.id = r.source_id+ LEFT JOIN sources o ON o.incarnation = r.source_incarnation+ LEFT JOIN pages p ON p.id = r.page_id+ WHERE r.sequence > $4::bigint+ AND ((r.created_at >= $1::timestamptz AND r.created_at < $2::timestamptz) OR (r.updated_at >= $1::timestamptz AND r.updated_at < $2::timestamptz) OR r.updated_at >= $3::timestamptz)+ ORDER BY r.sequence LIMIT $5`;++const EFFECTS_SQL = `SELECT e.id::text AS id, r.request_id::text AS request_id, e.source_id, e.source_incarnation::text AS source_incarnation, e.worktree_id::text AS worktree_id,+ r.source_id AS r_source_id, r.source_incarnation::text AS r_source_incarnation, r.worktree_id::text AS r_worktree_id,+ (e.updated_at >= $3::timestamptz) AS changed+ FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id+ WHERE e.id > $4::bigint AND ((e.updated_at >= $1::timestamptz AND e.updated_at < $2::timestamptz) OR e.updated_at >= $3::timestamptz)+ ORDER BY e.id LIMIT $5`;++type RequestRow = { seq: string; id: string; request_id: string; source_id: string; source_incarnation: string; page_id: string | null; slug: string; compacted: boolean;+ execution_token: string | null; stamp_token: string | null; changed: boolean; source_now: string | null; source_incarnation_now: string | null; incarnation_owner: string | null;+ page_now: string | null; page_source_id: string | null; page_slug: string | null };+type EffectRow = { id: string; request_id: string; source_id: string | null; source_incarnation: string | null; worktree_id: string | null;+ r_source_id: string; r_source_incarnation: string; r_worktree_id: string | null; changed: boolean };++function judgeRequest(row: RequestRow): { mismatch: AuditMismatch[]; unknown: string[] } {+ const base = { table: 'persistence_requests' as const, id: row.id, request_id: row.request_id };+ if (row.changed) return { mismatch: [], unknown: ['changed_during_audit'] };+ const mismatch: AuditMismatch[] = [];+ if (row.incarnation_owner !== null && row.incarnation_owner !== row.source_id) {+ mismatch.push({ ...base, field: 'source_incarnation', value: row.source_incarnation, expected: row.source_incarnation_now, belongs_to: { table: 'sources', id: row.incarnation_owner } });+ }+ if (row.page_now !== null && row.page_source_id !== row.source_id) {+ mismatch.push({ ...base, field: 'page_id', value: row.page_id, expected: null, belongs_to: { table: 'sources', id: row.page_source_id ?? '' } });+ }+ const unknown: string[] = [];+ if (row.source_now === null) unknown.push('source_removed');+ else if (row.incarnation_owner === null && row.source_incarnation_now !== row.source_incarnation) unknown.push('source_reincarnated');+ if (row.page_id !== null && row.page_now === null) unknown.push('page_removed');+ if (row.page_now !== null && row.page_source_id === row.source_id && row.page_slug !== row.slug) unknown.push('page_slug_differs');+ if (row.compacted) unknown.push('compacted_history');+ if (row.stamp_token !== null && row.execution_token !== null && row.stamp_token !== row.execution_token) unknown.push('token_reclaimed');+ return { mismatch, unknown };+}++function judgeEffect(row: EffectRow): { mismatch: AuditMismatch[]; unknown: string[] } {+ if (row.changed) return { mismatch: [], unknown: ['changed_during_audit'] };+ if (row.source_id === null && row.source_incarnation === null && row.worktree_id === null) return { mismatch: [], unknown: ['effect_identity_unset'] };+ const pairs: Array<[string, string | null, string | null]> = [+ ['source_id', row.source_id, row.r_source_id], ['source_incarnation', row.source_incarnation, row.r_source_incarnation], ['worktree_id', row.worktree_id, row.r_worktree_id]];+ return { mismatch: pairs.filter(([, value, expected]) => value !== expected)+ .map(([field, value, expected]) => ({ table: 'persistence_effects' as const, id: row.id, request_id: row.request_id, field, value, expected, belongs_to: undefined })), unknown: [] };+}++/** Runs the audit on `sql` (one connection). Read-only: every statement is a SELECT inside a READ ONLY transaction. */+export async function auditPoolerMisroute(sql: Sql, opts: AuditOptions): Promise<AuditReport> {+ const batchSize = opts.batchSize ?? 500;+ const timeoutMs = opts.batchTimeoutMs ?? 15_000;+ const report: AuditReport = { window: { since: opts.since.toISOString(), until: opts.until.toISOString() }, audit_started_at: '', snapshot: 'per_batch', disclaimer: DISCLAIMER,+ batches: 0, scanned: { requests: 0, effects: 0 }, verified_ok: { requests: 0, effects: 0 }, mismatch: [], unknown: [], unknown_by_reason: {} };+ const batch = async <T>(query: string, after: string, started: string | null): Promise<{ rows: T[]; started: string }> => {+ const result = await sql.begin('isolation level repeatable read read only', async tx => {+ await tx.unsafe("SELECT set_config('statement_timeout', $1, true), set_config('idle_in_transaction_session_timeout', $1, true)", [`${timeoutMs}ms`]);+ const now = started ?? (await tx.unsafe<Array<{ now: string }>>('SELECT now()::text AS now'))[0]!.now;+ return { rows: await tx.unsafe<T[]>(query, [report.window.since, report.window.until, now, after, batchSize]), started: now };+ });+ report.batches += 1;+ await opts.onBatch?.(report.batches);+ return result;+ };+ const record = (table: AuditUnknown['table'], id: string, requestId: string | null, verdict: { mismatch: AuditMismatch[]; unknown: string[] }) => {+ if (verdict.mismatch.length) { report.mismatch.push(...verdict.mismatch); return; }+ if (verdict.unknown.length) {+ report.unknown.push({ table, id, request_id: requestId, reasons: verdict.unknown });+ for (const reason of verdict.unknown) report.unknown_by_reason[reason] = (report.unknown_by_reason[reason] ?? 0) + 1;+ return;+ }+ if (table === 'persistence_requests') report.verified_ok.requests += 1; else report.verified_ok.effects += 1;+ };+ let started: string | null = null;+ for (let after = '0'; ;) {+ const page: { rows: RequestRow[]; started: string } = await batch<RequestRow>(REQUESTS_SQL, after, started);+ started = page.started;+ for (const row of page.rows) record('persistence_requests', row.id, row.request_id, judgeRequest(row));+ report.scanned.requests += page.rows.length;+ if (page.rows.length < batchSize) break;+ after = page.rows[page.rows.length - 1]!.seq;+ }+ for (let after = '0'; ;) {+ const page: { rows: EffectRow[] } = await batch<EffectRow>(EFFECTS_SQL, after, started);+ for (const row of page.rows) record('persistence_effects', row.id, row.request_id, judgeEffect(row));+ report.scanned.effects += page.rows.length;+ if (page.rows.length < batchSize) break;+ after = page.rows[page.rows.length - 1]!.id;+ }+ report.audit_started_at = new Date(started!).toISOString();+ return report;+}++/**+ * One connection, read-only by default on the session too. Statements are awaited one at a time, so nothing pipelines;+ * `max_pipeline: 0` is not set because upstream postgres 3.4.9 then never runs a transaction's begin hook.+ */+export function auditConnectionOptions(): Record<string, unknown> {+ return { max: 1, idle_timeout: 5, connect_timeout: 15, onnotice: () => {},+ connection: { application_name: 'gbrain-audit-pooler-misroute', default_transaction_read_only: 'on' } };+}++function parseArgs(argv: string[]): { url: string; since: Date; until: Date; json: boolean; batchSize: number; batchTimeoutMs: number } | string {+ const value = (flag: string) => { const at = argv.indexOf(flag); return at >= 0 ? argv[at + 1] : undefined; };+ const url = value('--url');+ const since = new Date(value('--since') ?? '');+ const until = new Date(value('--until') ?? '');+ if (!url) return 'missing --url (the direct URL or the session pooler; never read from the environment)';+ if (Number.isNaN(since.getTime()) || Number.isNaN(until.getTime())) return 'missing or invalid --since / --until (ISO timestamps)';+ if (since >= until) return '--since must be before --until';+ const batchSize = Number(value('--batch-size') ?? 500);+ const batchTimeoutMs = Number(value('--batch-timeout-ms') ?? 15_000);+ if (!Number.isInteger(batchSize) || batchSize < 1 || !Number.isInteger(batchTimeoutMs) || batchTimeoutMs < 100) return '--batch-size must be a positive integer and --batch-timeout-ms an integer of at least 100';+ return { url, since, until, json: argv.includes('--json'), batchSize, batchTimeoutMs };+}++async function main(): Promise<number> {+ const args = parseArgs(process.argv.slice(2));+ if (typeof args === 'string') { console.error(`audit-pooler-misroute: ${args}`); return 2; }+ const refused = refuseTransactionPoolerUrl(args.url);+ if (refused) { console.error(`audit-pooler-misroute: refused: ${refused}`); return 2; }+ const postgres = await loadPostgres();+ const sql = postgres(args.url, auditConnectionOptions());+ try {+ const report = await auditPoolerMisroute(sql, args);+ if (args.json) console.log(JSON.stringify(report, null, 2));+ else {+ console.log(`window ${report.window.since} .. ${report.window.until} (audit started ${report.audit_started_at}; ${report.batches} batches, per-batch snapshots)`);+ console.log(`scanned: ${report.scanned.requests} requests, ${report.scanned.effects} effects`);+ console.log(`verified_ok: ${report.verified_ok.requests} requests, ${report.verified_ok.effects} effects`);+ console.log(`mismatch: ${report.mismatch.length}`);+ for (const m of report.mismatch) console.log(` ${m.table} ${m.id} (request ${m.request_id}): ${m.field}=${m.value} expected ${m.expected}${m.belongs_to ? ` (belongs to ${m.belongs_to.table} ${m.belongs_to.id})` : ''}`);+ console.log(`unknown: ${report.unknown.length} ${JSON.stringify(report.unknown_by_reason)}`);+ console.log(DISCLAIMER);+ }+ return report.mismatch.length ? 1 : 0;+ } finally {+ await sql.end({ timeout: 5 });+ }+}++if (import.meta.main) process.exit(await main());diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex d280a5820c..fa852f0409 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -157,6 +157,7 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPENGBRAIN_TEST_DB) ;; # explicit schema-reset opt-in for service hosts; schema-drift still requires a test-shaped DB nameGBRAIN_PGBOUNCER_URL|GBRAIN_PGBOUNCER_DIRECT_URL|GBRAIN_CI_REQUIRE_PGBOUNCER) ;; # explicit pooler test target and execution requirementGBRAIN_PGBOUNCER_E2E_URL|GBRAIN_PGBOUNCER_E2E_DB) ;; # backend-matrix pooled target (scripts/e2e-backend-matrix.txt)+ GBRAIN_SUPAVISOR_URL) ;; # #6543 explicit Supavisor transaction-pooler target for the live pooler suitesGBRAIN_TEST_WAIT_MULTIPLIER) ;; # coverage deadline multiplier read by test/helpers/wait-for.ts — keepGBRAIN_TEST_REQUIRE_COMPILE) ;; # bootstrap-compiled-binary opt-in: a failed compile fails instead of skippingGBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive itdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 5e7683d733..e5a401e2ba 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -255,7 +255,7 @@ test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive ctest/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 source-surface-helpertest/physical-root-birth-tolerance-6501.test.ts physical root birth drift (${kind}) 5 readFileSynctest/physical-root-birth-tolerance-6501.test.ts samePhysicalBirth (#6501) 5 readFileSync-test/postgres-driver-vendor.test.ts vendored Postgres driver packaging 3 readFileSync+test/postgres-driver-vendor.test.ts vendored Postgres driver packaging 4 readFileSynctest/postgres-engine.test.ts postgres-engine / search date filtering 2 source-surface-helpertest/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 source-surface-helpertest/private-visibility.test.ts shared private predicate lives once (#4352 remediation) 1 readFileSyncdiff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.tsindex 354092b3b4..704dc64ac5 100644--- a/src/commands/doctor/checks/persistence-requests.ts+++ b/src/commands/doctor/checks/persistence-requests.ts@@ -185,11 +185,12 @@ export async function sessionTimeoutsCheck(engine: BrainEngine): Promise<Check>const details = { configured, applied, docs, ...(pooler ? { pooler: 'transaction_mode' } : {}) };if (applied !== '0') return { name: 'persistence_session_timeouts', status: pooler ? 'warn' : 'ok', details: pooler ? { ...details, reason: 'transaction_mode_pooler' } : details,message: `The session statement_timeout (${applied}) reaches the server.${poolerNote}` };- return { name: 'persistence_session_timeouts', status: 'warn', details: { ...details, reason: 'session_timeouts_not_applied' },+ const roleFix = `ALTER ROLE <gbrain role> SET statement_timeout = '${configured}'`;+ return { name: 'persistence_session_timeouts', status: 'warn', details: { ...details, reason: 'session_timeouts_not_applied', role_fix: roleFix },message: `session_timeouts_not_applied: gbrain configured statement_timeout=${configured} as a connection startup parameter, but SHOW statement_timeout through the configured URL `+ 'reads 0. A transaction-mode pooler (PgBouncer, Supavisor) drops startup parameters, so statements outside a transaction have no server-side bound; GBRAIN_STATEMENT_TIMEOUT is '+ 'ignored there. Preparation reads are bounded by their own transaction-local timeout (the preparation budget covers the gap); a long autocommit statement elsewhere still runs '- + `until it finishes. To restore the session default, set it on the role: ALTER ROLE <gbrain role> SET statement_timeout = '${configured}' (the pooler cannot be told to keep it).${poolerNote}` };+ + `until it finishes. To restore the session default, set it on the role: ${roleFix} (the pooler cannot be told to keep it).${poolerNote}` };} catch (error) {return checkError('persistence_session_timeouts', 'read the session statement_timeout', error, { details: { configured, health: 'unknown', docs } });}diff --git a/src/commands/serve-health.ts b/src/commands/serve-health.tsnew file mode 100644index 0000000000..3d33652f9e--- /dev/null+++ b/src/commands/serve-health.ts@@ -0,0 +1,204 @@+/**+ * #6543: what a `gbrain serve` reports about itself beyond `SELECT 1`, and the+ * opt-in exit that lets a supervisor recover a wedged serve without a human.+ *+ * Transport: the live read pool's `prepare` and `max_pipeline` (and why+ * `resolveReadPoolPipeline` chose that pipeline depth), the server+ * `statement_timeout` as read through the pool once at startup (the doctor's+ * `persistence_session_timeouts` probe, so the reading and its ALTER ROLE fix+ * live in one place; its env-URL pooler verdict is not used), and the+ * backend's `application_name` when it is Supavisor. A `0` where gbrain+ * configured a timeout means the startup parameters never applied, so no+ * server-side timeout bounds an autocommit statement. Serve logs the facts as+ * one line at startup and `/health?deep=1` returns them as its `transport`.+ *+ * Exit: `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (n >= 120, off by default)+ * makes serve exit with `SERVE_UNHEALTHY_EXIT_CODE` once its persistence+ * consumer has reported `restart_required` (a zombie preparation or a stuck+ * publication: it claims nothing until restart) continuously for n seconds,+ * read in-process. The condition clears when the stuck work settles, and the+ * hold restarts then. The exit is bounded: the consumer's stop waits on the+ * very work that is stuck, so cleanup runs under a deadline and the process+ * exits regardless. A supervisor that restarts on failure (the installed+ * service does) then brings up a fresh one; the floor keeps a restart loop+ * below the unit's `StartLimitBurst=10` per 300 s. A loop guard keeps a+ * durable ledger of self-exits (`serve-self-exit.json` under the gbrain home):+ * after 3 within an hour serve stops exiting, logs `serve_self_exit_suppressed`+ * and `/health?deep=1` reports `self_exit_suppressed`, so a human looks. A+ * pooled statement past the in-flight budget is reported by `/health?deep=1`+ * but never triggers the exit (the variable is named for its one trigger).+ */+import type { BrainEngine } from '../core/engine.ts';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname } from 'node:path';+import { gbrainPath } from '../core/config.ts';+import { OperationError } from '../core/ops/contract.ts';+import { SERVE_UNHEALTHY_EXIT_CODE } from '../core/exit-codes.ts';+import { consumerConnectionRoute, type ConsumerConnectionRoute } from '../core/persistence/consumer-lane.ts';+import { persistenceConsumerStatus } from '../core/persistence/service.ts';+import { resolveReadPoolPipeline, type ReadPoolPipelineReason } from '../core/db.ts';+import { sessionTimeoutsCheck } from './doctor/checks/persistence-requests.ts';++export interface ServeTransport {+ pooler_mode: ConsumerConnectionRoute['pooler_mode'];+ /** The live read pool's `prepare` option, null when the engine has no driver pool. */+ prepare: boolean | null;+ /** The live read pool's `max_pipeline` (0: no pipelining), null when the engine has no driver pool. */+ max_pipeline: number | null;+ /** Why the read pool got that depth (`resolveReadPoolPipeline` on the engine's URL); null when the URL is unknown. */+ max_pipeline_reason: ReadPoolPipelineReason | null;+ /** `SHOW statement_timeout` through the read pool at startup; null when it could not be read or none is configured. */+ statement_timeout: string | null;+ /** True when that reading is `0` while gbrain configured a timeout: the startup parameter never reached the server. */+ session_timeouts_not_applied: boolean;+ /** The doctor probe's fix for a session timeout that never applied. */+ fix?: string;+ /** Present when the backend reports Supavisor as its application_name (a Supabase pooler). */+ application_name?: 'Supavisor';+}++const transports = new WeakMap<BrainEngine, ServeTransport>();++/** Reads the transport facts of this engine's read pool (`SHOW statement_timeout`, `SHOW application_name`). */+export async function readServeTransport(engine: BrainEngine): Promise<ServeTransport> {+ const { pooler_mode } = consumerConnectionRoute(engine);+ const options = (engine as { sql?: { options?: { max_pipeline?: unknown; prepare?: unknown } } }).sql?.options;+ const url = (engine as { _savedConfig?: { database_url?: string } })._savedConfig?.database_url;+ const details = ((await sessionTimeoutsCheck(engine)) as { details?: { applied?: unknown; reason?: unknown; role_fix?: unknown } }).details ?? {};+ const notApplied = details.reason === 'session_timeouts_not_applied';+ const [app] = await engine.executeRaw<{ application_name?: string }>('SHOW application_name').catch(() => []);+ return { pooler_mode, prepare: typeof options?.prepare === 'boolean' ? options.prepare : null, max_pipeline: typeof options?.max_pipeline === 'number' ? options.max_pipeline : null,+ max_pipeline_reason: url ? resolveReadPoolPipeline(url).reason : null, statement_timeout: typeof details.applied === 'string' ? details.applied : null,+ session_timeouts_not_applied: notApplied, ...(notApplied && typeof details.role_fix === 'string' ? { fix: details.role_fix } : {}),+ ...(app?.application_name === 'Supavisor' ? { application_name: 'Supavisor' as const } : {}) };+}++export function formatServeTransportLine(t: ServeTransport): string {+ return `[gbrain serve] transport pooler_mode=${t.pooler_mode} prepare=${t.prepare ?? 'unknown'} max_pipeline=${t.max_pipeline ?? 'unknown'}`+ + ` max_pipeline_reason=${t.max_pipeline_reason ?? 'unknown'} statement_timeout=${t.statement_timeout ?? 'unknown'}${t.application_name ? ` application_name=${t.application_name}` : ''}`+ + (t.session_timeouts_not_applied ? ` session_timeouts_not_applied=true fix="${t.fix ?? 'gbrain doctor --json'}" docs=docs/guides/troubleshooting.md#session-timeouts-not-applied` : '');+}++/** Startup: reads the transport once, keeps it for `/health?deep=1` and logs the line. Never throws. */+export async function recordServeTransport(engine: BrainEngine, log: (line: string) => void): Promise<void> {+ try {+ const transport = await readServeTransport(engine);+ transports.set(engine, transport);+ log(formatServeTransportLine(transport));+ } catch { /* best-effort: deep health reports transport: null */ }+}++/** The transport recorded at startup, or null before it was read (or on an engine without one). */+export function serveTransport(engine: BrainEngine): ServeTransport | null {+ return transports.get(engine) ?? null;+}++type ConsumerStatusReader = (engine: BrainEngine) => object;++/** Whether this process's persistence consumer reports `restart_required`, read in-process (`persistenceConsumerStatus`). */+export function consumerRestartRequired(engine: BrainEngine, status: ConsumerStatusReader = persistenceConsumerStatus): boolean {+ return (status(engine) as { restart_required?: unknown }).restart_required === true;+}++export const SERVE_RESTART_REQUIRED_EXIT_ENV = 'GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS';+export const SERVE_RESTART_REQUIRED_EXIT_FLOOR_SECONDS = 120;+/** The loop guard: past this many self-exits within the window, serve stops exiting and a human has to look. */+export const SERVE_SELF_RESTART_LIMIT = 3;+export const SERVE_SELF_EXIT_WINDOW_MS = 60 * 60 * 1000;+/** The bound on cleanup before the exit fires regardless (serve.ts's CLEANUP_DEADLINE_MS). */+export const SERVE_RESTART_REQUIRED_CLEANUP_DEADLINE_MS = 5_000;++/** Seconds restart_required must hold before serve exits, or null (off). Refuses a value that is not a whole number of at least 120. */+export function resolveRestartRequiredExitSeconds(raw: string | undefined): number | null {+ if (raw === undefined || raw.trim() === '' || raw.trim() === '0') return null;+ const seconds = /^\s*\d+\s*$/.test(raw) ? Number(raw) : NaN;+ if (!(seconds >= SERVE_RESTART_REQUIRED_EXIT_FLOOR_SECONDS)) {+ throw new OperationError('invalid_params', `${SERVE_RESTART_REQUIRED_EXIT_ENV}=${JSON.stringify(raw)} is not a whole number of seconds of at least ${SERVE_RESTART_REQUIRED_EXIT_FLOOR_SECONDS}.`,+ `Set it to ${SERVE_RESTART_REQUIRED_EXIT_FLOOR_SECONDS} or more (a shorter hold would restart serve fast enough to trip the service's start limit of 10 per 300 s), or unset it (or 0) to keep serve running while restart_required.`);+ }+ return seconds;+}++/** The durable self-exit ledger under the gbrain home: ISO timestamps of recent self-exits. */+export function serveSelfExitLedgerPath(): string {+ return gbrainPath('serve-self-exit.json');+}++function readSelfExits(path: string): number[] {+ try {+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as { exits?: unknown };+ return Array.isArray(parsed.exits) ? parsed.exits.map(at => Date.parse(String(at))).filter(Number.isFinite) : [];+ } catch { return []; }+}++const suppressedEngines = new WeakSet<BrainEngine>();+/** True while this serve's exit is suppressed by the loop guard (restart_required held, but 3 self-exits in the last hour). */+export function selfExitSuppressed(engine: BrainEngine): boolean {+ return suppressedEngines.has(engine);+}++export interface RestartRequiredExitDeps {+ exit: (code: number) => void;+ log: (line: string) => void;+ /** Monotonic clock for the hold. */+ now?: () => number;+ /** Wall clock for the ledger. */+ wallNow?: () => number;+ ledgerPath?: string;+ consumerStatus?: ConsumerStatusReader;+ /** Check cadence; default a quarter of the hold, at most 15 s. */+ everyMs?: number;+ cleanupDeadlineMs?: number;+}++/**+ * Arms the opt-in exit. `check()` is what the timer runs; tests drive it directly. When restart_required has held for+ * `seconds`: if the ledger already holds 3 self-exits within the hour, log once and keep serving (`selfExitSuppressed`);+ * otherwise record this exit, log, disconnect the engine (which stops the consumer) under a deadline, and exit with+ * the registered code whether or not cleanup finished.+ */+export function installRestartRequiredExit(engine: BrainEngine, seconds: number, deps: RestartRequiredExitDeps): { check(): void; stop(): void } {+ const now = deps.now ?? (() => performance.now());+ const wallNow = deps.wallNow ?? Date.now;+ const ledger = deps.ledgerPath ?? serveSelfExitLedgerPath();+ let since: number | null = null;+ let fired = false;+ let exited = false;+ const exitOnce = (): void => { if (!exited) { exited = true; deps.exit(SERVE_UNHEALTHY_EXIT_CODE); } };+ const check = (): void => {+ if (fired) return;+ if (!consumerRestartRequired(engine, deps.consumerStatus)) { since = null; suppressedEngines.delete(engine); return; }+ if (since === null) { since = now(); return; }+ const heldMs = now() - since;+ if (heldMs < seconds * 1000 || suppressedEngines.has(engine)) return;+ const at = wallNow();+ const recent = readSelfExits(ledger).filter(t => at - t < SERVE_SELF_EXIT_WINDOW_MS && t <= at);+ if (recent.length >= SERVE_SELF_RESTART_LIMIT) {+ suppressedEngines.add(engine);+ deps.log(`[gbrain serve] error code=serve_self_exit_suppressed cause=persistence_restart_required self_exits_last_hour=${recent.length}`+ + ` message="${SERVE_RESTART_REQUIRED_EXIT_ENV}: ${recent.length} self-exits within the last hour; not exiting again, restart serve by hand and read gbrain sources writer status --json" ledger=${ledger} docs=docs/ENGINES.md#serve-unhealthy-exit`);+ return;+ }+ fired = true;+ clearInterval(timer);+ try {+ mkdirSync(dirname(ledger), { recursive: true });+ writeFileSync(ledger, `${JSON.stringify({ exits: [...recent, at].map(t => new Date(t).toISOString()) })}\n`, { mode: 0o600 });+ } catch (err: unknown) { deps.log(`[gbrain serve] serve_unhealthy_exit: could not record the self-exit in ${ledger}: ${err instanceof Error ? err.message : String(err)}`); }+ const deadlineMs = deps.cleanupDeadlineMs ?? SERVE_RESTART_REQUIRED_CLEANUP_DEADLINE_MS;+ deps.log(`[gbrain serve] error code=serve_unhealthy_exit cause=persistence_restart_required held_s=${Math.round(heldMs / 1000)} exit=${SERVE_UNHEALTHY_EXIT_CODE}`+ + ` message="${SERVE_RESTART_REQUIRED_EXIT_ENV}=${seconds}: exiting (cleanup bounded at ${deadlineMs} ms) so the supervisor starts a fresh serve" docs=docs/ENGINES.md#serve-unhealthy-exit`);+ const cleanup = setTimeout(() => {+ deps.log(`[gbrain serve] serve_unhealthy_exit: cleanup deadline (${deadlineMs} ms) exceeded, exiting ${SERVE_UNHEALTHY_EXIT_CODE} without it`);+ exitOnce();+ }, deadlineMs);+ cleanup.unref?.();+ Promise.resolve()+ .then(() => engine.disconnect())+ .catch((err: unknown) => { deps.log(`[gbrain serve] serve_unhealthy_exit: cleanup error: ${err instanceof Error ? err.message : String(err)}`); })+ .finally(() => { clearTimeout(cleanup); exitOnce(); });+ };+ const timer = setInterval(check, deps.everyMs ?? Math.min(15_000, seconds * 250));+ timer.unref?.();+ return { check, stop: () => clearInterval(timer) };+}diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.tsindex 577fcfd431..109c37c439 100644--- a/src/commands/serve-http-metrics.ts+++ b/src/commands/serve-http-metrics.ts@@ -22,6 +22,9 @@ import type { Express, NextFunction, Request, RequestHandler, Response } from 'eimport type { BrainEngine } from '../core/engine.ts';import { resolveInflightTimeoutSeconds, resolveSessionTimeouts } from '../core/db.ts';import { poolHealthSnapshot, type PoolHealthSnapshot } from '../core/postgres-engine/pool-stats.ts';+import { CODES } from '../core/error-registry.ts';+import { persistenceConsumerStatus } from '../core/persistence/service.ts';+import { consumerRestartRequired, selfExitSuppressed, serveTransport, type ServeTransport } from './serve-health.ts';import { VERSION } from '../version.ts';import type { ServeHttpContext } from './serve-http.ts';@@ -217,14 +220,23 @@ export async function probeLiveness(* claims an idle one, while the wedged connections sat in the driver's busy* queue where ordinary handler statements are routed. `/health?deep=1` runs* the probe through that ordinary pooled dispatch (no reservation) and reads- * the pool's own numbers; it answers 503 when the probe does not return within- * its budget, when a statement has waited past the read pool's in-flight- * budget, or when the previous deep probe is still pending. One deep probe is- * in flight per engine at a time, so a stuck one is never joined by a pile.+ * the pool's own numbers. One deep probe is in flight per engine at a time,+ * so a stuck one is never joined by a pile.+ *+ * #6543: every 503 carries a stable `code` (with `fix` and `docs` from the+ * error registry): `persistence_restart_required` when this process's+ * persistence consumer reports restart_required (read in-process before the+ * probe; it claims nothing until a restart; no request id reaches the+ * unauthenticated body), `pool_inflight_over_budget` when a statement has waited past the+ * read pool's in-flight budget, `deep_health_probe_failed` when the pooled+ * probe is still pending, timed out or failed. Both bodies carry the+ * `transport` serve read at startup (serve-health.ts). The endpoint is+ * unauthenticated, so it only reports: it never retires a connection.*/+type DeepHealthCode = 'persistence_restart_required' | 'pool_inflight_over_budget' | 'deep_health_probe_failed';export type DeepHealthResult =- | { ok: true; status: 200; body: { status: 'ok'; deep: true; version: string; engine: string; probe_ms: number; pool: PoolHealthSnapshot | null } }- | { ok: false; status: 503; body: { error: 'service_unavailable'; error_description: string; deep: true; pool: PoolHealthSnapshot | null } };+ | { ok: true; status: 200; body: { status: 'ok'; deep: true; version: string; engine: string; probe_ms: number; pool: PoolHealthSnapshot | null; transport: ServeTransport | null } }+ | { ok: false; status: 503; body: { error: 'service_unavailable'; code: DeepHealthCode; reason?: 'pending' | 'timeout' | 'error'; error_description: string; fix: string; docs: string; self_exit_suppressed?: true; deep: true; pool: PoolHealthSnapshot | null; transport: ServeTransport | null } };const pendingDeepProbes = new WeakMap<object, Promise<unknown>>();@@ -240,10 +252,18 @@ export async function probeDeepHealth(version: string,timeoutMs: number = HEALTH_TIMEOUT_MS,budgetMs: number | null = readPoolInflightBudgetMs(),+ consumerStatus: (engine: BrainEngine) => object = persistenceConsumerStatus,): Promise<DeepHealthResult> {const pool = () => poolHealthSnapshot(engine);- const unavailable = (why: string): DeepHealthResult => ({ ok: false, status: 503, body: { error: 'service_unavailable', error_description: why, deep: true, pool: pool() } });- if (pendingDeepProbes.has(engine)) return unavailable('Deep health probe still pending from an earlier request (a pooled SELECT 1 has not answered)');+ const transport = serveTransport(engine);+ const unavailable = (code: DeepHealthCode, why: string, reason?: 'pending' | 'timeout' | 'error'): DeepHealthResult => ({ ok: false, status: 503, body: {+ error: 'service_unavailable', code, ...(reason ? { reason } : {}), error_description: why, fix: CODES[code].suggestion, docs: CODES[code].docs, deep: true, pool: pool(), transport } });+ if (consumerRestartRequired(engine, consumerStatus)) {+ const result = unavailable('persistence_restart_required', 'The persistence consumer of this serve reports restart_required: it claims no write until the process restarts');+ if (result.ok || !selfExitSuppressed(engine)) return result;+ return { ...result, body: { ...result.body, self_exit_suppressed: true, fix: `self_exit_suppressed: this serve already exited on its own 3 times within the hour, so it is not exiting again; restart it by hand and investigate (gbrain sources writer status --json). ${result.body.fix}` } };+ }+ if (pendingDeepProbes.has(engine)) return unavailable('deep_health_probe_failed', 'Deep health probe still pending from an earlier request (a pooled SELECT 1 has not answered)', 'pending');const started = Date.now();const probe = engine.executeRaw('SELECT 1');pendingDeepProbes.set(engine, probe);@@ -256,17 +276,17 @@ export async function probeDeepHealth(]);} catch (e: unknown) {const msg = e instanceof Error ? e.message : 'unknown';- return unavailable(msg === 'health_timeout'- ? `Deep health probe timed out: a pooled SELECT 1 did not answer within ${timeoutMs} ms`- : `Deep health probe failed: ${msg}`);+ return msg === 'health_timeout'+ ? unavailable('deep_health_probe_failed', `Deep health probe timed out: a pooled SELECT 1 did not answer within ${timeoutMs} ms`, 'timeout')+ : unavailable('deep_health_probe_failed', `Deep health probe failed: ${msg}`, 'error');} finally {if (timer !== null) clearTimeout(timer);}const snapshot = pool();if (snapshot && budgetMs !== null && snapshot.inflight_oldest_ms > budgetMs) {- return unavailable(`A pooled statement has waited ${snapshot.inflight_oldest_ms} ms for the server, past the pool budget of ${budgetMs} ms`);+ return unavailable('pool_inflight_over_budget', `A pooled statement has waited ${snapshot.inflight_oldest_ms} ms for the server, past the pool budget of ${budgetMs} ms`);}- return { ok: true, status: 200, body: { status: 'ok', deep: true, version, engine: engineName, probe_ms: Date.now() - started, pool: snapshot } };+ return { ok: true, status: 200, body: { status: 'ok', deep: true, version, engine: engineName, probe_ms: Date.now() - started, pool: pool(), transport } };}/** GET /health: liveness only (full stats are the admin-only /admin/api/full-stats); `?deep=1` probes through the ordinary pool. */diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 99cbbaac7c..94ce019e6f 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -1,5 +1,7 @@import { spawnSync } from 'node:child_process';import { PoolStallWatch } from '../core/postgres-engine/pool-stall-watch.ts';+import { installRestartRequiredExit, recordServeTransport, resolveRestartRequiredExitSeconds, SERVE_RESTART_REQUIRED_EXIT_ENV } from './serve-health.ts';+import { SERVE_UNHEALTHY_EXIT_CODE } from '../core/exit-codes.ts';import type { BrainEngine } from '../core/engine.ts';// C10: `--fail-fast` / GBRAIN_SERVE_FAIL_FAST=1 — exit with the classified envelope instead of status-only/degraded mode (decided in src/cli.ts's connect path; F4's status mode consults it too).export { serveFailFastRequested, writeServeFailFastEnvelope } from '../core/serve-fail-fast.ts';@@ -248,6 +250,13 @@ export async function runServe(console.error(`[gbrain serve] surface=${surface} (source: ${SURFACE_SOURCE_LABEL[resolved.source]})`);// #6383: the pool stall line (Postgres only; the watch reports nothing for an engine without pool numbers).if (engine.kind === 'postgres') new PoolStallWatch(engine, (line) => console.error(line)).start();+ // #6543: the read pool's transport facts, logged once and kept for /health?deep=1; the opt-in unhealthy exit.+ if (engine.kind === 'postgres') void recordServeTransport(engine, (line) => console.error(line));+ const restartRequiredExitSeconds = resolveRestartRequiredExitSeconds(process.env[SERVE_RESTART_REQUIRED_EXIT_ENV]);+ if (restartRequiredExitSeconds !== null) {+ installRestartRequiredExit(engine, restartRequiredExitSeconds, { log: (line) => console.error(line), exit: opts.exit ?? ((code: number) => { process.exit(code); }) });+ console.error(`[gbrain serve] ${SERVE_RESTART_REQUIRED_EXIT_ENV}=${restartRequiredExitSeconds}: exits ${SERVE_UNHEALTHY_EXIT_CODE} after persistence_restart_required holds that long (at most 3 self-exits per hour)`);+ }// #4768: stdio read-only access ceiling. HTTP refuses it: per-token grants// (auth rescope-token --operations / rescope-client) are its operation control.const access = parseAccessFlag(args);diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsindex 9592a00ebc..c78caf37b1 100644--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@ -500,8 +500,13 @@ export type ManagedDelegationOutcome =| { kind: 'own_consumer'; reason: 'opted_out' | 'not_host' | 'not_postgres' | 'not_managed' | 'no_owner' | 'owner_not_serve' | 'probe_failed'| 'kill_switch' | 'unsupported_flag' | 'no_socket' | 'older_serve' | 'serve_refused' | 'serve_lost' | 'serve_no_admission'; line: string | null };-const fallbackLine = (pid: number, cause: string, fix = 'Restart that serve on this gbrain version to remove the second consumer.'): string =>- `[sync] ${cause}; this run uses its own consumer beside the serve (PID ${pid}). ${fix}`;+/**+ * #6543: only a forced rung (the serve cannot take the run) really runs a consumer beside the serve; on the others this+ * process admits its writes and, with persistence.single_consumer on, the serve's consumer publishes them.+ */+const fallbackLine = (pid: number, cause: string, forced: boolean, fix = 'Restart that serve on this gbrain version to run the catch-up inside it.'): string => forced+ ? `[sync] ${cause}; this run uses its own consumer beside the serve (PID ${pid}). ${fix}`+ : `[sync] ${cause}; this run does not delegate to the serve (PID ${pid}): it admits its own writes, and with persistence.single_consumer on the serve's consumer publishes them. ${fix}`;/*** The Postgres rung of the delegation ladder (#6317). Called with the connected@@ -513,12 +518,16 @@ const fallbackLine = (pid: number, cause: string, fix = 'Restart that serve on t*/export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args: string[], opts: SyncOpts, deps: ManagedDelegationDeps = {}): Promise<ManagedDelegationOutcome> {const env = deps.env ?? process.env;- const own = (reason: Extract<ManagedDelegationOutcome, { kind: 'own_consumer' }>['reason'], line: string | null = null): ManagedDelegationOutcome => {+ // #6543: `force` makes "this run uses its own consumer" true where the serve cannot take the run (the opt-out, a serve+ // not answering its socket, an older serve): with persistence.single_consumer on, this process would otherwise run+ // waiter-only behind the serve it bypassed. A healthy serve beside a kill switch or an unsupported flag keeps consuming.+ const own = async (reason: Extract<ManagedDelegationOutcome, { kind: 'own_consumer' }>['reason'], line: string | null = null, force = false): Promise<ManagedDelegationOutcome> => {if (line) serr(line);+ if (force) (await import('../core/persistence/consumer-election.ts')).forceOwnConsumer(reason);return { kind: 'own_consumer', reason, line };};// 0. Opt-outs bypass the ladder before anything is probed or classified.- if (args.includes('--no-delegate') || env.GBRAIN_SYNC_NO_DELEGATE === '1') return own('opted_out');+ if (args.includes('--no-delegate') || env.GBRAIN_SYNC_NO_DELEGATE === '1') return own('opted_out', null, true);const { resolveBrainId } = await import('../core/brain-resolver.ts');const { getCliOptions } = await import('../core/cli-options.ts');if (resolveBrainId(getCliOptions().brain) !== 'host') return own('not_host');@@ -546,18 +555,18 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:return own('owner_not_serve', `[sync] the live write owner on this host is a ${owner.kind} process (PID ${pid}), which cannot host a delegated sync; this run uses its own consumer beside it.`);}if (env.GBRAIN_SERVE_SYNC_IPC === '0') {- return own('kill_switch', fallbackLine(pid, 'GBRAIN_SERVE_SYNC_IPC=0 turns serve-delegated sync off', 'Unset it to run the catch-up inside the serve.'));+ return own('kill_switch', fallbackLine(pid, 'GBRAIN_SERVE_SYNC_IPC=0 turns serve-delegated sync off', false, 'Unset it to run the catch-up inside the serve.'));}// 3. Argv gate (default-deny). On Postgres an unsupported flag keeps today's own consumer instead of refusing.const parsed = parseDelegatedSyncArgs(args);if (!parsed.ok) {- return own('unsupported_flag', fallbackLine(pid, `\`${parsed.refused}\` isn't supported through serve-delegated sync`, 'Drop the flag to run the catch-up inside the serve.'));+ return own('unsupported_flag', fallbackLine(pid, `\`${parsed.refused}\` isn't supported through serve-delegated sync`, false, 'Drop the flag to run the catch-up inside the serve.'));}// 4. Socket + secret: the serve bound to this source, else the legacy URL-keyed socket.const { sock, secret } = deps.socket ? await deps.socket(sourceId): { sock: await hookResolveSocketForConfig(cfg, sourceId), secret: readIpcSecretForConfig(cfg) };if (!sock || !existsSync(sock) || !secret) {- return own('no_socket', fallbackLine(pid, 'the running gbrain serve exposes no sync IPC socket (older gbrain, or GBRAIN_SERVE_SYNC_IPC=0 on the serve)'));+ return own('no_socket', fallbackLine(pid, 'the running gbrain serve exposes no sync IPC socket (older gbrain, or GBRAIN_SERVE_SYNC_IPC=0 on the serve)', false));}// 5. The hand-off: this CLI's durable writer registration (the one its own consumer would run under).const { registerLocalWriter } = await import('../core/persistence/identity.ts');@@ -585,19 +594,20 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:let start = await requestSyncStart(sock, { secret, clientToken, options, registration });if (start === IPC_UNAVAILABLE && await ownerAlive()) start = await requestSyncStart(sock, { secret, clientToken, options, registration });if (start === IPC_UNAVAILABLE) {- return own('no_socket', fallbackLine(pid, 'the running gbrain serve is not answering its IPC socket'));+ return own('no_socket', fallbackLine(pid, 'the running gbrain serve is not answering its IPC socket', true), true);}if ('degraded' in (start as object)) {- return own('older_serve', fallbackLine(pid, 'the running gbrain serve predates serve-delegated managed sync'));+ return own('older_serve', fallbackLine(pid, 'the running gbrain serve predates serve-delegated managed sync', true), true);}const startResp = start as Exclude<SyncStartIpcResult, typeof IPC_UNAVAILABLE | { degraded: string }>;if (!startResp.ok) {if (startResp.refusal) throw operationErrorFromEnvelope(startResp.refusal);if (startResp.error === 'unsupported_kind') {- return own('older_serve', fallbackLine(pid, 'the running gbrain serve predates serve-delegated managed sync, or runs with GBRAIN_SERVE_SYNC_IPC=0'));+ // #6543: a current serve that echoes the protocol with unsupported_kind is healthy with delegation off on its side: it keeps consuming.+ return own('older_serve', fallbackLine(pid, 'the running gbrain serve runs with serve-delegated managed sync off (GBRAIN_SERVE_SYNC_IPC=0 on the serve)', false, 'Unset it on the serve to run the catch-up inside it.'));}if (startResp.error === 'permission_denied') throw operationErrorFromEnvelope({ error: 'permission_denied', message: 'The serve refused this CLI\'s writer registration.' });- return own('serve_refused', fallbackLine(pid, startRefusalText(startResp).replace(/\.$/, ''), 'Fix that, or let this run finish with its own consumer.'));+ return own('serve_refused', fallbackLine(pid, startRefusalText(startResp).replace(/\.$/, ''), false, 'Fix that, or let this run finish without the serve.'));}const jobId = startResp.jobId!;serr(startResp.completeddiff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex b3d8aa5058..c1ea4d48cf 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -133,6 +133,10 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {const { syncResumeCommand } = await import('../../core/sync-reconcile.ts');const { getCliOptions } = await import('../../core/cli-options.ts');const resumeCommand = syncResumeCommand(args, getCliOptions().brain);+ // #6543: --all never delegates, so its opt-out keeps this process's own consumer here (single-source runs: sync-delegate.ts).+ if (syncAll && (args.includes('--no-delegate') || process.env.GBRAIN_SYNC_NO_DELEGATE === '1')) {+ (await import('../../core/persistence/consumer-election.ts')).forceOwnConsumer('opted_out');+ }if (syncAll) return await runSyncAll(engine, { ...flags, ...fanout }, { noEmbed, embeddingCredentialError, resumeCommand });return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand, args });diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 215c8b656f..a43df8b089 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -473,6 +473,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },+ { since: '0.60.185.0', text: 'Read pools no longer pipeline statements behind a transaction-mode pooler: a database URL on port 6543 or with `?prepare=false`, or `GBRAIN_PREPARE=0`, now builds the read pools with `max_pipeline: 0` (through Supavisor, pipelined statements hung or came back with another statement\'s rows, #6543). A session-mode pooler (Supabase port 5432) and direct URLs keep the driver default; a URL `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins. The direct pool is unchanged.' },+ { since: '0.60.185.0', text: '`/health?deep=1` now answers 503 `persistence_restart_required` when the serve\'s persistence consumer reports restart_required (it answered 200 before), and every deep-health 503 carries a stable `code` (`persistence_restart_required`, `pool_inflight_over_budget`, `deep_health_probe_failed` with `reason`), `fix` and `docs`. Both answers carry a `transport` block (pooler mode, the live `prepare` and `max_pipeline` with its reason, the server `statement_timeout`, `session_timeouts_not_applied`), and `gbrain serve` logs it once at startup as a `[gbrain serve] transport` line.' },+ { since: '0.60.185.0', text: 'New opt-in `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (at least 120; a smaller value refuses to start serve): once the persistence consumer has reported restart_required continuously for n seconds, `gbrain serve` disconnects under a 5 s deadline and exits 69 (`serve_unhealthy_exit`) so a supervisor restarts it; after 3 self-exits within an hour (`serve-self-exit.json` under the gbrain home) it stops exiting and reports `self_exit_suppressed`. Off by default: nothing changes unless it is set.' },+ { since: '0.60.185.0', text: '`gbrain sync --no-delegate` (or `GBRAIN_SYNC_NO_DELEGATE=1`), and a sync that falls back because the serve is not answering its IPC socket or predates delegated sync, now run this process\'s own consumer even under persistence.single_consumer (they waited behind the serve they bypassed), and log `two_consumers_on_host` while a serve consumes on the same host. The other fallback lines no longer claim the run uses its own consumer: they say it does not delegate and, with single_consumer on, the serve publishes its writes.' },+ { since: '0.60.185.0', text: 'A `pg_statement_build_failed` line for `UNDEFINED_VALUE` now names the parameter (`param=$2`, or `param=?` for an array element), and a pipelined build failure no longer lets the pool queue more statements behind it on a connection built not to pipeline. A connection closed by the server (57P01) or a pooler no longer hands its error to the first statement on the replacement connection.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex b142b3cd1d..1f0dacec6f 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -38,7 +38,7 @@import postgres from '#postgres'import { traceSqlOptions } from './sql-trace.ts';-import { gbrainApplicationName, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';+import { gbrainApplicationName, readPoolPipelineOptions, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';import { redactPgUrl } from './url-redact.ts';import { logConnectionEvent } from './connection-audit.ts';@@ -355,6 +355,7 @@ export class ConnectionManager {types: { bigint: postgres.BigInt },onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},shared_types: resolveSharedTypes(this.opts.url),+ ...readPoolPipelineOptions(this.opts.url),};const timeouts = resolveSessionTimeouts();Object.assign(opts, poolHealthOptions({ ...this.opts.health?.('read'), onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status) }, timeouts.statement_timeout));diff --git a/src/core/db.ts b/src/core/db.tsindex 50f9886126..46c241a37e 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -113,6 +113,43 @@ export function resolvePrepare(url: string): boolean | undefined {return undefined;}+/** Why a read-side pool got its `max_pipeline` (#6543); `/health?deep=1` reports it beside the live value. */+export type ReadPoolPipelineReason = 'url_max_pipeline' | 'env_pgmax_pipeline' | 'transaction_pooler_port' | 'url_prepare_false' | 'gbrain_prepare_off' | 'default';++/**+ * #6543: the `max_pipeline` a read-side pool (the module singleton, an engine's+ * instance pool, the connection manager's read pool) is built with. A+ * transaction-mode pooler cannot carry statements pipelined on one client+ * connection across transaction boundaries: through Supavisor they hung or came+ * back with another statement's rows. So a transaction-mode URL (port 6543 or+ * `?prepare=false`, read from the URL itself because `GBRAIN_PREPARE` wins+ * inside `resolvePrepare`) or `GBRAIN_PREPARE=0` gets `0`. A session-mode+ * pooler (Supabase's :5432) keeps pipelining. The driver lets the options+ * object outrank the URL and `PGMAX_PIPELINE`, so `value` is null (the option+ * stays unset and the driver reads them, default 100) whenever the URL names+ * `max_pipeline` or `PGMAX_PIPELINE` is set and non-empty. The direct pool+ * never calls this.+ */+export function resolveReadPoolPipeline(url: string): { value: number | null; reason: ReadPoolPipelineReason } {+ const [beforeFragment = ''] = url.split('#', 1);+ const queryAt = beforeFragment.indexOf('?');+ const params = new URLSearchParams(queryAt >= 0 ? beforeFragment.slice(queryAt + 1) : '');+ if (params.has('max_pipeline')) return { value: null, reason: 'url_max_pipeline' };+ if ((process.env.PGMAX_PIPELINE ?? '').trim() !== '') return { value: null, reason: 'env_pgmax_pipeline' };+ let port = '';+ try { port = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://')).port; } catch { /* unparseable: no port */ }+ if (AUTO_DETECT_PORTS.has(port)) return { value: 0, reason: 'transaction_pooler_port' };+ if (params.get('prepare') === 'false') return { value: 0, reason: 'url_prepare_false' };+ if (process.env.GBRAIN_PREPARE === 'false' || process.env.GBRAIN_PREPARE === '0') return { value: 0, reason: 'gbrain_prepare_off' };+ return { value: null, reason: 'default' };+}++/** The read-side pool option `resolveReadPoolPipeline` decides: `{ max_pipeline: 0 }` or nothing. */+export function readPoolPipelineOptions(url: string): { max_pipeline?: number } {+ const { value } = resolveReadPoolPipeline(url);+ return value === null ? {} : { max_pipeline: value };+}+/*** Seconds a pool waits for a connection before giving up with CONNECT_TIMEOUT* when its URL names no `connect_timeout` of its own.@@ -274,16 +311,17 @@ export function resolveMaxLifetimeSeconds(* Set any env var to '0' or 'off' to disable that GUC entirely.** Delivered via postgres.js's `connection` option, which sends these as- * startup parameters in the initial connection packet. Works correctly- * with PgBouncer session mode AND transaction mode: startup parameters- * pass through to the backend on connection creation and persist for the- * backend's lifetime (unlike `SET` commands which transaction-mode- * PgBouncer strips between transactions).+ * startup parameters in the initial connection packet. A direct server and a+ * session-mode pooler apply them for the backend's lifetime. A transaction-mode+ * pooler does not: PgBouncer and Supavisor (Supabase :6543) drop or ignore+ * startup parameters, so `SHOW statement_timeout` through them reads `0` and no+ * server-side timeout bounds an autocommit statement (#6543; doctor's+ * `persistence_session_timeouts` and serve's transport line report it, and+ * `ALTER ROLE ... SET statement_timeout` is the fix there).** Supersedes the v0.21.0 `setSessionDefaults(sql)` helper, which used- * a post-pool `SET` command. That approach is unreliable in PgBouncer- * transaction mode (transaction-mode poolers strip session-state SETs- * between transactions); startup parameters are durable.+ * a post-pool `SET` command; transaction-mode poolers strip session-state+ * SETs between transactions.*/const DEFAULT_STATEMENT_TIMEOUT = '5min';const DEFAULT_IDLE_TX_TIMEOUT = '5min';@@ -311,8 +349,8 @@ export interface PoolHealthHooks {onpoisoned?: (status: string) => void;/** #6383: the in-flight watchdog retired a connection whose statement never answered. */onstuck?: (info: StuckConnectionInfo) => void;- /** #6383: a statement failed to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) and was rejected alone. */- onbuilderror?: (code: string, statement: string) => void;+ /** #6383: a statement failed to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) and was rejected alone; #6543: `parameter` is the undefined one's 1-based index. */+ onbuilderror?: (code: string, statement: string, parameter?: number) => void;/** An answer arrived on a connection with no statement waiting for it; the driver retired the connection. */ondesync?: (info: DesyncConnectionInfo) => void;}@@ -334,9 +372,11 @@ export function gucMilliseconds(value: string | undefined): number | null {/*** #6383: seconds a head statement may wait with nothing coming back before the* driver retires its connection: the pool's `statement_timeout` plus- * `GBRAIN_PG_STUCK_GRACE_MS` (default 30000). A legitimate statement cannot- * outlive the server-side timeout, so only a wedged connection (a desynced- * pipeline, a pooler that swallowed a CancelRequest, a dead peer) reaches it.+ * `GBRAIN_PG_STUCK_GRACE_MS` (default 30000). Usually only a wedged connection+ * (a desynced pipeline, a pooler that swallowed a CancelRequest, a dead peer)+ * reaches it, but not always: behind a transaction-mode pooler the startup+ * statement_timeout never applies, so a slow statement can reach it too, and+ * the clock restarts on every byte, so a streaming statement never does (#6543).* Null, which disables the watchdog, when the statement timeout is off or the* grace is `0`/`off`.*/@@ -454,13 +494,14 @@ export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {})onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},...poolHealthOptions(hooks, timeouts.statement_timeout),shared_types: resolveSharedTypes(url),+ ...readPoolPipelineOptions(url),};opts.connection = { ...timeouts, application_name: gbrainApplicationName() };if (typeof prepare === 'boolean') {opts.prepare = prepare;if (!prepare) {console.warn(- '[gbrain] Prepared statements disabled (PgBouncer transaction-mode convention on port 6543). Override with GBRAIN_PREPARE=true if your pooler runs in session mode.',+ '[gbrain] Prepared statements and statement pipelining disabled (transaction-mode pooler convention: port 6543, ?prepare=false or GBRAIN_PREPARE=0). If your pooler runs in session mode, connect on its session port (Supabase: 5432); GBRAIN_PREPARE=true re-enables prepared statements only, and ?max_pipeline= or PGMAX_PIPELINE sets the pipeline depth.',);}}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 1d1834c163..fc2a881fbb 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -318,11 +318,16 @@ export const CODES = {pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },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_restart_required: { class: 'host_only', summary: "This gbrain serve's persistence consumer reports restart_required, so it claims no write until the process restarts; `/health?deep=1` answers 503 with this code.", why: "A preparation abandoned past the ceiling (a zombie) or a publication that never settled past its deadline makes the owner stop claiming on every root, because the abandoned work may still hold locks or write files; only a process exit releases it. The deep health probe reports it so a supervisor can restart serve; it never acts on its own (GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS opts into an exit).", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart this gbrain serve (systemctl --user restart gbrain-serve, or stop and start the foreground process); to let a supervisor do it unattended, set GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=300 in the serve environment (~/.gbrain/env for the installed service). Then run gbrain sources writer status --json.' },+ pool_inflight_over_budget: { class: 'host_only', summary: "A pooled statement of this gbrain serve has waited longer than the read pool's in-flight budget (statement_timeout plus grace); `/health?deep=1` answers 503 with this code.", why: "The in-flight watchdog retires a connection only after nothing arrives for the budget, so a statement that keeps receiving bytes, or one behind a transaction-mode pooler where no server statement_timeout applies, can sit past it while every statement queued behind it waits. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check.' },+ deep_health_probe_failed: { class: 'retryable', summary: "The pooled `SELECT 1` of `/health?deep=1` did not answer: an earlier probe is still pending, it timed out, or it failed.", reasons: ['pending', 'timeout', 'error'], why: "The deep probe runs through the ordinary pooled dispatch, where handler statements wait, so a saturated or wedged pool fails it while plain /health (a reserved idle connection) may still answer 200. One deep probe runs per engine at a time.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Retry in a few seconds; if it keeps failing, run gbrain doctor --json from a fresh process to check the database and pooler, then restart this gbrain serve.' },+ serve_self_exit_suppressed: { class: 'host_only', summary: "gbrain serve stayed at restart_required past GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS but did not exit, because it had already exited on its own 3 times within the hour; `/health?deep=1` reports self_exit_suppressed.", why: "The opt-in self-exit keeps a durable ledger (serve-self-exit.json under the gbrain home). A serve that reaches restart_required again right after every restart has a cause a restart does not fix, so after 3 self-exits in an hour it keeps serving reads and leaves the decision to a human instead of looping.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Run gbrain sources writer status --json and gbrain doctor --json, report both with the serve log lines, then restart serve by hand.' },+ serve_unhealthy_exit: { class: 'unavailable', exit: 69, summary: "gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS.", why: "Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line.' },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_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: "Nothing arriving for that long usually means the connection 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. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too, and the clock restarts on every byte, so a statement that keeps streaming is never retired. 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.' },+ 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; it failed, and a transaction it was part of was aborted rather than committed without it.", why: "Either a gbrain programming error at the call site the warn line names by keyword and table (and by `param=$n`), or, behind a transaction-mode pooler (port 6543, prepare off), a value read from a row that belonged to another statement: a pooler that misroutes pipelined answers hands a statement someone else's row, and binding one of its missing columns fails here. 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: 'On a transaction-mode pooler, check /health?deep=1 transport (max_pipeline should be 0; PGMAX_PIPELINE=0 on the serve environment forces it) and treat earlier reads as suspect (docs/guides/pooler-misroute-audit.md); otherwise report the warn line (it names the statement and parameter) as a gbrain bug so the call site gets a null where it bound undefined.' },pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },pglite_vector_index_too_large: { class: 'unavailable', summary: "A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap.", why: "pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans.", docs: 'docs/ENGINES.md#pglite-vector-index-ceiling', suggestion: 'Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json', fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists what moves to Postgres, the blockers and the exact run command.', requires_exclusive: false } },plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },diff --git a/src/core/exit-codes.ts b/src/core/exit-codes.tsindex e903662d27..7a1b3f7471 100644--- a/src/core/exit-codes.ts+++ b/src/core/exit-codes.ts@@ -5,8 +5,8 @@* Agent operator contract v1 table (docs/guides/exit-codes.md):* 0 ok · 1 failed (class/retryable in JSON) · 2 usage / invalid input ·* 3 confirmation_required (its ONLY meaning) · 10 write pending ·- * 11 resumable budget stop · 75 migration lock held · 124 timeout ·- * 130 interrupted. `test/exit-codes.test.ts` enumerates every literal+ * 11 resumable budget stop · 69 serve exited unhealthy · 75 migration+ * lock held · 124 timeout · 130 interrupted. `test/exit-codes.test.ts` enumerates every literal* exit 3 in src/ so a new one cannot reuse it.*/@@ -43,3 +43,10 @@ export const PENDING_WRITE_EXIT_CODE = 10;* from 3, which agent-facing commands reserve for "ask the user first".*/export const BUDGET_STOP_EXIT_CODE = 11;++/**+ * #6543: `gbrain serve` exited on its own because its persistence consumer+ * reported `restart_required` continuously for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS`+ * (`serve_unhealthy_exit`). EX_UNAVAILABLE: a supervisor restarts it.+ */+export const SERVE_UNHEALTHY_EXIT_CODE = 69;diff --git a/src/core/persistence/consumer-election.ts b/src/core/persistence/consumer-election.tsindex 0240291668..17d92c8efa 100644--- a/src/core/persistence/consumer-election.ts+++ b/src/core/persistence/consumer-election.ts@@ -116,6 +116,7 @@ export class WaiterOnlyConsumer implements PersistenceConsumerLike {private transition: Promise<void> | undefined;private delayMs: number;private wakeRequested = false;+ private overlapRead: Promise<void> | undefined;private readonly self = consumerIdentity();/** The probe reads through the consumer's statement route (the direct lane when the engine has one). */private readonly statements: BrainEngine;@@ -231,9 +232,19 @@ export class WaiterOnlyConsumer implements PersistenceConsumerLike {inner.start();if (mode === 'full') { if (this.timer) clearTimeout(this.timer); this.timer = undefined; }if (reason !== 'no_live_owner' && reason !== 'single_consumer_off' && reason !== 'single_process_engine') this.log(`phase=consumer_probe reason=${mode} message="${reason}"`);+ if (reason.startsWith('forced:')) this.overlapRead = this.reportServeOverlap(reason);})().finally(() => { this.transition = undefined; });return this.transition;}+ /** #6543: a forced consumer skipped the election, so it says once when a live serve consumer of this host claims beside it. */+ private async reportServeOverlap(reason: string): Promise<void> {+ try {+ const signal = AbortSignal.timeout(this.opts.phaseMs ?? 5000);+ const rows = await (this.opts.readConsumers ? this.opts.readConsumers(signal) : listHostConsumers(this.statements, this.opts.hostId, { signal }));+ const serve = rows.find(row => row.kind === 'serve' && !(row.pid === this.self.pid && row.nonce === this.self.nonce) && row.renewed_age_ms < CONSUMER_LIVE_MS);+ if (serve) this.log(`phase=consumer_probe reason=two_consumers_on_host message="this ${this.opts.kind} process consumes beside serve pid ${serve.pid} on this host (${reason}); both claim writes until one exits"`);+ } catch { /* best-effort: doctor's two_consumers_on_host reports the overlap too */ }+ }private drainBack(owner: ListedConsumer): Promise<void> {if (this.transition) return this.transition;this.transition = (async () => {@@ -275,6 +286,7 @@ export class WaiterOnlyConsumer implements PersistenceConsumerLike {if (this.timer) { clearTimeout(this.timer); this.timer = undefined; }await this.tickPromise;await this.transition;+ await this.overlapRead;await this.inner?.stop();await this.heartbeat?.stop();}diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 4de9695b6c..1bd862e2c0 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -685,7 +685,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {return { ceilingMs,onOverdue: () => {if (clock) clock.waitingOn = 'publication_deadline';- this.log('publication', 'publication_deadline', `request ${row.request_id}: publishing past the ${ceilingMs} ms ceiling; its transaction's server-side timeouts end it on Postgres`);+ this.log('publication', 'publication_deadline', `request ${row.request_id}: publishing past the ${ceilingMs} ms ceiling; on Postgres its transaction-local timeouts end it only if the server sees the transaction idle, not when the client connection is wedged`);},onStuck: settled => {this.stuckPublications.set(row.id, { request_id: row.request_id, stuck_at: new Date().toISOString() });diff --git a/src/core/pool-gauge.ts b/src/core/pool-gauge.tsindex a27325fae5..87c79203d8 100644--- a/src/core/pool-gauge.ts+++ b/src/core/pool-gauge.ts@@ -95,7 +95,8 @@ export function formatPoisonedDiscardWarning(pool: 'read' | 'direct', status: st/*** #6383: connections the vendored driver's in-flight watchdog retired because a- * statement waited `statement_timeout + grace` with nothing coming back, and+ * statement waited `statement_timeout + grace` with nothing coming back (the+ * clock restarts on every byte, so a streaming statement never trips it), and* statements the driver rejected alone because they failed to build. Each is* counted once and logged as one fixed-shape warn line. The statement is named* by its first keyword and table (`sqlLabel`), never its text or parameters.@@ -118,8 +119,8 @@ export class PoolIncidentCounter {}/** The driver hooks of one pool, bound to this counter (what an engine passes as `PoolHealthHooks`). */- hooks(pool: 'read' | 'direct'): { onstuck: (info: { age_ms: number; queued: number; statement: string }) => void; onbuilderror: (code: string, statement: string) => void; ondesync: (info: { message: string; connection: number; statement: string }) => void } {- return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement) => this.recordBuildFailure(pool, code, statement), ondesync: (info) => this.recordDesync(pool, info) };+ hooks(pool: 'read' | 'direct'): { onstuck: (info: { age_ms: number; queued: number; statement: string }) => void; onbuilderror: (code: string, statement: string, parameter?: number) => void; ondesync: (info: { message: string; connection: number; statement: string }) => void } {+ return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement, parameter) => this.recordBuildFailure(pool, code, statement, parameter), ondesync: (info) => this.recordDesync(pool, info) };}recordStuck(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): void {@@ -132,15 +133,15 @@ export class PoolIncidentCounter {try { console.warn(formatDesyncWarning(pool, info)); } catch { /* best-effort */ }}- recordBuildFailure(pool: 'read' | 'direct', code: string, statement: string): void {+ recordBuildFailure(pool: 'read' | 'direct', code: string, statement: string, parameter?: number): void {this.buildFailures += 1;- try { console.warn(formatBuildFailureWarning(pool, code, statement)); } catch { /* best-effort */ }+ try { console.warn(formatBuildFailureWarning(pool, code, statement, parameter)); } catch { /* best-effort */ }}}export function formatStuckConnectionWarning(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): string {return `[gbrain] warn code=pg_connection_stuck pool=${pool} age_ms=${Math.max(0, Math.round(info.age_ms))} queued=${Math.max(0, info.queued | 0)} sql=${sqlLabel(info.statement).replaceAll(' ', '_')}` +- ` cause="a statement waited past statement_timeout with nothing coming back from the server; the connection was retired and its queued statements failed with CONNECTION_STUCK"` ++ ` cause="a statement waited past the pool's in-flight budget (statement_timeout plus grace) with nothing coming back from the server; the connection was retired and its queued statements failed with CONNECTION_STUCK"` +` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-stuck`;}@@ -151,9 +152,14 @@ export function formatDesyncWarning(pool: 'read' | 'direct', info: { message: st` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-desync`;}-export function formatBuildFailureWarning(pool: 'read' | 'direct', code: string, statement: string): string {+/**+ * #6543: an `UNDEFINED_VALUE` line names the undefined parameter (`param=$2`), or `param=?` when the driver raised it for+ * an array element, which carries no index.+ */+export function formatBuildFailureWarning(pool: 'read' | 'direct', code: string, statement: string, parameter?: number): string {const safeCode = /^[A-Z_]+$/.test(code) ? code : 'BUILD_FAILED';- return `[gbrain] warn code=pg_statement_build_failed error=${safeCode} pool=${pool} sql=${sqlLabel(statement).replaceAll(' ', '_')}` +- ` cause="a statement could not be built from its parameters and was rejected before it reached the connection; other statements were not affected"` ++ const param = safeCode !== 'UNDEFINED_VALUE' ? '' : Number.isInteger(parameter) && parameter! > 0 ? ` param=$${parameter}` : ' param=?';+ return `[gbrain] warn code=pg_statement_build_failed error=${safeCode} pool=${pool} sql=${sqlLabel(statement).replaceAll(' ', '_')}${param}` ++ ` cause="a statement could not be built from its parameters and was rejected before it reached the connection; on a transaction-mode pooler this usually means a value came from a row another statement was sent (a misrouted answer)"` +` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-statement-build-failed`;}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex bf5fa0e042..a923750632 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -404,7 +404,7 @@ export class PostgresEngine implements BrainEngine {// GBRAIN_PG_NOTICES=1.onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},...db.poolHealthOptions({ ...this.poolHealth('read'), onpoisoned: (status: string) => this.onPoisoned('read', status) }, timeouts.statement_timeout),- shared_types: db.resolveSharedTypes(url),+ shared_types: db.resolveSharedTypes(url), ...db.readPoolPipelineOptions(url),};opts.connection = { ...timeouts, application_name: db.gbrainApplicationName() };if (typeof prepare === 'boolean') {diff --git a/test/e2e/audit-pooler-misroute-postgres.test.ts b/test/e2e/audit-pooler-misroute-postgres.test.tsnew file mode 100644index 0000000000..ee2f130e8b--- /dev/null+++ b/test/e2e/audit-pooler-misroute-postgres.test.ts@@ -0,0 +1,152 @@+/**+ * #6543 (I1): scripts/audit-pooler-misroute.ts on Postgres.+ *+ * Protects: a seeded misrouted effect (another request's source identity) and+ * a request carrying another source's incarnation or page are reported as+ * `mismatch` with the conflicting values; a clean window reports none and+ * counts every row verified; a row updated while the audit runs (between two+ * batches) is `unknown` (changed_during_audit), never `mismatch`, even when the+ * update makes it look misrouted; coverage gaps (compacted history, a removed+ * page, effects from before the identity columns) are `unknown`, never clean;+ * every statement the audit sends is a read inside a READ ONLY transaction; a+ * transaction-mode URL is refused and the session pooler port is accepted.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { auditConnectionOptions, auditPoolerMisroute, refuseTransactionPoolerUrl } from '../../scripts/audit-pooler-misroute.ts';+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++let engine: PostgresEngine;+let databaseUrl: string;+let close: () => Promise<void>;+let a: { id: string; incarnation: string };+let b: { id: string; incarnation: string };++beforeAll(async () => {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; databaseUrl = pg.databaseUrl; close = pg.close;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const source = async (id: string) => {+ const [row] = await engine.executeRaw<{ incarnation: string }>("INSERT INTO sources(id,name,config) VALUES($1,$1,'{}') RETURNING incarnation::text", [id]);+ return { id, incarnation: row!.incarnation };+ };+ a = await source(`audit-a-${randomUUID().slice(0, 8)}`);+ b = await source(`audit-b-${randomUUID().slice(0, 8)}`);+}, 120_000);+afterAll(async () => { await close?.(); });++type Window = { since: Date; until: Date };+/** The window is read from the database clock, so each test sees only its own rows. */+const dbNow = async () => new Date((await engine.executeRaw<{ now: string }>('SELECT clock_timestamp()::text AS now'))[0]!.now);+async function window<T>(fn: () => Promise<T>): Promise<Window & { value: T }> {+ const since = await dbNow();+ const value = await fn();+ return { since, until: new Date((await dbNow()).getTime() + 1), value };+}+async function request(src: { id: string; incarnation: string }, opts: { slug?: string; incarnation?: string; pageId?: number | null; compacted?: boolean } = {}) {+ const [row] = await engine.executeRaw<{ id: string; request_id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,+ slug,page_id,digest,authority,intent_bytes,terminal_reservation,state,compacted)+ VALUES('local_cli','audit',gen_random_uuid(),'put_page',$1,$2::uuid,$3,$4,'d','{}'::jsonb,1,16384,'committed',$5) RETURNING id::text, request_id::text`,+ [src.id, opts.incarnation ?? src.incarnation, opts.slug ?? `audit/${randomUUID().slice(0, 8)}`, opts.pageId ?? null, opts.compacted ?? false]);+ return row!;+}+async function effect(requestRowId: string, identity: { source_id: string | null; source_incarnation: string | null }) {+ const [row] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation)+ VALUES($1::uuid,$2,'{}'::jsonb,$3,$4::uuid) RETURNING id::text`, [requestRowId, `embed-${randomUUID().slice(0, 6)}`, identity.source_id, identity.source_incarnation]);+ return row!.id;+}+async function page(src: { id: string }, slug: string) {+ const [row] = await engine.executeRaw<{ id: number }>("INSERT INTO pages(source_id,slug,type,title,compiled_truth) VALUES($1,$2,'note',$2,'') RETURNING id", [src.id, slug]);+ return row!.id;+}+async function audit(w: Window, opts: { batchSize?: number; onBatch?: (index: number) => Promise<void> } = {}) {+ const statements: string[] = [];+ const sql = postgres(databaseUrl, { ...auditConnectionOptions(), debug: (_connection: number, query: string) => { statements.push(query); } } as Parameters<typeof postgres>[1]);+ try {+ return { report: await auditPoolerMisroute(sql as never, { since: w.since, until: w.until, batchSize: opts.batchSize ?? 2, batchTimeoutMs: 10_000, onBatch: opts.onBatch }), statements };+ } finally { await sql.end({ timeout: 5 }); }+}+const readOnly = (statements: string[]) => {+ for (const statement of statements) expect(statement.trim()).toMatch(/^(begin isolation level repeatable read read only|SELECT\b|commit|rollback)/i);+};++describe('audit-pooler-misroute', () => {+ test('a clean window reports no mismatch and verifies every row, over several batches, with reads only', async () => {+ const w = await window(async () => {+ for (let i = 0; i < 3; i++) {+ const r = await request(a);+ await effect(r.id, { source_id: a.id, source_incarnation: a.incarnation });+ }+ const slug = `audit/page-${randomUUID().slice(0, 8)}`;+ await request(b, { slug, pageId: await page(b, slug) });+ });+ const { report, statements } = await audit(w);+ expect(report.mismatch).toEqual([]);+ expect(report.unknown).toEqual([]);+ expect(report.verified_ok).toEqual({ requests: 4, effects: 3 });+ expect(report.batches).toBeGreaterThan(2);+ expect(report.snapshot).toBe('per_batch');+ expect(report.disclaimer).toContain('no global snapshot');+ readOnly(statements);+ }, 60_000);++ test('seeded misroutes are mismatches with the conflicting values; coverage gaps are unknown', async () => {+ const w = await window(async () => {+ const victim = await request(a);+ const misroutedEffect = await effect(victim.id, { source_id: b.id, source_incarnation: b.incarnation });+ const foreignIncarnation = await request(a, { incarnation: b.incarnation });+ const foreignPage = await request(a, { pageId: await page(b, `audit/foreign-${randomUUID().slice(0, 8)}`) });+ const compacted = await request(a, { compacted: true });+ const removedPage = await request(a, { pageId: 2_000_000_000 });+ const legacy = await request(a);+ const legacyEffect = await effect(legacy.id, { source_id: null, source_incarnation: null });+ return { victim, misroutedEffect, foreignIncarnation, foreignPage, compacted, removedPage, legacy, legacyEffect };+ });+ const ids = w.value;+ const { report, statements } = await audit(w);+ expect(report.mismatch).toEqual(expect.arrayContaining([+ expect.objectContaining({ table: 'persistence_effects', id: ids.misroutedEffect, request_id: ids.victim.request_id, field: 'source_id', value: b.id, expected: a.id }),+ expect.objectContaining({ table: 'persistence_effects', id: ids.misroutedEffect, field: 'source_incarnation', value: b.incarnation, expected: a.incarnation }),+ expect.objectContaining({ table: 'persistence_requests', id: ids.foreignIncarnation.id, field: 'source_incarnation', value: b.incarnation, belongs_to: { table: 'sources', id: b.id } }),+ expect.objectContaining({ table: 'persistence_requests', id: ids.foreignPage.id, field: 'page_id', belongs_to: { table: 'sources', id: b.id } }),+ ]));+ expect(report.mismatch).toHaveLength(4);+ expect(report.unknown).toEqual(expect.arrayContaining([+ { table: 'persistence_requests', id: ids.compacted.id, request_id: ids.compacted.request_id, reasons: ['compacted_history'] },+ { table: 'persistence_requests', id: ids.removedPage.id, request_id: ids.removedPage.request_id, reasons: ['page_removed'] },+ { table: 'persistence_effects', id: ids.legacyEffect, request_id: ids.legacy.request_id, reasons: ['effect_identity_unset'] },+ ]));+ expect(report.unknown_by_reason).toEqual({ compacted_history: 1, page_removed: 1, effect_identity_unset: 1 });+ expect(report.verified_ok).toEqual({ requests: 2, effects: 0 });+ readOnly(statements);+ }, 60_000);++ test('a row updated between batches is unknown (changed_during_audit), never a mismatch, even when the update makes it look misrouted', async () => {+ const w = await window(async () => {+ const rows = [];+ for (let i = 0; i < 4; i++) rows.push(await request(a));+ const effects = [];+ for (const r of rows) effects.push(await effect(r.id, { source_id: a.id, source_incarnation: a.incarnation }));+ return { rows, effects };+ });+ const late = w.value.effects[3]!;+ const { report } = await audit(w, { batchSize: 2, onBatch: async index => {+ // After the first batch committed: a concurrent writer rewrites an effect the audit has not read yet.+ if (index === 1) await engine.executeRaw('UPDATE persistence_effects SET source_id=$1, source_incarnation=$2::uuid, updated_at=now() WHERE id=$3', [b.id, b.incarnation, late]);+ } });+ expect(report.mismatch).toEqual([]);+ expect(report.unknown).toEqual([{ table: 'persistence_effects', id: late, request_id: w.value.rows[3]!.request_id, reasons: ['changed_during_audit'] }]);+ expect(report.verified_ok).toEqual({ requests: 4, effects: 3 });+ }, 60_000);++ test('a transaction-mode URL is refused; a direct URL and the session pooler port are accepted', () => {+ expect(refuseTransactionPoolerUrl('postgresql://u:[email protected]:6543/postgres')).toContain('port 6543');+ expect(refuseTransactionPoolerUrl('postgresql://u:[email protected]:5432/postgres?prepare=false')).toContain('prepare=false');+ expect(refuseTransactionPoolerUrl('postgresql://u:[email protected]:5432/postgres')).toBeNull();+ expect(refuseTransactionPoolerUrl('postgresql://u:[email protected]/postgres')).toBeNull();+ expect(refuseTransactionPoolerUrl('not a url')).toContain('not a valid');+ });+});diff --git a/test/e2e/persistence-two-consumers-postgres.test.ts b/test/e2e/persistence-two-consumers-postgres.test.tsindex a9c32d12f2..54f827d187 100644--- a/test/e2e/persistence-two-consumers-postgres.test.ts+++ b/test/e2e/persistence-two-consumers-postgres.test.ts@@ -15,6 +15,9 @@* disappears promotes within two leases and drains back after the owner has* been live for three ticks. Fails on the base branch: no heartbeat table,* no election, and the CLI's own pid stamps the claims whatever the switch.+ * #6543: with the switch on and a serve whose heartbeat renews while it+ * claims nothing, `--no-delegate` runs the sync's own consumer and drains its+ * rows (before: waiter-only behind the wedged serve, nothing claimed).*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -25,7 +28,8 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../../src/core/engine.ts';import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';-import { WaiterOnlyConsumer } from '../../src/core/persistence/consumer-election.ts';+import { resetOwnConsumerForTest, WaiterOnlyConsumer } from '../../src/core/persistence/consumer-election.ts';+import { maybeDelegateManagedSyncToServe } from '../../src/commands/sync-delegate.ts';import { consumerIdentity, listHostConsumers, resetConsumerIdentityForTest, startConsumerHeartbeat, type ListedConsumer } from '../../src/core/persistence/consumer-heartbeat.ts';import { claimOwner, setClaimOwnerForTest } from '../../src/core/persistence/claim-phase.ts';import { localHostIdentity } from '../../src/core/persistence/identity.ts';@@ -156,6 +160,40 @@ describe.skipIf(!hasDatabase())('two consumers on one host (Postgres, #6317)', (}), 300_000);}+ test('#6543: --no-delegate with single_consumer on, beside a heartbeating serve that claims nothing: the sync runs its own consumer and drains its own rows', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '8' }, async () => {+ await engine.setConfig('persistence.single_consumer', 'true');+ resetWriteSwitches();+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('DELETE FROM persistence_consumers');+ // The #6543 wedge: a serve whose heartbeat keeps renewing (not restart_required) while it claims nothing.+ const wedged = startConsumerHeartbeat(engine, hostId, { kind: 'serve', mode: 'full', identity: { pid: process.pid + 300_000, nonce: 'wedged-serve', pid_ns: original.pid_ns },+ everyMs: 2_000, report: () => ({ restart_required: false, root_barrier_age_ms: null }) });+ await wedged.renew();+ const stderr: string[] = [];+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => { stderr.push(String(chunk)); return (write as (...a: unknown[]) => boolean)(chunk, ...rest); }) as typeof process.stderr.write;+ try {+ const f = await fixture(20);+ const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull', '--no-delegate'], { sourceId: f.id, noPull: true });+ expect(outcome).toEqual({ kind: 'own_consumer', reason: 'opted_out', line: null });+ startPersistenceConsumer(engine, { engine: 'postgres' });+ await waitFor(async () => (persistenceConsumerStatus(engine) as { consumer_election?: { mode: string } }).consumer_election?.mode === 'full',+ { timeoutMs: 15_000, intervalMs: 50, label: 'the opted-out sync runs its own full consumer (base branch: waiter_only behind the wedged serve)' });+ await waitFor(async () => stderr.some(line => line.includes('reason=two_consumers_on_host') && line.includes(`serve pid ${process.pid + 300_000}`)),+ { timeoutMs: 10_000, intervalMs: 50, label: 'the forced consumer names the serve beside it' });+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 2 });+ expect(result.drain?.outcome).toBe('synced');+ const rows = await imports(f.id);+ expect(rows).toHaveLength(20);+ expect(rows.every(row => row.state === 'committed' && row.owner_pid === process.pid)).toBe(true);+ } finally {+ process.stderr.write = write;+ resetOwnConsumerForTest();+ await disposePersistenceConsumer(engine);+ await wedged.stop();+ }+ }), 180_000);+test('T1b: two starters within one renewal both start full; doctor reports the persistent overlap once both are over 30 s old', async () => withEnv({ GBRAIN_HOME: home }, async () => {await engine.setConfig('persistence.single_consumer', 'true');resetWriteSwitches();diff --git a/test/e2e/pgbouncer-pipelined-read-pool.test.ts b/test/e2e/pgbouncer-pipelined-read-pool.test.tsnew file mode 100644index 0000000000..622ca854a1--- /dev/null+++ b/test/e2e/pgbouncer-pipelined-read-pool.test.ts@@ -0,0 +1,82 @@+/**+ * #6543 (A3): gbrain's read-side pools stop pipelining on a transaction-mode+ * pooler URL (`?prepare=false` or port 6543), which turns pipelining off for+ * every pooled E2E pass, because the PgBouncer lane pins `?prepare=false`.+ * PgBouncer carries pipelined statements correctly (measured: no wrong rows,+ * no cost), so this file keeps pipelined-through-a-pooler coverage: an engine+ * whose URL says `?prepare=false&max_pipeline=100` keeps the driver's+ * pipelining (the user's explicit value wins over A3's default), and+ * statements pipelined on one pooled connection, autocommit and inside a+ * transaction, each read their own rows. A twin without the override pins+ * A3's default (`max_pipeline` 0) through the same pooler.+ *+ * Runs when the CI PgBouncer fixture is configured (GBRAIN_PGBOUNCER_URL ++ * GBRAIN_PGBOUNCER_DIRECT_URL), against a database of its own.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { withEnv } from '../helpers/with-env.ts';++const pooled = process.env.GBRAIN_PGBOUNCER_URL;+const pooledAdmin = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && !(pooled && pooledAdmin)) throw new Error('The pipelined read-pool PgBouncer test requires the configured CI PgBouncer fixture.');+const database = `gbrain_test_pipelined_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;+const pooledUrl = (query: string) => { const url = new URL(pooled!); url.pathname = `/${database}`; url.search = query; return url.toString(); };++beforeAll(async () => {+ if (!(pooled && pooledAdmin)) return;+ assertSafeE2eDatabaseUrl(pooledAdmin);+ const admin = postgres(pooledAdmin, { max: 1, prepare: false, onnotice: () => {} });+ try { await admin.unsafe(`CREATE DATABASE ${database}`); } finally { await admin.end(); }+}, 60_000);++afterAll(async () => {+ if (!(pooled && pooledAdmin)) return;+ const admin = postgres(pooledAdmin, { max: 1, prepare: false, onnotice: () => {} });+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); } finally { await admin.end(); }+});++/** Statements waiting in the pool for a connection: 0 when the one connection took them all (pipelined). */+const queuedInPool = (sql: unknown): number => (sql as { pool: { queued: number } }).pool.queued;++async function withEngine<T>(query: string, run: (sql: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {+ const url = pooledUrl(query);+ assertSafeE2eDatabaseUrl(url);+ return withEnv({ PGMAX_PIPELINE: undefined, GBRAIN_PREPARE: undefined, GBRAIN_DISABLE_DIRECT_POOL: '1' }, async () => {+ const engine = new PostgresEngine();+ await engine.connect({ engine: 'postgres', database_url: url, poolSize: 1 });+ try { return await run(engine.sql); } finally { await engine.disconnect(); }+ });+}++describe.skipIf(!(pooled && pooledAdmin))('#6543 read pool pipelining through transaction-mode PgBouncer', () => {+ test('an explicit ?max_pipeline=100 keeps pipelining on, and pipelined statements each read their own rows (autocommit and in a transaction)', async () => {+ await withEngine('?prepare=false&max_pipeline=100', async sql => {+ expect((sql as unknown as { options: { max_pipeline: number } }).options.max_pipeline).toBe(100);+ // One connection (poolSize 1). With the parameter types known (the first statement described them), 40 statements+ // dispatched at once all go onto that connection, pipelined: none waits in the pool's queue.+ await sql.unsafe('SELECT $1::int AS n', [0]);+ const pending = Array.from({ length: 40 }, (_, i) => sql.unsafe('SELECT $1::int AS n', [i]).execute());+ for (let i = 0; i < 4; i++) await Promise.resolve();+ expect(queuedInPool(sql)).toBe(0);+ const autocommit = await Promise.all(pending);+ expect(autocommit.map(rows => (rows[0] as unknown as { n: number }).n)).toEqual(Array.from({ length: 40 }, (_, i) => i));+ const inTransaction = await sql.begin(async tx => Promise.all(Array.from({ length: 20 }, (_, i) => tx.unsafe('SELECT $1::text AS who', [`t${i}`]))));+ expect(inTransaction.map(rows => (rows[0] as unknown as { who: string }).who)).toEqual(Array.from({ length: 20 }, (_, i) => `t${i}`));+ });+ }, 60_000);++ test('without the override the same pooled URL reads max_pipeline 0 and still answers every statement', async () => {+ await withEngine('?prepare=false', async sql => {+ expect((sql as unknown as { options: { max_pipeline: number } }).options.max_pipeline).toBe(0);+ await sql.unsafe('SELECT $1::int AS n', [0]);+ const pending = Array.from({ length: 10 }, (_, i) => sql.unsafe('SELECT $1::int AS n', [i]).execute());+ for (let i = 0; i < 4; i++) await Promise.resolve();+ expect(queuedInPool(sql)).toBeGreaterThan(0);+ const rows = await Promise.all(pending);+ expect(rows.map(r => (r[0] as unknown as { n: number }).n)).toEqual(Array.from({ length: 10 }, (_, i) => i));+ });+ }, 60_000);+});diff --git a/test/e2e/postgres-driver-6543-postgres.test.ts b/test/e2e/postgres-driver-6543-postgres.test.tsnew file mode 100644index 0000000000..bf304155c8--- /dev/null+++ b/test/e2e/postgres-driver-6543-postgres.test.ts@@ -0,0 +1,84 @@+/**+ * #6543: three vendored-driver defects behind the managed Supabase serve wedge+ * (Supavisor transaction pooler, port 6543). Each runs against direct Postgres;+ * no pooler is needed to show the driver's half.+ *+ * 1. A socket that closed under a failed statement left its ErrorResponse+ * behind, and the replacement connection handed it to its first statement:+ * a stale `57P01` on direct Postgres, `XX000 DbHandler exited` through+ * Supavisor, so one terminated backend cost two failures.+ * 2. A statement that failed to build reported its connection ready for more,+ * so a pool built with `max_pipeline: 0` (gbrain's transaction-pooler pools)+ * still pipelined the next statement behind the Unbuildable query.+ * 3. `UNDEFINED_VALUE` did not say which parameter was undefined, so the+ * report's two build failures could not be traced to a column.+ *+ * Regression that fails it on the base driver: case 1's queued statement+ * rejects `57P01`; case 2's pool reads `{ busy: 1, full: 0, queued: 0 }`;+ * case 3's `onbuilderror` gets two arguments.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const url = process.env.DATABASE_URL;+const opened: Array<{ end: (o?: { timeout?: number }) => Promise<void> }> = [];+afterEach(async () => { while (opened.length) await opened.pop()!.end({ timeout: 1 }).catch(() => {}); });++type Settled = { rows: unknown[] } | { code: string } | { hung: true };+function settle(query: PromiseLike<unknown>, ms = 8000): Promise<Settled> {+ return Promise.race([+ Promise.resolve(query).then(rows => ({ rows: Array.from(rows as unknown[]) }), (e: { code?: string; message?: string }) => ({ code: e.code ?? e.message ?? 'error' })),+ new Promise<Settled>(resolve => setTimeout(() => resolve({ hung: true }), ms)),+ ]);+}+function pool(options: Record<string, unknown>) {+ assertSafeE2eDatabaseUrl(url!);+ const appName = `gbrain-6543-${Math.random().toString(36).slice(2)}`;+ const sql = postgres(url!, { max: 1, prepare: false, onnotice: () => {}, connection: { application_name: appName }, ...options } as Parameters<typeof postgres>[1]);+ opened.push(sql);+ return { sql, appName };+}+function admin() {+ assertSafeE2eDatabaseUrl(url!);+ const sql = postgres(url!, { max: 1, onnotice: () => {} });+ opened.push(sql);+ return sql;+}++describe.skipIf(!url)('#6543 vendored driver', () => {+ test('a terminated backend does not hand its 57P01 to the first statement of the replacement connection', async () => {+ const { sql, appName } = pool({});+ await sql`SELECT 1`;+ const head = settle(sql`SELECT pg_sleep(5), 'head' AS who`);+ // Describe-first (an untyped parameter under prepare: false): the pool routes nothing more to the connection behind it.+ const describeFirst = settle(sql`SELECT 'n1' AS who, ${1}::int AS n`);+ const queued = settle(sql`SELECT 'n2' AS who`);+ await new Promise(r => setTimeout(r, 500));+ const a = admin();+ await a`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name = ${appName}`;+ expect(await head).toEqual({ code: 'CONNECTION_CLOSED' });+ expect(await describeFirst).toEqual({ code: 'CONNECTION_CLOSED' });+ expect(await queued).toEqual({ rows: [{ who: 'n2' }] });+ }, 30_000);++ test('a statement that fails to build leaves the connection unroutable when max_pipeline forbids pipelining', async () => {+ const { sql } = pool({ max_pipeline: 0 });+ await sql`SELECT 1`;+ const culprit = settle(sql`SELECT ${undefined as unknown as string}::text AS who`);+ const next = settle(sql`SELECT 'next' AS who`);+ await Promise.resolve(); await Promise.resolve(); await Promise.resolve();+ const routed = (sql as unknown as { pool: { busy: number; full: number; queued: number } }).pool;+ expect({ busy: routed.busy, full: routed.full, queued: routed.queued }).toEqual({ busy: 0, full: 1, queued: 1 });+ expect(await culprit).toEqual({ code: 'UNDEFINED_VALUE' });+ expect(await next).toEqual({ rows: [{ who: 'next' }] });+ }, 30_000);++ test('UNDEFINED_VALUE names the parameter', async () => {+ const builds: unknown[][] = [];+ const { sql } = pool({ onbuilderror: (...args: unknown[]) => builds.push(args) });+ const r = await settle(sql`SELECT ${'a'}::text, ${undefined as unknown as string}::text`);+ expect(r).toEqual({ code: 'UNDEFINED_VALUE' });+ expect(builds).toEqual([['UNDEFINED_VALUE', 'SELECT $1::text, $2::text', 2]]);+ }, 30_000);+});diff --git a/test/e2e/serve-delegated-managed-sync.serial.test.ts b/test/e2e/serve-delegated-managed-sync.serial.test.tsindex 41ab439440..3b849aca90 100644--- a/test/e2e/serve-delegated-managed-sync.serial.test.ts+++ b/test/e2e/serve-delegated-managed-sync.serial.test.ts@@ -221,7 +221,7 @@ describeWithDb('serve-delegated managed sync on Postgres (#6317 D1 a′)', () =>const result = await runSync(['--source', 'other', '--no-pull', '--no-embed', '--json'], { GBRAIN_SOURCE: 'other' }, 120_000);// The ladder reached the serve (through the legacy URL-keyed socket), was told source_mismatch, and kept the own consumer;// what the unclaimed source does after that is the in-process path's business.- expect(result.err).toMatch(/\[sync\] the serve is bound to a different source than this sync targets.*this run uses its own consumer beside the serve \(PID \d+\)/);+ expect(result.err).toMatch(/\[sync\] the serve is bound to a different source than this sync targets.*this run does not delegate to the serve \(PID \d+\)/);expect(result.err).not.toMatch(/running the managed catch-up inside it/);}, 300_000);});diff --git a/test/exit-codes.test.ts b/test/exit-codes.test.tsindex 30f932a095..640937a064 100644--- a/test/exit-codes.test.ts+++ b/test/exit-codes.test.ts@@ -35,6 +35,7 @@ describe('exit code table', () => {expect(exitCodes.CONFIRMATION_REQUIRED_EXIT_CODE).toBe(3);expect(exitCodes.PENDING_WRITE_EXIT_CODE).toBe(10);expect(exitCodes.BUDGET_STOP_EXIT_CODE).toBe(11);+ expect(exitCodes.SERVE_UNHEALTHY_EXIT_CODE).toBe(69);expect(exitCodes.MIGRATIONS_RUNNING_EXIT_CODE).toBe(75);expect(exitCodes.TIMEOUT_EXIT_CODE).toBe(124);expect(exitCodes.INTERRUPTED_EXIT_CODE).toBe(130);@@ -50,6 +51,7 @@ describe('exit code table', () => {expect(exitCodeForCode('invalid_params')).toBe(2);expect(exitCodeForCode('unknown_flag')).toBe(2);expect(exitCodeForCode('write_pending')).toBe(10);+ expect(exitCodeForCode('serve_unhealthy_exit')).toBe(69);expect(exitCodeForCode('timeout')).toBe(124);expect(exitCodeForCode('interrupted')).toBe(130);expect(exitCodeForCode('internal_error')).toBe(1);@@ -78,7 +80,7 @@ describe('exit code table', () => {test('the exit-codes guide documents every value; the CHANGELOG carries the contract v1 exit changes', () => {const doc = readFileSync(join(ROOT, 'docs/guides/exit-codes.md'), 'utf8');- for (const v of [0, 1, 2, 3, 10, 11, 75, 124, 130]) expect(doc).toContain(`| ${v} |`);+ for (const v of [0, 1, 2, 3, 10, 11, 69, 75, 124, 130]) expect(doc).toContain(`| ${v} |`);expect(doc).toContain('CHANGELOG.md#exit-code-changes-by-command');expect(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8')).toContain('#### Exit code changes by command');});diff --git a/test/persistence-consumer-election.test.ts b/test/persistence-consumer-election.test.tsindex e9298bcf66..9ce8ff0fa0 100644--- a/test/persistence-consumer-election.test.ts+++ b/test/persistence-consumer-election.test.ts@@ -237,6 +237,19 @@ describe('WaiterOnlyConsumer mode machine', () => {expect(forced.consumer.mode).toBe('full');await forced.consumer.stop();});+ test('#6543: a forced consumer logs two_consumers_on_host once when a live serve of this host consumes beside it, and nothing when none does', async () => {+ forceOwnConsumer('opted_out');+ const beside = harness({ kind: 'sync', rows: () => [row({ kind: 'serve', pid: 4242 })] });+ beside.consumer.start();+ await beside.consumer.stop();+ expect(beside.consumer.mode).toBe('full');+ expect(beside.logs.filter(line => line.includes('reason=two_consumers_on_host'))).toEqual([+ 'phase=consumer_probe reason=two_consumers_on_host message="this sync process consumes beside serve pid 4242 on this host (forced:opted_out); both claim writes until one exits"']);+ const alone = harness({ kind: 'sync', rows: () => [row({ kind: 'serve', renewed_age_ms: CONSUMER_LAPSED_MS + 1 }), row({ kind: 'jobs', pid: 7 })] });+ alone.consumer.start();+ await alone.consumer.stop();+ expect(alone.logs.filter(line => line.includes('two_consumers_on_host'))).toEqual([]);+ });test('promote() turns a waiter into a full consumer in place', async () => {const h = harness({ rows: () => [row()] });h.consumer.start();diff --git a/test/pool-health-6383.test.ts b/test/pool-health-6383.test.tsindex b06e9c1fbc..b03d2b0261 100644--- a/test/pool-health-6383.test.ts+++ b/test/pool-health-6383.test.ts@@ -76,6 +76,20 @@ describe('warn lines', () => {expect(formatBuildFailureWarning('read', 'weird code', 'SELECT 1')).toContain('error=BUILD_FAILED');});+ test('#6543: an UNDEFINED_VALUE line names the parameter, `param=?` when the driver gave none (an array element)', () => {+ expect(formatBuildFailureWarning('read', 'UNDEFINED_VALUE', 'SELECT * FROM source_ingestion_receipts WHERE a = $1 AND b = $2', 2))+ .toContain('error=UNDEFINED_VALUE pool=read sql=SELECT_source_ingestion_receipts param=$2 cause=');+ expect(formatBuildFailureWarning('read', 'UNDEFINED_VALUE', 'SELECT $1')).toContain('sql=SELECT param=? cause=');+ expect(formatBuildFailureWarning('read', 'MAX_PARAMETERS_EXCEEDED', 'SELECT $1', 3)).not.toContain('param=');+ const counter = new PoolIncidentCounter();+ const warn = console.warn;+ const lines: string[] = [];+ console.warn = (line: string) => { lines.push(line); };+ try { counter.hooks('direct').onbuilderror('UNDEFINED_VALUE', 'UPDATE persistence_effects SET state = $1 WHERE id = $2', 2); } finally { console.warn = warn; }+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('sql=UPDATE_persistence_effects param=$2');+ });+test('pg_connection_desync names the message type, the connection and the last statement by keyword and table only', () => {const line = formatDesyncWarning('read', { message: 'C', connection: 7, statement: "SELECT enabled FROM persistence_brain WHERE singleton = 1 AND note = 'secret'" });expect(line).toContain('[gbrain] warn code=pg_connection_desync pool=read message=C connection=7 sql=SELECT_persistence_brain');diff --git a/test/postgres-driver-startup-death.test.ts b/test/postgres-driver-startup-death.test.tsindex c7e11b3b3f..1bf1ead843 100644--- a/test/postgres-driver-startup-death.test.ts+++ b/test/postgres-driver-startup-death.test.ts@@ -54,19 +54,21 @@ const fatalTerminated = frame('E', Buffer.concat([Buffer.from('M'), cstr('terminating connection due to administrator command'), Buffer.from([0]),]));+type Script = { kill?: boolean; killAt?: number };/*** Answers the extended protocol with empty results (ParseComplete, BindComplete, NoData, CommandComplete, ReadyForQuery)- * and a simple Query with CommandComplete. `kill` ends the connection with FATAL 57P01 at its first statement.+ * and a simple Query with CommandComplete. `kill` ends the connection with FATAL 57P01 at its first statement, `killAt`+ * at its n-th (1-based).*/-function serve(socket: Socket, buffered: Buffer, mode: { kill?: boolean }, onStatement: () => void): Buffer {+function serve(socket: Socket, buffered: Buffer, mode: Script, onStatement: () => number): Buffer {let rest: Buffer = buffered;for (;;) {if (rest.length < 5) return rest;const type = String.fromCharCode(rest[0]!), length = rest.readInt32BE(1);if (rest.length < length + 1) return rest;rest = rest.subarray(length + 1);- if (type === 'P' || type === 'Q') onStatement();- if (mode.kill) { socket.write(fatalTerminated); socket.end(); return Buffer.alloc(0); }+ const statement = type === 'P' || type === 'Q' ? onStatement() : 0;+ if (mode.kill || (statement > 0 && statement === mode.killAt)) { socket.write(fatalTerminated); socket.end(); return Buffer.alloc(0); }if (type === 'P') socket.write(frame('1'));else if (type === 'B') socket.write(frame('2'));else if (type === 'D') socket.write(frame('n'));@@ -81,7 +83,7 @@ let server: Server | undefined;afterEach(() => new Promise<void>(resolve => { server ? server.close(() => resolve()) : resolve(); server = undefined; }));/** A scripted server; `script(n)` chooses how the n-th connection (1-based) behaves. */-async function listen(script: (connection: number) => { kill?: boolean }): Promise<{ port: number; connections: { statements: number }[] }> {+async function listen(script: (connection: number) => Script): Promise<{ port: number; connections: { statements: number }[] }> {const connections: { statements: number }[] = [];server = createServer(socket => {const connection = { statements: 0 };@@ -97,18 +99,18 @@ async function listen(script: (connection: number) => { kill?: boolean }): Promibuffered = buffered.subarray(length); started = true;socket.write(startupReply);}- buffered = serve(socket, buffered, mode, () => { connection.statements++; });+ buffered = serve(socket, buffered, mode, () => ++connection.statements);});socket.on('error', () => undefined);});await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', () => resolve()));return { port: (server.address() as { port: number }).port, connections };}-function client(port: number): { sql: ReturnType<typeof postgres>; socket: () => ScriptedSocket } {+function client(port: number, extra: Record<string, unknown> = {}): { sql: ReturnType<typeof postgres>; socket: () => ScriptedSocket } {let current: ScriptedSocket | undefined;// A socket option hands the driver a connecting socket (the driver then skips its own connect step); the option is not in the public types.const options = { host: '127.0.0.1', port, user: 'u', password: 'p', database: 'd', ssl: false, max: 1, prepare: false, fetch_types: true, connect_timeout: 2, onnotice() {},- socket: () => (current = new ScriptedSocket()).connect(port, '127.0.0.1') };+ socket: () => (current = new ScriptedSocket()).connect(port, '127.0.0.1'), ...extra };const sql = postgres(options as unknown as Parameters<typeof postgres>[0]);return { sql, socket: () => current! };}@@ -155,3 +157,21 @@ test('forced probe: a close delivered while a statement\'s bytes wait for the wrexpect(connections[1]!.statements).toBeGreaterThanOrEqual(2);} finally { await sql.end({ timeout: 1 }); }}, 15_000);++test('forced probe (#6543): a backend terminated under a running statement does not hand its 57P01 to the first statement of the replacement connection', async () => {+ // The serve wedge's `recovery_scan reason=57P01`: a FATAL that arrived before the close stayed in the connection's+ // state, and the reconnect's startup ReadyForQuery delivered it to the statement the pool had queued for the slot.+ // `max_pipeline: 0` keeps that statement in the pool's queue, so it is written only on the replacement connection.+ const { port, connections } = await listen(connection => (connection === 1 ? { killAt: 2 } : {}));+ const { sql } = client(port, { fetch_types: false, max_pipeline: 0 });+ const settled = (query: PromiseLike<unknown>) => Promise.resolve(query).then(rows => ({ rows: [...rows as unknown[]] }), (error: { code?: string }) => ({ code: error.code }));+ try {+ expect([...await sql.unsafe('select 1')]).toEqual([]);+ const head = settled(sql.unsafe('select 2'));+ const queued = settled(sql.unsafe('select 3'));+ expect(await head).toEqual({ code: 'CONNECTION_CLOSED' });+ expect(await queued).toEqual({ rows: [] });+ expect(connections.length).toBe(2);+ expect(connections[1]!.statements).toBe(1);+ } finally { await sql.end({ timeout: 1 }); }+}, 15_000);diff --git a/test/postgres-driver-vendor.test.ts b/test/postgres-driver-vendor.test.tsindex 636488561d..55934c8f14 100644--- a/test/postgres-driver-vendor.test.ts+++ b/test/postgres-driver-vendor.test.ts@@ -42,4 +42,23 @@ describe('vendored Postgres driver packaging', () => {expect(connection).toContain('function answersStatement(xs, x)');}});++ test('#6543: all three shipped copies carry the A1 close reset, the A2 build-failure pipelining gate and the A7 parameter index (offline; update-postgres.sh --check is the networked proof)', () => {+ for (const path of ['src', 'cjs/src', 'cf/src']) {+ const connection = readFileSync(new URL(`../vendor/postgres/${path}/connection.js`, import.meta.url), 'utf8');+ // A1: a closed socket's ErrorResponse and partial result never reach the replacement connection's first statement.+ expect(connection).toContain('query = errorResponse = results = null');+ expect(connection).toContain('result = new Result()');+ // A2: a build failure obeys max_pipeline and onexecute (stock: `write(Unbuildable)` then `return true`); onexecute runs only after build.+ expect(connection).toContain('let mayPipeline = !q.options.onexecute');+ expect(connection).toMatch(/build\(q\)\n\s+mayPipeline = mayPipeline \|\| q\.options\.onexecute\(connection\)/);+ expect(connection).toMatch(/return write\(Unbuildable\)\n\s+&& sent\.length < max_pipeline\n\s+&& mayPipeline/);+ expect(connection).not.toMatch(/write\(Unbuildable\)\n\s+return true/);+ // A7: onbuilderror names the undefined parameter.+ expect(connection).toContain("statementText(q), error && error.parameter)");+ const types = readFileSync(new URL(`../vendor/postgres/${path}/types.js`, import.meta.url), 'utf8');+ expect(types).toContain('(parameter $');+ }+ expect(readFileSync(new URL('../vendor/postgres/types/index.d.ts', import.meta.url), 'utf8')).toContain('parameter?: number');+ });});diff --git a/test/read-pool-pipeline-6543.test.ts b/test/read-pool-pipeline-6543.test.tsnew file mode 100644index 0000000000..fd5b66af96--- /dev/null+++ b/test/read-pool-pipeline-6543.test.ts@@ -0,0 +1,152 @@+/**+ * #6543 (A3): a read-side pool whose URL is a transaction-mode pooler does not+ * pipeline. Through Supavisor's transaction mode, statements pipelined on one+ * client connection crossed transaction boundaries: they hung until the+ * in-flight watchdog fired, or came back with another statement's rows.+ *+ * `resolveReadPoolPipeline(url)` decides it once for the three read-side+ * construction sites (the module singleton in db.ts, an engine's instance pool,+ * the connection manager's read pool) and names the reason: `0` for a+ * transaction-mode URL (port 6543 or `?prepare=false`, read from the URL even+ * when `GBRAIN_PREPARE=1`) or `GBRAIN_PREPARE=0`; unset (the driver's default+ * 100) otherwise, a session-mode pooler included; and unset when the user set+ * `?max_pipeline=` or a non-empty `PGMAX_PIPELINE`, because the driver lets the+ * options object outrank both.+ *+ * Regression that fails it on the base branch: every case reads the driver's+ * default 100, because no site set `max_pipeline`.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { createServer, type Server, type Socket } from 'node:net';+import postgres from '#postgres';+import { connect as connectModule, disconnect as disconnectModule, getConnection, readPoolPipelineOptions, resolveReadPoolPipeline, type ReadPoolPipelineReason } from '../src/core/db.ts';+import { ConnectionManager } from '../src/core/connection-manager.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { withEnv } from './helpers/with-env.ts';++const NO_OVERRIDES = { PGMAX_PIPELINE: undefined, GBRAIN_PREPARE: undefined, GBRAIN_DIRECT_DATABASE_URL: undefined, GBRAIN_DISABLE_DIRECT_POOL: undefined, GBRAIN_SQL_TRACE: undefined };+const POOLER_HOST = 'aws-0-us-east-1.pooler.supabase.com';++/** URL, extra env, the option the helper returns, its reason, the max_pipeline the driver ends up with. */+const MATRIX: Array<{ name: string; url: string; env?: Record<string, string>; option: { max_pipeline?: number }; reason: ReadPoolPipelineReason; effective: number }> = [+ { name: 'direct :5432', url: 'postgresql://u:[email protected]:5432/d', option: {}, reason: 'default', effective: 100 },+ { name: 'transaction pooler port :6543', url: 'postgresql://u:[email protected]:6543/d', option: { max_pipeline: 0 }, reason: 'transaction_pooler_port', effective: 0 },+ { name: '?prepare=false', url: 'postgresql://u:[email protected]:5432/d?prepare=false', option: { max_pipeline: 0 }, reason: 'url_prepare_false', effective: 0 },+ { name: 'GBRAIN_PREPARE=0', url: 'postgresql://u:[email protected]:5432/d', env: { GBRAIN_PREPARE: '0' }, option: { max_pipeline: 0 }, reason: 'gbrain_prepare_off', effective: 0 },+ { name: 'Supabase transaction pooler :6543 with GBRAIN_PREPARE=1', url: `postgresql://postgres.ref:p@${POOLER_HOST}:6543/postgres`, env: { GBRAIN_PREPARE: '1' }, option: { max_pipeline: 0 }, reason: 'transaction_pooler_port', effective: 0 },+ { name: ':6543 with ?prepare=true', url: 'postgresql://u:[email protected]:6543/d?prepare=true', option: { max_pipeline: 0 }, reason: 'transaction_pooler_port', effective: 0 },+ { name: 'Supabase session pooler :5432', url: `postgresql://postgres.ref:p@${POOLER_HOST}:5432/postgres`, option: {}, reason: 'default', effective: 100 },+ { name: ':6543 with ?max_pipeline=5', url: 'postgresql://u:[email protected]:6543/d?max_pipeline=5', option: {}, reason: 'url_max_pipeline', effective: 5 },+ { name: ':6543 with PGMAX_PIPELINE=5', url: 'postgresql://u:[email protected]:6543/d', env: { PGMAX_PIPELINE: '5' }, option: {}, reason: 'env_pgmax_pipeline', effective: 5 },+ { name: 'direct :5432 with PGMAX_PIPELINE=5', url: 'postgresql://u:[email protected]:5432/d', env: { PGMAX_PIPELINE: '5' }, option: {}, reason: 'env_pgmax_pipeline', effective: 5 },+ { name: '?prepare=false with GBRAIN_PREPARE=1', url: 'postgresql://u:[email protected]:5432/d?prepare=false', env: { GBRAIN_PREPARE: '1' }, option: { max_pipeline: 0 }, reason: 'url_prepare_false', effective: 0 },+ { name: ':6543 with an empty PGMAX_PIPELINE', url: 'postgresql://u:[email protected]:6543/d', env: { PGMAX_PIPELINE: '' }, option: { max_pipeline: 0 }, reason: 'transaction_pooler_port', effective: 0 },+ { name: 'direct :5432 with an empty PGMAX_PIPELINE', url: 'postgresql://u:[email protected]:5432/d', env: { PGMAX_PIPELINE: '' }, option: {}, reason: 'default', effective: 100 },+];++const opened: Array<{ end: (o?: { timeout?: number }) => Promise<void> }> = [];+let server: Server | undefined;+afterEach(async () => {+ while (opened.length) await opened.pop()!.end({ timeout: 1 }).catch(() => {});+ await new Promise<void>(resolve => { server ? server.close(() => resolve()) : resolve(); server = undefined; });+});+const effective = (pool: unknown): number => (pool as { options: { max_pipeline: number } }).options.max_pipeline;++describe('resolveReadPoolPipeline', () => {+ for (const c of MATRIX) {+ test(`${c.name}: ${JSON.stringify(c.option)} (${c.reason}), driver max_pipeline ${c.effective}`, async () => withEnv({ ...NO_OVERRIDES, ...c.env }, async () => {+ expect(resolveReadPoolPipeline(c.url)).toEqual({ value: c.option.max_pipeline ?? null, reason: c.reason });+ expect(readPoolPipelineOptions(c.url)).toEqual(c.option);+ const pool = postgres(c.url, { ...readPoolPipelineOptions(c.url) } as Parameters<typeof postgres>[1]);+ opened.push(pool);+ expect(effective(pool)).toBe(c.effective);+ }));+ }+});++describe('connection manager read pool', () => {+ for (const c of MATRIX) {+ test(`${c.name}: max_pipeline ${c.effective}`, async () => withEnv({ ...NO_OVERRIDES, GBRAIN_DISABLE_DIRECT_POOL: '1', ...c.env }, async () => {+ // getReadPool builds the pool without connecting, so an unreachable host is fine here.+ const pool = await new ConnectionManager({ url: c.url }).getReadPool();+ opened.push(pool);+ expect(effective(pool)).toBe(c.effective);+ }));+ }+});++/**+ * The module singleton and the instance pool connect at once, so they run against a scripted server that answers the+ * extended protocol with empty results; the URL cases are those a loopback address can carry.+ */+const frame = (type: string, body: Buffer = Buffer.alloc(0)): Buffer => {+ const header = Buffer.alloc(5);+ header.write(type, 0, 'ascii'); header.writeInt32BE(body.length + 4, 1);+ return Buffer.concat([header, body]);+};+const cstr = (s: string): Buffer => Buffer.from(`${s}\0`, 'utf8');+const readyForQuery = frame('Z', Buffer.from('I'));+const startupReply = Buffer.concat([+ frame('R', Buffer.from([0, 0, 0, 0])),+ frame('S', Buffer.concat([cstr('server_version'), cstr('16.0')])),+ frame('K', Buffer.from([0, 0, 0, 7, 0, 0, 0, 9])),+ readyForQuery,+]);+function answer(socket: Socket, buffered: Buffer): Buffer {+ let rest = buffered;+ while (rest.length >= 5) {+ const type = String.fromCharCode(rest[0]!), length = rest.readInt32BE(1);+ if (rest.length < length + 1) break;+ rest = rest.subarray(length + 1);+ if (type === 'P') socket.write(frame('1'));+ else if (type === 'B') socket.write(frame('2'));+ else if (type === 'D') socket.write(frame('n'));+ else if (type === 'E') socket.write(frame('C', cstr('SELECT 0')));+ else if (type === 'S') socket.write(readyForQuery);+ else if (type === 'Q') socket.write(Buffer.concat([frame('C', cstr('SELECT 0')), readyForQuery]));+ else if (type === 'X') socket.end();+ }+ return rest;+}+async function scriptedServer(): Promise<number> {+ server = createServer(socket => {+ let buffered: Buffer = Buffer.alloc(0), started = false;+ socket.on('data', (chunk: Buffer) => {+ buffered = Buffer.concat([buffered, chunk]);+ if (!started) {+ if (buffered.length < 8 || buffered.length < buffered.readInt32BE(0)) return;+ buffered = buffered.subarray(buffered.readInt32BE(0)); started = true;+ socket.write(startupReply);+ }+ buffered = answer(socket, buffered);+ });+ socket.on('error', () => undefined);+ });+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', () => resolve()));+ return (server.address() as { port: number }).port;+}+const LOOPBACK: Array<{ name: string; query: string; env?: Record<string, string>; effective: number }> = [+ { name: 'direct', query: '', effective: 100 },+ { name: '?prepare=false', query: '?prepare=false', effective: 0 },+ { name: 'GBRAIN_PREPARE=0', query: '', env: { GBRAIN_PREPARE: '0' }, effective: 0 },+ { name: '?prepare=false&max_pipeline=5', query: '?prepare=false&max_pipeline=5', effective: 5 },+ { name: 'GBRAIN_PREPARE=0 with PGMAX_PIPELINE=5', query: '', env: { GBRAIN_PREPARE: '0', PGMAX_PIPELINE: '5' }, effective: 5 },+];++describe('module singleton and instance pool', () => {+ for (const c of LOOPBACK) {+ test(`${c.name}: max_pipeline ${c.effective} on both`, async () => withEnv({ ...NO_OVERRIDES, GBRAIN_DISABLE_DIRECT_POOL: '1', ...c.env }, async () => {+ const port = await scriptedServer();+ const url = `postgresql://u:[email protected]:${port}/d${c.query}`;+ const engine = new PostgresEngine();+ await engine.connect({ engine: 'postgres', database_url: url, poolSize: 2 });+ try { expect(effective(engine.sql)).toBe(c.effective); } finally { await engine.disconnect(); }+ const warn = console.warn;+ console.warn = () => {};+ try {+ await connectModule({ engine: 'postgres', database_url: url });+ expect(effective(getConnection())).toBe(c.effective);+ } finally { console.warn = warn; await disconnectModule(); }+ }), 15_000);+ }+});diff --git a/test/serve-health-6543.test.ts b/test/serve-health-6543.test.tsnew file mode 100644index 0000000000..5c8f4d70a2--- /dev/null+++ b/test/serve-health-6543.test.ts@@ -0,0 +1,289 @@+/**+ * #6543 (A5r, A5x): `/health?deep=1` names why serve is unhealthy and what its+ * transport is, and the opt-in exit lets a supervisor restart a wedged serve.+ *+ * Protects: a real persistence consumer driven to restart_required (an+ * abandoned preparation past the ceiling) makes the deep probe answer 503+ * `persistence_restart_required` before it runs its SELECT 1, with no request+ * id in the unauthenticated body (it answered 200 before: the probe only read+ * the pool); every 503 carries a stable `code`, `fix` and `docs`; the+ * transport block reports the live pool's prepare and max_pipeline with the+ * reason, the startup statement_timeout, `session_timeouts_not_applied` with+ * the doctor probe's ALTER ROLE fix whenever a configured timeout reads 0+ * (whatever the env URL says), and a Supavisor application_name;+ * `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` refuses values under 120, is off when+ * unset, exits 69 only after restart_required has held continuously for the+ * window (the hold restarts when the flag clears, as it does when the stuck+ * work settles), never exits on a statement past the in-flight budget, and+ * exits even when cleanup never finishes.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { admitWrite } from '../src/core/persistence/journal.ts';+import { cancelWriteRequest } from '../src/core/persistence/control.ts';+import { driverPoolStats } from '../src/core/postgres-engine/pool-stats.ts';+import { probeDeepHealth } from '../src/commands/serve-http-metrics.ts';+import { formatServeTransportLine, installRestartRequiredExit, readServeTransport, recordServeTransport, resolveRestartRequiredExitSeconds, selfExitSuppressed, serveTransport } from '../src/commands/serve-health.ts';+import { readFileSync, writeFileSync } from 'node:fs';+import { SERVE_UNHEALTHY_EXIT_CODE } from '../src/core/exit-codes.ts';+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';+import { withEnv } from './helpers/with-env.ts';+import { waitFor } from './helpers/wait-for.ts';++interface FakeState { oldest?: number; applied?: string; appName?: string; prepare?: boolean; maxPipeline?: number; url?: string; executeRaw?: () => Promise<unknown>; disconnect?: () => Promise<void> }+function fakeEngine(state: FakeState = {}) {+ const probes: string[] = [];+ const engine = {+ kind: 'postgres',+ _savedConfig: state.url ? { database_url: state.url } : undefined,+ sql: { options: { prepare: state.prepare ?? true, max_pipeline: state.maxPipeline ?? 100 } },+ executeRaw: (sql: string) => {+ probes.push(sql);+ if (state.executeRaw) return state.executeRaw();+ if (sql === 'SHOW statement_timeout') return Promise.resolve([{ statement_timeout: state.applied ?? '5min' }]);+ if (sql === 'SHOW application_name') return Promise.resolve([{ application_name: state.appName ?? 'gbrain' }]);+ return Promise.resolve([{ '?column?': 1 }]);+ },+ disconnect: state.disconnect ?? (() => Promise.resolve()),+ getPoolDiagnostics: () => ({+ poisonedDiscards: 0, stuckDiscards: 0, buildFailures: 0, desyncDiscards: 0,+ pool: driverPoolStats({ pool: { max: 4, open: 3, busy: 1, full: 0, reserved: 0, connecting: 0, closed: 0, ended: 0, queued: 0, inflight_oldest_ms: state.oldest ?? 0, completed: 1 } }),+ }),+ } as unknown as BrainEngine;+ return { engine, probes };+}+const healthy = () => ({ restart_required: false });+const ledgerDir = mkdtempSync(join(tmpdir(), 'gbrain-serve-self-exit-'));+const ledger = (name: string) => join(ledgerDir, `${name}-${randomUUID().slice(0, 8)}.json`);+afterAll(() => rmSync(ledgerDir, { recursive: true, force: true }));+const ENV = { GBRAIN_STATEMENT_TIMEOUT: undefined, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, PGMAX_PIPELINE: undefined, GBRAIN_PREPARE: undefined };++describe('a real consumer at restart_required', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-serve-health-6543-'));+ const config: HarnessConfig = {+ kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),+ seed: 6543, schedules: 0, operations: 0, sourceIds: ['serve-health'], principalIds: [randomUUID()],+ };+ const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };+ let engine: PGLiteEngine;+ beforeAll(async () => withEnv(env, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+ }), 120_000);+ afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++ test('deep health answers 503 persistence_restart_required before its probe, without the request id; the exit fires after a continuous hold and resets when the zombie settles', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const stuck = await admitWrite(engine, admission(config, sources[0]!, 'health/stuck', 'stuck body'));+ const never = Promise.withResolvers<ReturnType<typeof prepared>>();+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => never.promise,+ { hostId: config.hostId, pollMs: 20, preparationMs: 30, preparationBudgets: { maxAttempts: 3, ceilingMs: 200 }, onError: () => {} });+ const status = () => consumer.status();+ const { engine: served, probes } = fakeEngine();+ try {+ consumer.start();+ await waitFor(() => consumer.restartRequired(), { timeoutMs: 5_000, label: 'the abandoned preparation passes the ceiling' });++ const result = await probeDeepHealth(served, 'postgres', '1.2.3', 100, 330_000, status);+ if (result.ok) throw new Error('expected 503');+ expect(result.body).toMatchObject({ code: 'persistence_restart_required', docs: 'docs/ENGINES.md#serve-deep-health' });+ expect(result.body.fix).toContain('GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS');+ expect(probes).toEqual([]);+ expect(JSON.stringify(result.body)).not.toContain(stuck.request_id);+ expect(JSON.stringify(result.body)).not.toContain(stuck.id);++ let now = 0;+ const fired: number[] = [];+ const firing = installRestartRequiredExit(served, 120, { ledgerPath: ledger('real'), now: () => now, consumerStatus: status, exit: code => fired.push(code), log: () => {}, everyMs: 3_600_000 });+ try {+ firing.check(); now = 120_000; firing.check();+ await waitFor(() => fired.length > 0, { timeoutMs: 2_000, label: 'the held restart_required exits' });+ expect(fired).toEqual([SERVE_UNHEALTHY_EXIT_CODE]);+ } finally { firing.stop(); }++ now = 0;+ const exits: number[] = [];+ const watch = installRestartRequiredExit(served, 120, { ledgerPath: ledger('real'), now: () => now, consumerStatus: status, exit: code => exits.push(code), log: () => {}, everyMs: 3_600_000 });+ try {+ watch.check();+ now = 100_000; watch.check();+ never.resolve(prepared(stuck, sources));+ await waitFor(() => !consumer.restartRequired(), { timeoutMs: 5_000, label: 'the zombie settles and restart_required clears' });+ now = 130_000; watch.check();+ expect(exits).toEqual([]);+ expect((await probeDeepHealth(served, 'postgres', '1.2.3', 100, 330_000, status)).status).toBe(200);+ } finally { watch.stop(); }+ } finally {+ never.resolve(prepared(stuck, sources));+ await consumer.stop();+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0]! }, stuck.request_id).catch(() => {});+ }+ }), 30_000);+});++describe('/health?deep=1 codes', () => {+ test('503 pool_inflight_over_budget names the restart and PGMAX_PIPELINE=0 in its fix', async () => {+ const result = await probeDeepHealth(fakeEngine({ oldest: 400_000 }).engine, 'postgres', '1.2.3', 100, 330_000, healthy);+ if (result.ok) throw new Error('expected 503');+ expect(result.body.code).toBe('pool_inflight_over_budget');+ expect(result.body.fix).toContain('Restart this gbrain serve');+ expect(result.body.fix).toContain('PGMAX_PIPELINE=0');+ expect(result.body.fix).toContain('transport');+ });++ test('a probe that times out or fails carries deep_health_probe_failed with its reason', async () => {+ const timedOut = await probeDeepHealth(fakeEngine({ executeRaw: () => new Promise(() => {}) }).engine, 'postgres', '1.2.3', 20, 330_000, healthy);+ if (timedOut.ok) throw new Error('expected 503');+ expect(timedOut.body).toMatchObject({ code: 'deep_health_probe_failed', reason: 'timeout' });+ const failed = await probeDeepHealth(fakeEngine({ executeRaw: () => Promise.reject(new Error('boom')) }).engine, 'postgres', '1.2.3', 100, 330_000, healthy);+ if (failed.ok) throw new Error('expected 503');+ expect(failed.body).toMatchObject({ code: 'deep_health_probe_failed', reason: 'error' });+ });++ test('a healthy serve answers 200 with a null transport until startup recorded one; with no consumer running it is healthy too', async () => {+ const result = await probeDeepHealth(fakeEngine().engine, 'postgres', '1.2.3', 100, 330_000, healthy);+ expect(result.status).toBe(200);+ if (result.ok) expect(result.body.transport).toBeNull();+ expect((await probeDeepHealth(fakeEngine().engine, 'postgres', '1.2.3', 100, 330_000)).status).toBe(200);+ });+});++describe('transport block', () => {+ test('a configured timeout that reads 0: session_timeouts_not_applied with the ALTER ROLE fix, the live pool options and their reason, Supavisor named', async () => withEnv(ENV, async () => {+ const { engine } = fakeEngine({ applied: '0', prepare: false, maxPipeline: 0, appName: 'Supavisor', url: 'postgresql://u:[email protected]:6543/d' });+ expect(await readServeTransport(engine)).toEqual({ pooler_mode: 'transaction', prepare: false, max_pipeline: 0, max_pipeline_reason: 'transaction_pooler_port',+ statement_timeout: '0', session_timeouts_not_applied: true, fix: "ALTER ROLE <gbrain role> SET statement_timeout = '5min'", application_name: 'Supavisor' });+ const lines: string[] = [];+ await recordServeTransport(engine, line => lines.push(line));+ expect(lines).toEqual([formatServeTransportLine(serveTransport(engine)!)]);+ expect(lines[0]).toContain('transport pooler_mode=transaction prepare=false max_pipeline=0 max_pipeline_reason=transaction_pooler_port statement_timeout=0 application_name=Supavisor session_timeouts_not_applied=true');+ expect(lines[0]).toContain("ALTER ROLE <gbrain role> SET statement_timeout = '5min'");+ const result = await probeDeepHealth(engine, 'postgres', '1.2.3', 100, 330_000, healthy);+ if (!result.ok) throw new Error('expected 200');+ expect(result.body.transport).toMatchObject({ max_pipeline: 0, session_timeouts_not_applied: true });+ }));++ test('the live pool wins over the URL: a 0 reading flags the timeout even with no pooler URL in the environment, and the pool reports what it really runs', async () => withEnv(ENV, async () => {+ const transport = await readServeTransport(fakeEngine({ applied: '0', prepare: true, maxPipeline: 7, url: 'postgresql://u:[email protected]:5432/d?max_pipeline=7' }).engine);+ expect(transport).toMatchObject({ pooler_mode: 'session_or_direct', prepare: true, max_pipeline: 7, max_pipeline_reason: 'url_max_pipeline', session_timeouts_not_applied: true });+ }));++ test('a direct server that applies the timeout reports it and no flag', async () => withEnv(ENV, async () => {+ const transport = await readServeTransport(fakeEngine({ applied: '5min', url: 'postgresql://u:[email protected]:5432/d' }).engine);+ expect(transport).toEqual({ pooler_mode: 'session_or_direct', prepare: true, max_pipeline: 100, max_pipeline_reason: 'default', statement_timeout: '5min', session_timeouts_not_applied: false });+ expect(formatServeTransportLine(transport)).toBe('[gbrain serve] transport pooler_mode=session_or_direct prepare=true max_pipeline=100 max_pipeline_reason=default statement_timeout=5min');+ }));+});++describe('GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS', () => {+ test('unset, empty or 0 is off; 120 and up is accepted; anything else is refused with invalid_params', () => {+ expect(resolveRestartRequiredExitSeconds(undefined)).toBeNull();+ expect(resolveRestartRequiredExitSeconds('')).toBeNull();+ expect(resolveRestartRequiredExitSeconds('0')).toBeNull();+ expect(resolveRestartRequiredExitSeconds('120')).toBe(120);+ expect(resolveRestartRequiredExitSeconds(' 600 ')).toBe(600);+ for (const bad of ['119', '30', '-5', 'abc', '1.5e3']) {+ expect(() => resolveRestartRequiredExitSeconds(bad)).toThrow(expect.objectContaining({ code: 'invalid_params' }));+ }+ expect(() => resolveRestartRequiredExitSeconds('60')).toThrow(/at least 120/);+ });++ test('exits 69 once restart_required has held continuously for the window; a clear restarts the hold; cleanup runs first', async () => {+ let now = 0;+ let restart = true;+ const exits: number[] = [];+ const lines: string[] = [];+ let disconnected = 0;+ const { engine } = fakeEngine({ disconnect: async () => { disconnected++; } });+ const watch = installRestartRequiredExit(engine, 120, { ledgerPath: ledger('fake'), now: () => now, consumerStatus: () => ({ restart_required: restart }), exit: code => exits.push(code), log: line => lines.push(line), everyMs: 3_600_000 });+ try {+ watch.check();+ now = 60_000; watch.check();+ restart = false; now = 90_000; watch.check();+ restart = true; now = 100_000; watch.check();+ now = 219_000; watch.check();+ expect(exits).toEqual([]);+ now = 220_000; watch.check();+ await waitFor(() => exits.length > 0, { timeoutMs: 2_000 });+ expect(exits).toEqual([SERVE_UNHEALTHY_EXIT_CODE]);+ expect(SERVE_UNHEALTHY_EXIT_CODE).toBe(69);+ expect(disconnected).toBe(1);+ expect(lines[0]).toContain('code=serve_unhealthy_exit cause=persistence_restart_required held_s=120 exit=69');+ now = 400_000; watch.check();+ expect(exits).toHaveLength(1);+ } finally { watch.stop(); }+ });++ test('cleanup that never finishes (a consumer stop waiting on the stuck work) still exits 69 at the cleanup deadline, once', async () => {+ let now = 0;+ const exits: number[] = [];+ const lines: string[] = [];+ const { engine } = fakeEngine({ disconnect: () => new Promise<void>(() => {}) });+ const watch = installRestartRequiredExit(engine, 120, { ledgerPath: ledger('fake'), now: () => now, consumerStatus: () => ({ restart_required: true }), exit: code => exits.push(code), log: line => lines.push(line), everyMs: 3_600_000, cleanupDeadlineMs: 30 });+ try {+ watch.check(); now = 120_000; watch.check();+ expect(exits).toEqual([]);+ await waitFor(() => exits.length > 0, { timeoutMs: 2_000, label: 'the cleanup deadline forces the exit' });+ expect(exits).toEqual([SERVE_UNHEALTHY_EXIT_CODE]);+ expect(lines.some(line => line.includes('cleanup deadline (30 ms) exceeded'))).toBe(true);+ await Bun.sleep(50);+ expect(exits).toHaveLength(1);+ } finally { watch.stop(); }+ });++ test('loop guard: each exit is recorded durably; with 3 self-exits in the last hour serve logs serve_self_exit_suppressed, keeps serving and deep health reports it; a clear lifts it', async () => {+ const path = ledger('guard');+ const wall = Date.parse('2026-10-12T12:00:00.000Z');+ const minutesAgo = (m: number) => new Date(wall - m * 60_000).toISOString();+ writeFileSync(path, JSON.stringify({ exits: [minutesAgo(90), minutesAgo(40), minutesAgo(20)] }));+ let now = 0;+ let restart = true;+ const exits: number[] = [];+ const { engine } = fakeEngine();+ const first = installRestartRequiredExit(engine, 120, { ledgerPath: path, wallNow: () => wall, now: () => now, consumerStatus: () => ({ restart_required: restart }), exit: code => exits.push(code), log: () => {}, everyMs: 3_600_000 });+ try {+ first.check(); now = 120_000; first.check();+ await waitFor(() => exits.length > 0, { timeoutMs: 2_000 });+ expect(exits).toEqual([SERVE_UNHEALTHY_EXIT_CODE]);+ } finally { first.stop(); }+ // The 90-minute-old exit aged out; this one was added: 3 within the hour now.+ expect((JSON.parse(readFileSync(path, 'utf8')) as { exits: string[] }).exits).toEqual([minutesAgo(40), minutesAgo(20), new Date(wall).toISOString()]);++ const lines: string[] = [];+ const exits2: number[] = [];+ const { engine: next } = fakeEngine();+ now = 0;+ const second = installRestartRequiredExit(next, 120, { ledgerPath: path, wallNow: () => wall + 60_000, now: () => now, consumerStatus: () => ({ restart_required: restart }), exit: code => exits2.push(code), log: line => lines.push(line), everyMs: 3_600_000 });+ try {+ second.check(); now = 120_000; second.check(); now = 240_000; second.check();+ await Bun.sleep(20);+ expect(exits2).toEqual([]);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('code=serve_self_exit_suppressed cause=persistence_restart_required self_exits_last_hour=3');+ expect(selfExitSuppressed(next)).toBe(true);+ const result = await probeDeepHealth(next, 'postgres', '1.2.3', 100, 330_000, () => ({ restart_required: restart }));+ if (result.ok) throw new Error('expected 503');+ expect(result.body).toMatchObject({ code: 'persistence_restart_required', self_exit_suppressed: true });+ expect(result.body.fix).toStartWith('self_exit_suppressed:');+ restart = false; second.check();+ expect(selfExitSuppressed(next)).toBe(false);+ } finally { second.stop(); }+ });++ test('a statement past the in-flight budget never triggers the exit, nor does a healthy consumer', () => {+ let now = 0;+ const exits: number[] = [];+ const watch = installRestartRequiredExit(fakeEngine({ oldest: 10_000_000 }).engine, 120, { ledgerPath: ledger('budget'), now: () => now, consumerStatus: healthy, exit: code => exits.push(code), log: () => {}, everyMs: 3_600_000 });+ try { for (let i = 0; i < 10; i++) { now += 60_000; watch.check(); } } finally { watch.stop(); }+ expect(exits).toEqual([]);+ });+});diff --git a/test/serve-sync-handoff.serial.test.ts b/test/serve-sync-handoff.serial.test.tsindex bf08758701..ba13cb2e0c 100644--- a/test/serve-sync-handoff.serial.test.ts+++ b/test/serve-sync-handoff.serial.test.ts@@ -36,6 +36,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { ownConsumerForcedReason, resetOwnConsumerForTest } from '../src/core/persistence/consumer-election.ts';import { registerLocalWriter, revokeLocalWriter } from '../src/core/persistence/identity.ts';import { startResolveIpcServer, type IpcHandlers } from '../src/core/context/resolve-ipc.ts';import { localIpcSocketPath } from '../src/core/context/ipc-path.ts';@@ -234,7 +235,11 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (const f = await fixture(1);let probed = 0;const d = { ...deps({}), probe: async () => { probed++; return serveRow(); } };+ resetOwnConsumerForTest();expect(await maybeDelegateManagedSyncToServe(engine, ['--no-delegate', '--repo', '/x'], baseOpts(f.id), d)).toEqual({ kind: 'own_consumer', reason: 'opted_out', line: null });+ // #6543: the opt-out makes this process a full consumer even under persistence.single_consumer.+ expect(ownConsumerForcedReason()).toBe('opted_out');+ resetOwnConsumerForTest();expect(await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), { ...d, env: { GBRAIN_SYNC_NO_DELEGATE: '1' } })).toEqual({ kind: 'own_consumer', reason: 'opted_out', line: null });expect(probed).toBe(0);}), 120_000);@@ -252,34 +257,65 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (test('an unsupported flag, the kill switch and a missing socket each fall back with one actionable line, never a refusal', async () => withEnv({ GBRAIN_HOME: home }, async () => {const f = await fixture(1);+ resetOwnConsumerForTest();captureStderr();const flag = await maybeDelegateManagedSyncToServe(engine, ['--exclude', 'x'], baseOpts(f.id), deps({ sock: await serveSocket() }));const kill = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), { ...deps({ sock: await serveSocket() }), env: { GBRAIN_SERVE_SYNC_IPC: '0' } });const noSock = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: null }));releaseStderr();expect(flag).toMatchObject({ kind: 'own_consumer', reason: 'unsupported_flag' });- expect(flag.kind === 'own_consumer' && flag.line).toMatch(/`--exclude` isn't supported through serve-delegated sync; this run uses its own consumer beside the serve \(PID 4242\)/);+ expect(flag.kind === 'own_consumer' && flag.line).toMatch(/`--exclude` isn't supported through serve-delegated sync; this run does not delegate to the serve \(PID 4242\): it admits its own writes, and with persistence.single_consumer on the serve's consumer publishes them/);expect(kill).toMatchObject({ kind: 'own_consumer', reason: 'kill_switch' });- expect(kill.kind === 'own_consumer' && kill.line).toMatch(/GBRAIN_SERVE_SYNC_IPC=0.*own consumer beside the serve \(PID 4242\)/);+ expect(kill.kind === 'own_consumer' && kill.line).toMatch(/GBRAIN_SERVE_SYNC_IPC=0.*does not delegate to the serve \(PID 4242\)/);+ expect(kill.kind === 'own_consumer' && kill.line).not.toContain('own consumer beside');expect(noSock).toMatchObject({ kind: 'own_consumer', reason: 'no_socket' });expect(noSock.kind === 'own_consumer' && noSock.line).toMatch(/exposes no sync IPC socket.*Restart that serve on this gbrain version/);expect(captured).toHaveLength(3);+ // #6543: none of these rungs forces this process's own consumer beside the serve.+ expect(ownConsumerForcedReason()).toBeNull();}), 120_000);- test('skew (T1c): an older serve answering unknown_kind, a stale serve without the protocol echo, and unsupported_kind each fall back with one line', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ test('#6543: a serve whose IPC socket does not answer cannot take the run, so this process consumes itself (forced past single_consumer)', async () => withEnv({ GBRAIN_HOME: home }, async () => {const f = await fixture(1);- // An older base server has no sync handlers at all: `unknown_kind:sync_start` without a protocol echo → stale_serve on the client.- const older = await serveSocket({ sync_start: undefined, sync_status: undefined, sync_abort: undefined });- // A serve of this family with the kinds disabled (GBRAIN_SERVE_SYNC_IPC=0 on the serve) → `unsupported_kind` with the echo.+ const dead = join(home, `dead-${randomUUID().slice(0, 8)}.sock`);+ writeFileSync(dead, '');+ resetOwnConsumerForTest();+ captureStderr();+ const silent = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: dead }));+ releaseStderr();+ expect(silent).toMatchObject({ kind: 'own_consumer', reason: 'no_socket' });+ expect(silent.kind === 'own_consumer' && silent.line).toMatch(/not answering its IPC socket/);+ expect(ownConsumerForcedReason()).toBe('no_socket');+ resetOwnConsumerForTest();+ }), 120_000);++ test('skew (T1c): a stale serve without the protocol echo forces this process\'s own consumer; a current serve answering unsupported_kind (kinds absent or disabled) falls back without forcing', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const f = await fixture(1);+ // A pre-delegation serve answers `unknown_kind:sync_start` without a protocol echo → stale_serve (degraded) on the client.+ const legacy = await serveSocket({ sync_start: (() => ({ ok: false, error: 'unknown_kind:sync_start' })) as unknown as IpcHandlers['sync_start'] });+ // A serve of this family without the sync kinds, or with them disabled (GBRAIN_SERVE_SYNC_IPC=0 on the serve) → `unsupported_kind` with the echo.+ const absent = await serveSocket({ sync_start: undefined, sync_status: undefined, sync_abort: undefined });const disabled = await serveSocket({ sync_start: () => ({ ok: false, protocol: 2, error: 'unsupported_kind' }) });+ resetOwnConsumerForTest();captureStderr();- const stale = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: older }));- const unsupported = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: disabled }));+ const stale = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: legacy }));releaseStderr();expect(stale).toMatchObject({ kind: 'own_consumer', reason: 'older_serve' });expect(stale.kind === 'own_consumer' && stale.line).toMatch(/predates serve-delegated managed sync.*own consumer beside the serve \(PID 4242\).*Restart that serve/);- expect(unsupported).toMatchObject({ kind: 'own_consumer', reason: 'older_serve' });+ // #6543: the stale serve cannot take the run, so this process consumes itself.+ expect(ownConsumerForcedReason()).toBe('older_serve');+ resetOwnConsumerForTest();+ captureStderr();+ const withoutKinds = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: absent }));+ const unsupported = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: disabled }));+ releaseStderr();+ for (const outcome of [withoutKinds, unsupported]) {+ expect(outcome).toMatchObject({ kind: 'own_consumer', reason: 'older_serve' });+ expect(outcome.kind === 'own_consumer' && outcome.line).toMatch(/runs with serve-delegated managed sync off.*does not delegate to the serve \(PID 4242\)/);+ }expect(captured).toHaveLength(2);+ // #6543: a healthy current serve with delegation off keeps consuming, so neither fallback forces a second consumer.+ expect(ownConsumerForcedReason()).toBeNull();// Nothing was admitted by the serve: the source's cursor is untouched.const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [f.id]);expect(n).toBe(0);diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsindex acca266e93..3a3ea36cc8 100644--- a/vendor/postgres/cf/src/connection.js+++ b/vendor/postgres/cf/src/connection.js@@ -177,6 +177,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return+ let mayPipeline = !q.options.onexecutetry {q.state = backendquery@@ -184,9 +185,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose: (query = q, query.active = true, armInflight())build(q)+ mayPipeline = mayPipeline || q.options.onexecute(connection)lastWritten = qlastExecuted = q- const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn@@ -204,15 +205,19 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.retried = errorq.describeFirst = falseq.cursorFn = null+ // GBrain (#6543): the stock `return true` let the pool route more statements behind q whatever max_pipeline and+ // onexecute said, so a pool built not to pipeline (a transaction-mode pooler) pipelined after every build failure.+ // onexecute (a transaction's begin) ran only if q built; a begin that failed to build is never pipelined behind.options.onbuilderror && reportBuildError(q, error)- write(Unbuildable)- return true+ return write(Unbuildable)+ && sent.length < max_pipeline+ && mayPipeline}}function reportBuildError(q, error) {try {- options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q), error && error.parameter)} catch (_) {}}@@ -546,7 +551,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))- query = null+ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged+ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that+ // error to its first statement, and a stale row count left holes at the start of the next result.+ query = errorResponse = results = null+ result = new Result()+ rows = 0closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000diff --git a/vendor/postgres/cf/src/types.js b/vendor/postgres/cf/src/types.jsindex aa2ead29fa..3a4794c909 100644--- a/vendor/postgres/cf/src/types.js+++ b/vendor/postgres/cf/src/types.js@@ -81,7 +81,7 @@ export function handleValue(x, parameters, types, options) {: value = x = options.transform.undefinedif (value === undefined)- throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ throw Object.assign(Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed (parameter $' + (types.length + 1) + ')'), { parameter: types.length + 1 })}return '$' + (types.push(diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsindex 1d6ea0a50f..ad0cbd0c28 100644--- a/vendor/postgres/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -175,6 +175,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return+ let mayPipeline = !q.options.onexecutetry {q.state = backendquery@@ -182,9 +183,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose: (query = q, query.active = true, armInflight())build(q)+ mayPipeline = mayPipeline || q.options.onexecute(connection)lastWritten = qlastExecuted = q- const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn@@ -202,15 +203,19 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.retried = errorq.describeFirst = falseq.cursorFn = null+ // GBrain (#6543): the stock `return true` let the pool route more statements behind q whatever max_pipeline and+ // onexecute said, so a pool built not to pipeline (a transaction-mode pooler) pipelined after every build failure.+ // onexecute (a transaction's begin) ran only if q built; a begin that failed to build is never pipelined behind.options.onbuilderror && reportBuildError(q, error)- write(Unbuildable)- return true+ return write(Unbuildable)+ && sent.length < max_pipeline+ && mayPipeline}}function reportBuildError(q, error) {try {- options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q), error && error.parameter)} catch (_) {}}@@ -544,7 +549,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))- query = null+ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged+ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that+ // error to its first statement, and a stale row count left holes at the start of the next result.+ query = errorResponse = results = null+ result = new Result()+ rows = 0closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000diff --git a/vendor/postgres/cjs/src/types.js b/vendor/postgres/cjs/src/types.jsindex 0578284c5a..e80a868ebd 100644--- a/vendor/postgres/cjs/src/types.js+++ b/vendor/postgres/cjs/src/types.js@@ -80,7 +80,7 @@ module.exports.handleValue = handleValue;function handleValue(x, parameters, typ: value = x = options.transform.undefinedif (value === undefined)- throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ throw Object.assign(Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed (parameter $' + (types.length + 1) + ')'), { parameter: types.length + 1 })}return '$' + (types.push(diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex 37824bf4cd..84f8a5878e 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -175,6 +175,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return+ let mayPipeline = !q.options.onexecutetry {q.state = backendquery@@ -182,9 +183,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose: (query = q, query.active = true, armInflight())build(q)+ mayPipeline = mayPipeline || q.options.onexecute(connection)lastWritten = qlastExecuted = q- const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst&& !q.cursorFn@@ -202,15 +203,19 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.retried = errorq.describeFirst = falseq.cursorFn = null+ // GBrain (#6543): the stock `return true` let the pool route more statements behind q whatever max_pipeline and+ // onexecute said, so a pool built not to pipeline (a transaction-mode pooler) pipelined after every build failure.+ // onexecute (a transaction's begin) ran only if q built; a begin that failed to build is never pipelined behind.options.onbuilderror && reportBuildError(q, error)- write(Unbuildable)- return true+ return write(Unbuildable)+ && sent.length < max_pipeline+ && mayPipeline}}function reportBuildError(q, error) {try {- options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q), error && error.parameter)} catch (_) {}}@@ -544,7 +549,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))- query = null+ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged+ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that+ // error to its first statement, and a stale row count left holes at the start of the next result.+ query = errorResponse = results = null+ result = new Result()+ rows = 0closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000diff --git a/vendor/postgres/src/types.js b/vendor/postgres/src/types.jsindex 7c7c2b9309..d462498a38 100644--- a/vendor/postgres/src/types.js+++ b/vendor/postgres/src/types.js@@ -80,7 +80,7 @@ export function handleValue(x, parameters, types, options) {: value = x = options.transform.undefinedif (value === undefined)- throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ throw Object.assign(Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed (parameter $' + (types.length + 1) + ')'), { parameter: types.length + 1 })}return '$' + (types.push(diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.tsindex 53127d627f..b77d74e109 100644--- a/vendor/postgres/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts@@ -135,9 +135,10 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {onstuck: (stuck: { age_ms: number; queued: number; statement: string }) => void;/*** GBrain: called when a statement fails to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`);- * `statement` is its text with `$n` placeholders, never parameter values.+ * `statement` is its text with `$n` placeholders, never parameter values; `parameter` is the 1-based+ * index of an undefined parameter value, undefined when the failure names none (an array element).*/- onbuilderror: (code: string, statement: string) => void;+ onbuilderror: (code: string, statement: string, parameter?: number) => void;/*** GBrain: called once per connection retired because a statement's answer arrived with no statement* waiting for it; `statement` is the last statement written on it, with `$n` placeholders.