Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): owner.backend[] from pg_stat_activity by application_name, backend_visibility, persistence_pooler_transaction_mode doctor check (#6317 lane 2, reporter ask 3)

garrytandbce1c0f483a
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index ce91207aed..4ab69cc41d 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1888,6 +1888,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_pooler_transaction_mode
+
+<a id="persistence_pooler_transaction_mode"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The resident write consumer's ordinary pool goes through a transaction-mode pooler (prepared statements off), where a consumer round-trip can be lost and one claim then holds its root for as long as the process lives. | A transaction-mode pooler (PgBouncer, Supavisor on port 6543) assigns a server connection per transaction and can leave a client waiting for a reply that never arrives (the backend reads `active` in `ClientRead`); the owner's phase deadline fires but the awaited promise never settles, so the claim renews forever with nothing in flight at the database. The same catch-up on the session-mode URL (port 5432) or the direct URL drains. Short-lived readers on the pooler are unaffected; the finding is about the processes that hold write claims. | Set DATABASE_URL for gbrain serve, gbrain sync and the jobs worker to the session-mode pooler URL or the direct database URL on their supervisor, restart them, then verify with gbrain sources writer movement. Run: gbrain sources writer status --json | host_admin | `gbrain doctor --only persistence_pooler_transaction_mode --json` | 1 | no |
+
+More: [docs/guides/troubleshooting.md#persistence-pooler-transaction-mode](../../docs/guides/troubleshooting.md#persistence-pooler-transaction-mode)
+
### persistence_write_stall
<a id="persistence_write_stall"></a>
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index e8b1731909..992a3665f9 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2202 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2998 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move)
-src/core/postgres-engine.ts 2955 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +2 #6317: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts)
+src/core/postgres-engine.ts 2956 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +2 #6317: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts); +1 #6317: getPoolDiagnostics().prepare (the pooler-mode mark the doctor check reads)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
src/core/types.ts 2239 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/commands/doctor/checks/managed-sync-movement.ts b/src/commands/doctor/checks/managed-sync-movement.ts
index a258ac5496..03b8439a18 100644
--- a/src/commands/doctor/checks/managed-sync-movement.ts
+++ b/src/commands/doctor/checks/managed-sync-movement.ts
@@ -31,7 +31,7 @@ async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]>
message: `${stuck.map(m => `${m.source_id} (since ${m.not_moving_since}${m.head?.step ? `, head at step ${m.head.step}` : ''}${m.head?.owner ? `, ${m.head.owner.kind} pid ${m.head.owner.pid}` : ''})`).join('; ')}: `
+ `managed sync data has not moved for longer than the ${Math.round(first.ceiling_ms / 1000)}s ceiling while a sync or consumer is live. The health signals are green; the data is not.`,
fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', first.source_id, '--json'],
- 'Read-only: names the request at the head, its step, what it waits on, the owner process and the next action on the running claim.', 'managed_sync_not_moving', { docs: DOCS }) });
+ 'Read-only: names the request at the head, its step, what it waits on, the owner process and the next step (`claim.next`) on the running claim.', 'managed_sync_not_moving', { docs: DOCS }) });
} else if (pending.length) {
checks.push({ name: 'managed_sync_not_moving', status: 'ok', severity: 'info', details,
message: `Managed sync data is moving${parked.length ? `; ${parked.map(m => `${m.source_id} is parked at ${m.cursor!.index}/${m.cursor!.total} (no sync or consumer live; resume: ${m.cursor!.resume_command})`).join('; ')}` : ''}.` });
diff --git a/src/commands/doctor/checks/persistence-pooler.ts b/src/commands/doctor/checks/persistence-pooler.ts
new file mode 100644
index 0000000000..e3fc8a88a9
--- /dev/null
+++ b/src/commands/doctor/checks/persistence-pooler.ts
@@ -0,0 +1,44 @@
+/**
+ * persistence_pooler_transaction_mode (#6317): the resident consumer's own
+ * database URL goes through a transaction-mode pooler. The reporter's wedge
+ * reproduced with one process on Supavisor transaction mode (:6543): a
+ * consumer round-trip (the expired-claims CTE) whose reply never came back,
+ * backend `active` in `ClientRead`, the 5 s phase deadline firing without the
+ * awaited promise settling; the same command on the session-mode URL (:5432)
+ * drained cleanly. The engine already marks that URL (`prepare: false`, the
+ * port-6543 convention db.ts `resolvePrepare` applies, or an explicit
+ * `GBRAIN_PREPARE=false`); this check turns the mark into a finding for the
+ * processes that hold claims (`serve`, `sync`, `jobs`), with the session-mode
+ * URL as the operator's fix. Short-lived readers on the pooler are fine.
+ * Reads nothing from the database: the mark is a connection option.
+ */
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+const DOCS = 'docs/guides/troubleshooting.md#persistence-pooler-transaction-mode';
+
+async function runPersistencePoolerCheck(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const engine = connectedEngine(ctx);
+ if (engine.kind !== 'postgres') {
+ checks.push({ name: 'persistence_pooler_transaction_mode', status: 'ok', severity: 'info', readiness_state: 'not_applicable', message: 'PGLite has no pooler.', details: { docs: DOCS } });
+ return checks;
+ }
+ const diagnostics = (engine as { getPoolDiagnostics?: () => { prepare?: boolean | null; poolMax?: number | null } | null }).getPoolDiagnostics?.() ?? null;
+ const url = (engine as { connectionManager?: { describeMode(): { mode: string; direct_host?: string } } | null }).connectionManager?.describeMode() ?? null;
+ const details = { prepare: diagnostics?.prepare ?? null, pool_max: diagnostics?.poolMax ?? null, pool_mode: url?.mode ?? null, direct_host: url?.direct_host ?? null, docs: DOCS };
+ if (diagnostics?.prepare !== false) {
+ checks.push({ name: 'persistence_pooler_transaction_mode', status: 'ok', message: 'The ordinary pool runs with prepared statements (a session-mode pooler or a direct connection).', details });
+ return checks;
+ }
+ checks.push({ name: 'persistence_pooler_transaction_mode', status: 'warn', readiness_state: 'degraded', details,
+ message: 'The ordinary pool is on a transaction-mode pooler (prepared statements off: the port-6543 convention or GBRAIN_PREPARE=false). A resident write consumer (serve, sync, jobs) on it '
+ + 'can lose a round-trip inside the pooler (backend active in ClientRead, the reply never arrives) and sit on one claim for as long as the process lives; the same catch-up on the session-mode URL drains.',
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'host_admin', requires_exclusive: false, docs: DOCS,
+ why: 'Point the processes that hold write claims (serve, the sync CLI, the jobs worker) at the session-mode pooler URL (port 5432) or the direct URL through DATABASE_URL on their supervisor, then restart them; status then shows their backends by application_name.',
+ user_message: 'Set DATABASE_URL for gbrain serve, gbrain sync and the jobs worker to the session-mode pooler URL (port 5432, same host) or the direct database URL, restart them, then run gbrain sources writer movement.',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_pooler_transaction_mode', '--json'] } } });
+ return checks;
+}
+
+export const persistencePoolerEntry: DoctorEntry = { name: 'persistence_pooler_transaction_mode', emits: ['persistence_pooler_transaction_mode'], run: runPersistencePoolerCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 3ef1908b13..430336594a 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -101,6 +101,7 @@ import { chatFallbackChainEntry } from './checks/chat-fallback.ts';
import { behaviorChangesEntry } from './checks/behavior-changes.ts';
import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
+import { persistencePoolerEntry } from './checks/persistence-pooler.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
@@ -178,6 +179,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
coreMemoryEntry,
fenceIntegrityEntry,
managedSyncMovementEntry,
+ persistencePoolerEntry,
searchModeEntry,
];
diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.ts
index b9858084bc..817f885426 100644
--- a/src/commands/sources-writer-movement.ts
+++ b/src/commands/sources-writer-movement.ts
@@ -220,7 +220,7 @@ export async function runMovementCheck(engine: BrainEngine, opts: { sourceId?: s
}
const sources = after.map(m => movementReport(byId.get(m.source_id), m, window.window_ms));
const failing = sources.find(r => r.exit !== 0);
- const error = failing ? toAgentError(opError('managed_sync_not_moving', failing.why, `Run ${writerStatusCommand(failing.source_id)} and follow the running claim's next_action; verify with gbrain sources writer movement ${failing.source_id}.`,
+ const error = failing ? toAgentError(opError('managed_sync_not_moving', failing.why, `Run ${writerStatusCommand(failing.source_id)} and follow the running claim's next step; verify with gbrain sources writer movement ${failing.source_id}.`,
{ reason: failing.reason, fix: readFix('Read-only: the request at the head, its step, wait cause, owner and next action.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', failing.source_id, '--json'] }) }),
{ transport: 'cli', command: 'sources writer movement', render: cliRenderContext() }) : undefined;
return { schema_version: 1, window_ms: window.window_ms, budget_ms: window.budget_ms, window_source: window.source, waited_ms: waited, sources, exit_code: failing ? 1 : 0, ...(error ? { error } : {}) };
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index 93c5fdd246..aead71049c 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 { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded } from './db.ts';
+import { gbrainApplicationName, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded } from './db.ts';
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
@@ -513,6 +513,7 @@ export class ConnectionManager {
statement_timeout: String(DDL_STMT_TIMEOUT_MS),
idle_in_transaction_session_timeout: String(DDL_IDLE_TX_TIMEOUT_MS),
maintenance_work_mem: BULK_MAINTENANCE_WORK_MEM,
+ application_name: gbrainApplicationName(),
},
};
const t0 = Date.now();
diff --git a/src/core/db.ts b/src/core/db.ts
index 1d0f49d214..438b135d55 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,4 +1,5 @@
import postgres from '#postgres'
+import { claimOwner } from './persistence/claim-phase.ts';
import { traceSqlOptions } from './sql-trace.ts';
import { GBrainError, type EngineConfig } from './types.ts';
import { SCHEMA_SQL } from './schema-embedded.generated.ts';
@@ -263,6 +264,18 @@ export function resolveMaxLifetimeSeconds(
const DEFAULT_STATEMENT_TIMEOUT = '5min';
const DEFAULT_IDLE_TX_TIMEOUT = '5min';
+/**
+ * #6317 (C1): the `application_name` every gbrain pool starts its connections
+ * with, `gbrain <kind>:<pid>:<nonce8>`, so `writer status` can find the owner
+ * process's backends in `pg_stat_activity` (and a ClientRead wedge is visible
+ * in one command). Through a transaction-mode pooler the server connection is
+ * shared, so the mapping is partial; readers say `backend_visibility: pooled`.
+ */
+export function gbrainApplicationName(): string {
+ const owner = claimOwner();
+ return `gbrain ${owner.kind}:${owner.pid}:${(owner.nonce ?? '').slice(0, 8)}`.slice(0, 63);
+}
+
export function resolveSessionTimeouts(): Record<string, string> {
const out: Record<string, string> = {};
const add = (envKey: string, gucKey: string, defaultVal: string) => {
@@ -359,9 +372,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statu
onpoisoned: hooks.onpoisoned,
shared_types: resolveSharedTypes(),
};
- if (Object.keys(timeouts).length > 0) {
- opts.connection = timeouts;
- }
+ opts.connection = { ...timeouts, application_name: gbrainApplicationName() };
if (typeof prepare === 'boolean') {
opts.prepare = prepare;
if (!prepare) {
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 8e75001361..3ed2a11a54 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -249,6 +249,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'persistence_request_indexes',
'persistence_write_stall',
'managed_sync_not_moving',
+ 'persistence_pooler_transaction_mode',
'persistence_session_timeouts',
'stale_embedding_effects',
'vector_plan',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c2990c04b4..9d6a7003ad 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -278,6 +278,13 @@ 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_pooler_transaction_mode: { class: 'host_only', actor: 'host_admin',
+ summary: "The resident write consumer's ordinary pool goes through a transaction-mode pooler (prepared statements off), where a consumer round-trip can be lost and one claim then holds its root for as long as the process lives.",
+ why: "A transaction-mode pooler (PgBouncer, Supavisor on port 6543) assigns a server connection per transaction and can leave a client waiting for a reply that never arrives (the backend reads `active` in `ClientRead`); the owner's phase deadline fires but the awaited promise never settles, so the claim renews forever with nothing in flight at the database. The same catch-up on the session-mode URL (port 5432) or the direct URL drains. Short-lived readers on the pooler are unaffected; the finding is about the processes that hold write claims.",
+ docs: 'docs/guides/troubleshooting.md#persistence-pooler-transaction-mode',
+ suggestion: 'Set DATABASE_URL for gbrain serve, gbrain sync and the jobs worker to the session-mode pooler URL or the direct database URL on their supervisor, restart them, then verify with gbrain sources writer movement.',
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: shows the consumers alive on this host and, per running claim, the owner\'s backends from pg_stat_activity with their wait events.', requires_exclusive: false,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_pooler_transaction_mode', '--json'] } } },
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 } },
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.' },
plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 20336f2294..b96f2cf9c7 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -4,7 +4,7 @@ import type { JournalLimits } from './model.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { writeHealth } from './health.ts';
-import { claimStall, claimStateOf, isOwnerThisProcess, type ClaimRow, type ClaimState, type ClaimStall } from './claim-phase.ts';
+import { claimStall, claimStateOf, isOwnerThisProcess, sqlLabel, type ClaimRow, type ClaimState, type ClaimStall } from './claim-phase.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
import { enginePoolStats, type DriverPoolStats } from '../postgres-engine/pool-stats.ts';
import { consumerLive, listHostConsumers, type ConsumerRow } from './consumer-heartbeat.ts';
@@ -40,7 +40,7 @@ export function writerNextAction(reason: string | null | undefined): string {
}
/**
- * #6317 (C1): the one `next_action` envelope a running claim ends with, so the two-call journey (sources status → writer
+ * #6317 (C1): the one `next` envelope (`claim.next`: code, why, retry_after_ms, fix) a running claim ends with, so the two-call journey (sources status → writer
* status) ends in an action: inside the allowance the agent reruns status after `retry_after_ms` (`next: run`); past the
* ceiling or on `restart_required` the host admin restarts the named owner (`tell_user_to_run`); a lapsed claim resumes
* on its own once its transaction ends or the owner exits, so the fix is the resume (`run`).
@@ -71,6 +71,43 @@ export function claimNextAction(claim: ClaimState, stall: ClaimStall | null, pol
: `${who} is ${claim.phase === 'publishing' ? 'publishing' : 'preparing'} this write${where}${owner.live === false ? '; its heartbeat row is not live' : ''}. Nothing to do yet.`,
fix: renderAction({ argv: status, consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: rerun after retry_after_ms to see the step advance or the claim settle.', verify: { argv: status } }, ctx) };
}
+/**
+ * #6317 (reporter ask 3): the owner process's database backends from `pg_stat_activity`, matched on the `application_name`
+ * every gbrain pool starts its connections with (`gbrain <kind>:<pid>:<nonce8>`, db.ts), so a round-trip that never
+ * returns (backend `active`, `wait_event` ClientRead, an old transaction) is visible in one command. Statement text never
+ * leaves: only its label (first keyword plus table). Through a transaction-mode pooler the server connection is shared
+ * and carries the pooler's own name or another client's, so the mapping is partial (`backend_visibility: 'pooled'`).
+ */
+export interface OwnerBackend { pid: number; state: string | null; wait_event_type: string | null; wait_event: string | null; statement: string | null;
+ query_age_ms: number | null; xact_age_ms: number | null; state_age_ms: number | null; application_name: string }
+export type BackendVisibility = 'session' | 'pooled' | 'unavailable';
+export async function readOwnerBackends(engine: BrainEngine, owners: Array<Pick<ClaimState['owner'] & object, 'kind' | 'pid' | 'nonce'>>): Promise<{ visibility: BackendVisibility; byOwner: Map<string, OwnerBackend[]> }> {
+ const byOwner = new Map<string, OwnerBackend[]>();
+ if (engine.kind !== 'postgres' || !owners.length) return { visibility: 'unavailable', byOwner };
+ const diagnostics = (engine as { getPoolDiagnostics?: () => { prepare?: boolean | null } | null }).getPoolDiagnostics?.();
+ const visibility: BackendVisibility = diagnostics?.prepare === false ? 'pooled' : 'session';
+ const names = owners.map(owner => `gbrain ${owner.kind}:${owner.pid}:${(owner.nonce ?? '').slice(0, 8)}`);
+ try {
+ const rows = await engine.executeRaw<{ pid: number; state: string | null; wait_event_type: string | null; wait_event: string | null; query: string | null;
+ query_age_ms: string | number | null; xact_age_ms: string | number | null; state_age_ms: string | number | null; application_name: string }>(
+ `SELECT pid, state, wait_event_type, wait_event, left(query, 300) AS query, application_name,
+ (EXTRACT(EPOCH FROM (now() - query_start)) * 1000)::bigint AS query_age_ms,
+ (EXTRACT(EPOCH FROM (now() - xact_start)) * 1000)::bigint AS xact_age_ms,
+ (EXTRACT(EPOCH FROM (now() - state_change)) * 1000)::bigint AS state_age_ms
+ FROM pg_stat_activity WHERE datname = current_database() AND backend_type = 'client backend' AND application_name = ANY($1::text[]) ORDER BY pid`,
+ [names], { timeoutMs: 2_000 });
+ for (const row of rows) {
+ const list = byOwner.get(row.application_name) ?? [];
+ list.push({ pid: Number(row.pid), state: row.state, wait_event_type: row.wait_event_type, wait_event: row.wait_event, statement: row.query ? sqlLabel(row.query) : null,
+ query_age_ms: row.query_age_ms === null ? null : Number(row.query_age_ms), xact_age_ms: row.xact_age_ms === null ? null : Number(row.xact_age_ms),
+ state_age_ms: row.state_age_ms === null ? null : Number(row.state_age_ms), application_name: row.application_name });
+ byOwner.set(row.application_name, list);
+ }
+ return { visibility, byOwner };
+ } catch {
+ return { visibility: 'unavailable', byOwner };
+ }
+}
/** #6317 (C1): the pool numbers for a running claim: this process's driver when it owns the claim, else the owner's heartbeat row. */
function claimPool(engine: BrainEngine, claim: ClaimState, row: ConsumerRow | null): { pool: DriverPoolStats | null; pool_source: 'driver' | 'heartbeat' | null } {
if (isOwnerThisProcess(claim.owner)) return { pool: enginePoolStats(engine), pool_source: enginePoolStats(engine) ? 'driver' : null };
@@ -138,6 +175,8 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
const hostId = existingLocalHostId();
const consumerRows = hostId ? await listHostConsumers(engine, hostId) : [];
const tracked = (engine as { getPoolDiagnostics?: () => { tracked?: unknown } | null }).getPoolDiagnostics?.()?.tracked ?? null;
+ const claimStates = blockers.map(row => claimStateOf({ state: row.state, claim_phase: row.claim_phase, execution_token: row.execution_token, claim_lapsed: row.claim_lapsed, publication_started: row.publication_started }));
+ const backends = await readOwnerBackends(engine, claimStates.flatMap(state => state?.owner ? [state.owner] : []));
// C-NEW-4: the consumer is per process, so this is the answering process's own ingress, never proof the brain's owner is down.
const local = persistenceConsumerStatus(engine);
const local_process_ingress = { ...local, scope: local.state === 'not_running'
@@ -146,20 +185,23 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
return { ...brain, sampled_at: new Date().toISOString(), publication_concurrency: publicationConcurrency(engine),
local_process_ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits), preparation_policy,
recent_failures: failures.map(row => ({ ...row, next_action: row.error_detail?.origin === 'database_guard' ? DATABASE_REFUSAL_HINT : DATABASE_TRIGGER_HINT })),
- blockers: blockers.map(({ claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }) => {
+ backend_visibility: backends.visibility,
+ blockers: blockers.map(({ claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }, index) => {
const health = writeHealth(row);
const advice = writerNextAction(row.blocked_reason ?? row.error_code);
// #6176: a running request names the phase its claim is in and how long it has held it; #6278: its step, wait cause, owner
// process and, past its budget, the `preparation_overdue` verdict (the running state; `preparation_stalled` is only the terminal give-up).
- const state = claimStateOf({ state: row.state, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started });
+ const state = claimStates[index] ?? null;
const budget = snapshot ? preparationBudgetMs({ operation: row.operation, intent: row.intent_kind ? { kind: row.intent_kind } : null }, snapshot.preparation, 30_000) : null;
const stall = state && budget !== null ? claimStall(state, budget) : null;
// #6317 (C1): the owner's heartbeat row (liveness, pool), the last statement, and the one next_action envelope per running claim.
const ownerRow = state?.owner ? consumerRows.find(r => r.pid === state.owner!.pid && (state.owner!.nonce === undefined || r.nonce === state.owner!.nonce)) ?? null : null;
const ceilingMs = snapshot?.preparation.ceilingMs ?? 600_000;
- const claim = state ? { ...state, ...(budget === null ? {} : { budget_ms: budget }), stall, ...claimPool(engine, state, ownerRow), pool_tracked_subset: tracked,
+ const ownerBackends = state?.owner ? backends.byOwner.get(`gbrain ${state.owner.kind}:${state.owner.pid}:${(state.owner.nonce ?? '').slice(0, 8)}`) ?? [] : [];
+ const claim = state ? { ...state, ...(state.owner ? { owner: { ...state.owner, backend: ownerBackends, backend_visibility: backends.visibility } } : {}),
+ ...(budget === null ? {} : { budget_ms: budget }), stall, ...claimPool(engine, state, ownerRow), pool_tracked_subset: tracked,
owner_live: ownerRow ? consumerLive(ownerRow) : null, owner_mode: ownerRow?.mode ?? null,
- next_action: claimNextAction(state, stall, { budgetMs: budget, ceilingMs }, row.source_id, { row: ownerRow, live: ownerRow ? consumerLive(ownerRow) : null }) } : undefined;
+ next: claimNextAction(state, stall, { budgetMs: budget, ceilingMs }, row.source_id, { row: ownerRow, live: ownerRow ? consumerLive(ownerRow) : null }) } : undefined;
return { ...row, preparation_attempts: row.preparation_attempts ?? 0, ...health, ...(claim ? { claim } : {}), next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT
? `${WRITER_INSPECTION_HINT} ${advice}` : advice };
}) };
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index 79a2c7761a..e72ff1a0a2 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -197,7 +197,7 @@ export function startMovementWatch(engine: BrainEngine, opts: { log: (line: stri
for (const m of await readSourceMovement(engine)) {
if (m.movement_state === 'not_moving' && !flipped.has(m.source_id)) {
flipped.add(m.source_id);
- opts.log(`[gbrain notice managed_sync_not_moving kind=degraded] ${formatSourceMovement(m)}\nnext: run ${m.writer_status_command} (read-only) and act on the running claim's next_action.`);
+ opts.log(`[gbrain notice managed_sync_not_moving kind=degraded] ${formatSourceMovement(m)}\nnext: run ${m.writer_status_command} (read-only) and act on the running claim's next step.`);
} else if (m.movement_state !== 'not_moving' && flipped.delete(m.source_id)) {
opts.log(`[gbrain notice managed_sync_not_moving kind=info] ${m.source_id}: managed sync data is moving again (${m.movement_state}).`);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 10899abc8d..7a7380cb4c 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -379,9 +379,7 @@ export class PostgresEngine implements BrainEngine {
onpoisoned: (status: string) => this.onPoisoned('read', status),
shared_types: db.resolveSharedTypes(),
};
- if (Object.keys(timeouts).length > 0) {
- opts.connection = timeouts;
- }
+ opts.connection = { ...timeouts, application_name: db.gbrainApplicationName() };
if (typeof prepare === 'boolean') {
opts.prepare = prepare;
}
@@ -703,7 +701,7 @@ export class PostgresEngine implements BrainEngine {
/** #5801: observe connection acquisition (see CheckoutGauge.onCheckout). Duck-typed like getPoolDiagnostics. */
onCheckout(listener: () => void): () => void { return this.checkoutGauge.onCheckout(listener); }
- getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; pool: DriverPoolStats | null } | null {
+ getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {
try {
const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;
return {
@@ -711,6 +709,7 @@ export class PostgresEngine implements BrainEngine {
poolMax: typeof max === 'number' ? max : null,
poisonedDiscards: this.poisonedDiscards?.count ?? 0,
pool: driverPoolStats(this.sql),
+ prepare: (this.sql as unknown as { options?: { prepare?: boolean } }).options?.prepare ?? null,
};
} catch {
return null;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 045fa01810..29a3aceb39 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -112,3 +112,4 @@ test/sync-waiver-budget.test.ts
test/takes-vector-lifecycle-5885.serial.test.ts
test/withdrawal-overlay-concurrency.test.ts
test/withdrawal-publication-file.test.ts
+test/writer-status-owner-backends.test.ts
diff --git a/test/sync-movement.test.ts b/test/sync-movement.test.ts
index 07e8145742..58be801d33 100644
--- a/test/sync-movement.test.ts
+++ b/test/sync-movement.test.ts
@@ -275,14 +275,14 @@ describe('doctor managed_sync_not_moving and the serve notice', () => {
const ctx = { engine } as unknown as Parameters<typeof managedSyncMovementEntry.run>[0];
const f = await managedSource();
await cursor(f, 1, 9); await request(f, 'committed', { completedAt: ago(400_000) });
- const [parked] = await managedSyncMovementEntry.run(ctx) as Array<Record<string, unknown>>;
+ const [parked] = await managedSyncMovementEntry.run(ctx) as unknown as Array<Record<string, unknown>>;
expect(parked).toMatchObject({ name: 'managed_sync_not_moving', status: 'ok', severity: 'info' });
expect(String(parked!.message)).toContain(`${f.id} is parked at 1/9`);
const lines: string[] = [];
const watch = startMovementWatch(engine, { log: line => lines.push(line), everyMs: 3_600_000 });
const lock = await tryAcquireDbLock(engine, syncLockId(f.id));
try {
- const [warn] = await managedSyncMovementEntry.run(ctx) as Array<Record<string, unknown>>;
+ const [warn] = await managedSyncMovementEntry.run(ctx) as unknown as Array<Record<string, unknown>>;
expect(warn).toMatchObject({ name: 'managed_sync_not_moving', status: 'warn', readiness_state: 'degraded', details: { count: 1 } });
expect(warn!.fix).toMatchObject({ argv: ['gbrain', 'sources', 'writer', 'status', '--source', f.id, '--json'], actor: 'agent', consent: [] });
await watch.tick(); await watch.tick();
@@ -291,7 +291,7 @@ describe('doctor managed_sync_not_moving and the serve notice', () => {
await request(f, 'committed', { completedAt: ago(0) });
await watch.tick();
expect(lines[1]).toContain('moving again');
- const [ok] = await managedSyncMovementEntry.run(ctx) as Array<Record<string, unknown>>;
+ const [ok] = await managedSyncMovementEntry.run(ctx) as unknown as Array<Record<string, unknown>>;
expect(ok).toMatchObject({ status: 'ok' });
} finally { watch.stop(); await lock!.release(); }
}), 60_000);
diff --git a/test/writer-status-owner-backends.test.ts b/test/writer-status-owner-backends.test.ts
new file mode 100644
index 0000000000..557ede94bf
--- /dev/null
+++ b/test/writer-status-owner-backends.test.ts
@@ -0,0 +1,160 @@
+/**
+ * #6317 (C1, reporter ask 3): `writer status --json` shows, per running
+ * claim, the owner process's database backends from `pg_stat_activity`,
+ * matched on the `application_name` every gbrain pool starts its connections
+ * with (`gbrain <kind>:<pid>:<nonce8>`), with the statement label, ages,
+ * state and wait event, and says how far the mapping can be trusted
+ * (`backend_visibility`: session, pooled, unavailable). The running claim also
+ * ends with one `next` envelope, carries `last_sql` from the stamp and the
+ * pool numbers from the vendored driver when this process owns the claim.
+ * The doctor check `persistence_pooler_transaction_mode` fires from the
+ * engine's own `prepare: false` mark (the port-6543 convention), never a probe.
+ *
+ * PGLite: the fields exist and read `unavailable`/empty. Postgres
+ * (DATABASE_URL): this process's own connection appears under its name.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { readWriterDiagnostics, readOwnerBackends, claimNextAction } from '../src/core/persistence/diagnostics.ts';
+import { claimOwner, claimPhaseStamp, startClaimPhase, recordClaimSql, sqlLabel, claimTripleText, isOwnerThisProcess, claimStateOf } from '../src/core/persistence/claim-phase.ts';
+import { boundedReads } from '../src/core/persistence/bounded-reads.ts';
+import { consumerIdentity } from '../src/core/persistence/consumer-heartbeat.ts';
+import { gbrainApplicationName } from '../src/core/db.ts';
+import { driverPoolStats } from '../src/core/postgres-engine/pool-stats.ts';
+import { persistencePoolerEntry } from '../src/commands/doctor/checks/persistence-pooler.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const engines: Array<{ engine: BrainEngine; close?: () => Promise<void> }> = [];
+beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push({ engine: lite }); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push({ engine: pg.engine, close: pg.close }); }
+}, 120_000);
+afterAll(async () => { for (const e of engines) { if (e.close) await e.close(); else await e.engine.disconnect(); } });
+
+async function runningClaim(engine: BrainEngine, stamp: string): Promise<string> {
+ const id = `wb-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, `/tmp/${id}`]);
+ const [wt] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees(owner_host_id) VALUES(gen_random_uuid()) RETURNING id::text AS id');
+ const [src] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const token = JSON.parse(stamp).token as string, requestId = randomUUID();
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,authority,intent,intent_bytes,terminal_reservation,
+ state,execution_token,claim_expires_at,claim_phase)
+ VALUES('local_cli','cli:example',$1::uuid,'submit_job',$2,$3::uuid,'notes/p',$4::uuid,'d','{}'::jsonb,'{"kind":"managed_sync_import","path":"notes/p.md"}'::jsonb,1,16384,'running',$5::uuid,now()+interval '30 seconds',$6::text::jsonb)`,
+ [requestId, id, src!.incarnation, wt!.id, token, stamp]);
+ return requestId;
+}
+
+describe('claim stamp identity and last_sql', () => {
+ test('the owner carries the nonce and pid namespace; the stamp carries last_sql; the triple text and the same-process check read them', () => {
+ const owner = claimOwner();
+ expect(owner).toMatchObject({ pid: process.pid, nonce: consumerIdentity().nonce });
+ expect(gbrainApplicationName()).toBe(`gbrain ${owner.kind}:${process.pid}:${owner.nonce!.slice(0, 8)}`);
+ expect(gbrainApplicationName().length).toBeLessThanOrEqual(63);
+ expect(sqlLabel('SELECT r.id FROM persistence_requests r WHERE ...')).toBe('SELECT persistence_requests');
+ expect(sqlLabel(' update "pages" set x=1')).toBe('UPDATE pages');
+ expect(sqlLabel('WITH expired AS (SELECT 1) UPDATE persistence_requests SET state=$1')).toBe('WITH persistence_requests');
+ expect(sqlLabel('SELECT 1')).toBe('SELECT');
+ const clock = startClaimPhase(1_000, undefined, 30_000);
+ recordClaimSql(clock, 'SELECT * FROM pages WHERE slug=$1', 5_000);
+ expect(clock.lastSql).toEqual({ label: 'SELECT pages', at: 5_000 });
+ expect(claimTripleText({ step: 'origin_check', waitingOn: 'db', lastSql: clock.lastSql }, 9_000)).toBe(' step=origin_check waiting_on=db last_sql=SELECT_pages@4s');
+ expect(claimTripleText(undefined)).toBe(' step=none waiting_on=unknown last_sql=none');
+ const state = claimStateOf({ state: 'running', claim_phase: claimPhaseStamp(clock, 'tok'), execution_token: 'tok' }, 9_000);
+ expect(state).toMatchObject({ phase: 'preparing', owner: { pid: process.pid, nonce: owner.nonce }, last_sql: { label: 'SELECT pages', age_ms: 4_000 } });
+ expect(isOwnerThisProcess({ pid: process.pid })).toBe(true);
+ expect(isOwnerThisProcess({ pid: process.pid, nonce: owner.nonce })).toBe(true);
+ expect(isOwnerThisProcess({ pid: process.pid, nonce: 'reused-pid-other-process' })).toBe(false);
+ expect(isOwnerThisProcess({ pid: process.pid + 1 })).toBe(false);
+ });
+
+ test('boundedReads records the statement label on the clock before issuing it (Postgres path with a deadline)', async () => {
+ const seen: string[] = [];
+ const fake = { kind: 'postgres', executeRaw: async (sql: string) => { seen.push(sql); return []; } } as unknown as BrainEngine;
+ const clock = startClaimPhase(Date.now(), undefined, 30_000);
+ await boundedReads(fake, clock).executeRaw('SELECT 1 FROM persistence_requests');
+ expect(seen).toHaveLength(1);
+ expect(clock.lastSql?.label).toBe('SELECT persistence_requests');
+ });
+
+ test('driverPoolStats reads the vendored driver\'s queues and reports null for a driver without the accessor', () => {
+ expect(driverPoolStats({ pool: { max: 10, open: 6, busy: 2, full: 1, reserved: 1, connecting: 0, closed: 0, ended: 0, queued: 3 } })).toEqual({ checked_out: 4, max: 10, waiters: 3 });
+ expect(driverPoolStats({})).toBeNull();
+ expect(driverPoolStats(null)).toBeNull();
+ });
+});
+
+describe('writer status running claims', () => {
+ test('owner.backend[], backend_visibility, next, last_sql and pool per engine', async () => {
+ for (const { engine } of engines) {
+ const clock = startClaimPhase(Date.now() - 20_000, undefined, 120_000);
+ recordClaimSql(clock, 'SELECT id FROM pages WHERE slug=$1', Date.now() - 3_000);
+ clock.step = 'import_screen'; clock.waitingOn = 'db';
+ const requestId = await runningClaim(engine, claimPhaseStamp(clock, randomUUID()));
+ const status = await readWriterDiagnostics(engine);
+ const blocker = (status.blockers as Array<Record<string, any>>).find(b => b.request_id === requestId)!;
+ expect(blocker).toBeDefined();
+ const claim = blocker.claim;
+ expect(claim).toMatchObject({ phase: 'preparing', step: 'import_screen', waiting_on: 'db', last_sql: { label: 'SELECT pages' }, owner: { pid: process.pid, nonce: consumerIdentity().nonce } });
+ expect(claim.next).toMatchObject({ code: 'claim_running', fix: { next: 'run', argv: ['gbrain', 'sources', 'writer', 'status', '--source', blocker.source_id, '--json'] } });
+ expect(claim.next.retry_after_ms).toBeGreaterThan(0);
+ expect(claim.next.why).toContain(`pid ${process.pid}`);
+ expect(typeof blocker.next_action).toBe('string');
+ if (engine.kind === 'postgres') {
+ expect(status.backend_visibility).toBe('session');
+ expect(claim.owner.backend_visibility).toBe('session');
+ // This process's own connection is one of the owner's backends: named, labelled, with a state and an age, never the SQL text.
+ const mine = claim.owner.backend as Array<Record<string, unknown>>;
+ expect(mine.length).toBeGreaterThanOrEqual(1);
+ expect(mine[0]!.application_name).toBe(gbrainApplicationName());
+ expect(mine.every(b => typeof b.pid === 'number' && typeof b.state === 'string')).toBe(true);
+ expect(mine.some(b => String(b.statement ?? '').startsWith('SELECT'))).toBe(true);
+ expect(JSON.stringify(mine)).not.toContain('pg_stat_activity WHERE');
+ expect(claim.pool).toMatchObject({ max: expect.any(Number), checked_out: expect.any(Number), waiters: expect.any(Number) });
+ expect(claim.pool_source).toBe('driver');
+ // An owner that is not this process has no backend here and no pool (no heartbeat row yet).
+ const other = await readOwnerBackends(engine, [{ kind: 'serve', pid: 999_999, nonce: 'nope' }]);
+ expect(other.visibility).toBe('session');
+ expect(other.byOwner.size).toBe(0);
+ } else {
+ expect(status.backend_visibility).toBe('unavailable');
+ expect(claim.owner.backend).toEqual([]);
+ expect(claim.pool).toBeNull();
+ }
+ }
+ }, 60_000);
+
+ test('next: past the ceiling or a wedged owner tells the host admin to restart the named pid; a lapsed claim resumes on its own', () => {
+ const base = claimStateOf({ state: 'running', claim_phase: claimPhaseStamp({ ...startClaimPhase(Date.now() - 700_000), step: 'raw_hash', waitingOn: 'pool' }, 't'), execution_token: 't' })!;
+ const overdue = claimNextAction(base, { reason: 'preparation_overdue', step: 'raw_hash', step_age_ms: 700_000, waiting_on: 'pool', budget_ms: 120_000 }, { budgetMs: 120_000, ceilingMs: 600_000 }, 's', { row: null, live: null });
+ expect(overdue).toMatchObject({ code: 'claim_overdue', retry_after_ms: 0, fix: { next: 'tell_user_to_run', actor: 'host_admin' } });
+ expect(overdue.fix.user_message).toContain(`pid ${process.pid}`);
+ expect(overdue.why).toContain('past the 600s ceiling');
+ const young = claimStateOf({ state: 'running', claim_phase: claimPhaseStamp({ ...startClaimPhase(Date.now() - 10_000), step: 'raw_hash', waitingOn: 'db' }, 't'), execution_token: 't' })!;
+ const wedged = claimNextAction(young, null, { budgetMs: 120_000, ceilingMs: 600_000 }, 's',
+ { row: { host_id: 'h', pid: process.pid, nonce: 'n', pid_ns: null, kind: 'serve', mode: 'full', started_at: '', renewed_at: new Date().toISOString(), restart_required: true, root_barrier_age_ms: null, pool: null, host_json_path: null, persistence_home: null, minted_under: null, version: null }, live: true });
+ expect(wedged).toMatchObject({ code: 'claim_overdue', fix: { next: 'tell_user_to_run' } });
+ expect(wedged.why).toContain('restart_required');
+ const running = claimNextAction(young, null, { budgetMs: 120_000, ceilingMs: 600_000 }, 's', { row: null, live: null });
+ expect(running).toMatchObject({ code: 'claim_running', fix: { next: 'run' } });
+ expect(running.retry_after_ms).toBeGreaterThan(100_000);
+ const lapsed = claimStateOf({ state: 'running', claim_phase: null, execution_token: 't', claim_lapsed: true })!;
+ expect(claimNextAction(lapsed, null, { budgetMs: null, ceilingMs: 600_000 }, null, { row: null, live: null })).toMatchObject({ code: 'claim_lapsed', retry_after_ms: null, fix: { next: 'run', argv: ['gbrain', 'sources', 'writer', 'status', '--json'] } });
+ });
+});
+
+describe('doctor persistence_pooler_transaction_mode', () => {
+ const ctxFor = (engine: unknown) => ({ engine } as unknown as Parameters<typeof persistencePoolerEntry.run>[0]);
+ test('fires from the engine\'s prepare:false mark with a host-admin fix; ok with prepared statements; not applicable on PGLite', async () => {
+ const pooled = { kind: 'postgres', getPoolDiagnostics: () => ({ prepare: false, poolMax: 10 }), connectionManager: { describeMode: () => ({ mode: 'split', direct_host: 'db.example:5432' }) } };
+ const [warn] = await persistencePoolerEntry.run(ctxFor(pooled)) as unknown as Array<Record<string, any>>;
+ expect(warn).toMatchObject({ name: 'persistence_pooler_transaction_mode', status: 'warn', readiness_state: 'degraded', details: { prepare: false, pool_mode: 'split' },
+ fix: { actor: 'host_admin', consent: [], argv: ['gbrain', 'sources', 'writer', 'status', '--json'], verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_pooler_transaction_mode', '--json'] } } });
+ expect(warn!.message).toContain('ClientRead');
+ const session = { kind: 'postgres', getPoolDiagnostics: () => ({ prepare: true, poolMax: 10 }) };
+ expect((await persistencePoolerEntry.run(ctxFor(session)) as unknown as Array<Record<string, any>>)[0]).toMatchObject({ status: 'ok' });
+ expect((await persistencePoolerEntry.run(ctxFor({ kind: 'pglite' })) as unknown as Array<Record<string, any>>)[0]).toMatchObject({ status: 'ok', readiness_state: 'not_applicable' });
+ });
+});