Repository navigation
fix: prevent PostgreSQL connection exhaustion in multi-agent Gateways - #188614
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis PR returns idle PostgreSQL transports after reader use while retaining logical readers and reusing connections across store schemas. Example: A Gateway with 13 agent stores uses a PostgreSQL role limited to 40 connections.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR addresses an evidenced PostgreSQL capacity bug through the existing connection owners, with no actionable code defect found; failing CI checks remain unattributed. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway reader workers acquire admitted agent-store readers, execute PostgreSQL queries through shared I/O workers, and return rows; the changed lifecycle releases physical backends independently of logical reader retention. flowchart LR
A[Gateway history and usage requests] --> B[Reader worker lanes]
B --> C[Admitted logical reader]
C --> D[Exclusive transport]
D --> E[PostgreSQL I O worker]
E --> F[Selected store schema]
D --> G[Bounded idle transport cache]
G --> D
Technical reviewBest possible solution: Retain admitted logical readers while returning idle physical transports through the existing bounded cache and preserving exclusive transactions. Do we have a high-confidence way to reproduce the issue? Current-main source confirms retained per-store connections outside the idle-cache bound, and etzelm supplies a concrete capped Gateway reproduction; this read-only review ran no target code. Is this the best way to solve the issue? The change repairs the lifetime mismatch at existing owners, and its measured alternatives explain why immediate reader closure or schema-bound reuse would impose substantial reconnect costs. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against ab547867cb96. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +57, Tests +223, Docs +25, Other +1. Total +306 across 15 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 30, 2026, 2:57 PM ET / 18:57 UTC. |
|
Merged via squash.
|
|
Posting for the record now that this has merged. Independent bench of this PR on our own data (reporter of #184027). Base = merge-base 3b410a6, PR = 6c199c9. Inert gateway, 13 stores (state, 11 agents, workboard) ported from our production SQLite set to PostgreSQL 17.11, role
|
Restore pre-statement validation for transports cached idle for at least one second after #188614 removed the checkout health check. Timestamp release in the idle cache and carry the validation decision with the first request. Reconnect before borrower SQL if validation fails; preserve burst reuse, observed-error recovery, and exclusive transaction ownership. Fix the terminated-idle reuse regression observed in #188693 CI run 41126168981, PostgreSQL shard 3, job 124306054395: "reconnects after an idle backend is terminated, without reusing the broken backend" failed with PostgreSQL connection lost; outcome unknown. Cover the inclusive idle-age boundary with the existing fixture clock and make the PostgreSQL termination case deterministic. Document the remaining subsecond termination window. No public configuration or schema changes. Validation: PostgreSQL 17.11 reuse suite 20/20 runs (260 test executions), connection suite 26/26, and isolated agent database suite 11/11. Core typed lint, state-logging typecheck, formatting, and whitespace checks pass. Tests have zero net line growth. Two isolated Codex P0-P2 reviews are clean.
|
Follow-up to my earlier comment: the throughput drop I flagged was host noise. I re-ran the bench on the landed commit, and #188614 does not reduce throughput on our data. Arms: f3009a5 (this PR as squashed) vs its parent 5adde05. The landed diff has the same patch-id as the benched head 6c199c9. Same harness, data and RPC mix as before (13 stores, no role connection limit, 6 min idle, then 120 s of read RPCs at concurrency 8). Runs were interleaved base, PR, PR, base, base, PR, base, PR, with the 1-minute load average recorded at the start of each mix. One base run lost its results to a stats overflow in our load driver and was re-run.
Where the chat.history p50 goes (connection churn under concurrent reads)During the 120 s mix, base opened 16 new PostgreSQL sessions in every run. The PR opened 651 to 974 (about 7 to 8 per second) while holding 19 to 20 backends. It also ran 37,080 to 51,046 With
The extra plans are concentrated in the transcript-history reads. The watermark/window read is planned 9,188 times for 39,406 calls, and each of the two active-event reads 8,918 times for 22,701 calls. On base these reads don't appear among the top planning costs, because each store keeps its own connection and its prepared plans. As far as I can tell from the code, |
…openclaw#188614) * fix: bound idle PostgreSQL connections across agent stores * fix: preserve checked-out PostgreSQL failure semantics
Restore pre-statement validation for transports cached idle for at least one second after openclaw#188614 removed the checkout health check. Timestamp release in the idle cache and carry the validation decision with the first request. Reconnect before borrower SQL if validation fails; preserve burst reuse, observed-error recovery, and exclusive transaction ownership. Fix the terminated-idle reuse regression observed in openclaw#188693 CI run 41126168981, PostgreSQL shard 3, job 124306054395: "reconnects after an idle backend is terminated, without reusing the broken backend" failed with PostgreSQL connection lost; outcome unknown. Cover the inclusive idle-age boundary with the existing fixture clock and make the PostgreSQL termination case deterministic. Document the remaining subsecond termination window. No public configuration or schema changes. Validation: PostgreSQL 17.11 reuse suite 20/20 runs (260 test executions), connection suite 26/26, and isolated agent database suite 11/11. Core typed lint, state-logging typecheck, formatting, and whitespace checks pass. Tests have zero net line growth. Two isolated Codex P0-P2 reviews are clean.
…#188614) Backport f3009a5. Co-authored-by: RomneyDa <[email protected]>
What Problem This Solves
An idle multi-agent Gateway using PostgreSQL could exhaust a role's connection limit, breaking history reads, cron maintenance, usage refresh, and memory maintenance.
Fixes #184027
Thanks @etzelm for the report and measurements.
User Impact
Idle reader retention no longer grows by one PostgreSQL backend per store per worker. A 13-store Gateway completed startup, six idle minutes, and all 130 history reads under
CONNECTION LIMIT 40, with zero53300in both server and Gateway logs. SQLite retention, transaction exclusivity, and worker retirement remain unchanged. No configuration or schema change is required.Why This Change Was Made
Logical reader reuse and physical backend retention had the same lifetime. Each worker can retain 64 store scopes, while seven reader lanes own independent pools. Each retained scope pinned its own physical connection, outside the four-entry returned-connection cache. The 30-minute SQLite handle TTL was expensive when the handle represented a server backend. A capped control reproduced 209 server
53300errors and only 42/130 successful history reads; instrumentation attributed the pressure to retained readers, not simultaneous query demand.The existing scope now retains its admitted logical reader and returns its idle transport after the last borrower. The existing isolate cache retains at most two transports across stores, keyed by DSN and timeout settings. The next query lazily switches
search_pathwhen needed; prepared statements retain SQL-text identity and PostgreSQL re-analyzes them after a path change. Host-side transaction status allows local return with no checkout/release message. Failed or unknown status uses the existing worker guard. Active transactions stay exclusive; failed user statements are never replayed.Reconnect-before-query is allowed only on the first request after taking a returned transport. A still-checked-out writer keeps its existing connection-loss behavior. A disconnect that races the next statement reports the existing error rather than replaying that statement.
Accepted edge case: Idle checkout no longer sends main's
SELECT 1validation query. A server-closed socket (restart,idle_session_timeout, or termination) is still recovered before the borrower's first statement through the PostgreSQLerrorevent andreconnectIfIdle. A socket that dies silently within the three-minute idle-cache window instead fails the borrower's first statement; for a writer'sBEGIN, the caller sees an outcome-unknown error. This rare failure is visible and recoverable, and the cache window is shorter than typical NAT/load-balancer idle timeouts.The physical budget is approximately the sum across isolates of checked-out connections + up to two returned transports. Dedicated writers and maintenance owners count as checked out even when PostgreSQL reports them idle. This bounds retention rather than introducing process-wide admission.
Evidence
Synthetic state and agent families both used local PostgreSQL 17. Each store held four sessions with twelve messages, populated through normal store APIs. Real
gateway run --allow-unconfiguredprocesses used isolated state and task ports. A separate observer sampled the role every 500 ms. After ready +30 seconds, +3 minutes, and +6 minutes, the workload issued 130 history reads across all agents plus a usage refresh. Main ran uncapped at role limit 200 for usable latency and peak references; the candidate ran at 40.Zero candidate server/Gateway
53300; all 390/390 reads succeeded in the final 1/13-store replays and the preceding 4-store run. Six-minute idle occupancy stayed at or below 12; the final 13-store burst reached 16 and overall peak 24. An earlier uncapped 13-store candidate peaked at 27. The final simplification restored normal background-worker retirement and repeated the 13-store capacity cell and one-store usage measurement.Warm percentiles exclude the first read wave. One- and four-store rows use interleaved runs on base
3b410a688ebf; the 13-store main reference is from3140acb54221with unchanged connection owners, and the candidate is the final capacity-only replay on3b410a688ebf. The earlier one/four-store candidate used one-second background retirement; the final candidate restores normal retirement. These healthy-workload measurements precede the fault-only checkout recovery guard; its tests preserve the same healthy message/SQL counts. No healthy per-use checkout/release messages remain; data-query counts match main (1087/1133/1290). Final 13-store physical connect p50/p95 was 3.80/14.84 ms during the burst.Latency caveat and accepted tradeoff: this shared 32-CPU host had materially different load between runs. Four-store load was 18.22 on main versus 36.99 on the candidate; main's own one-store p50 varied from 4.7 to 8.5 ms between iterations. The four-store p50 increase was 37.45% (+2.81 ms), while the candidate beat main at one store. Final 13-store warm p50/p95 was +27.7%/+38.9% with load 34.97 versus the reference's 24.86. These are observations, not established code-causal regressions. The maintainer accepted the latency result; the last replay was explicitly capacity-only. Main needed roughly 100 backends for its 13-store numbers.
Usage refresh (
usage.cost): main/candidate was 0.885/1.535 s at one store before restoring retirement, and 0.874/0.772 s at four stores. Final one-store refresh was 0.819 s; final 13-store refresh was 1.476 s versus the 0.834 s reference. The final one-store time was 47% lower than the one-second-retirement candidate and within the main reference; host load still differs, so this is not a causal speedup claim. The final one-store replay also completed 130/130 reads with warm p50/p95 6.39/9.33 ms, three fresh burst connections, and no checkout/release messages.Rejected alternatives and validation
Regressions cover bounded physical backends while retaining logical scopes, no repeated admission, active borrower protection, fake-clock expiry, zero per-use control messages, unknown-status fallback after query failure, A→B→A rows/prepared statements/recovery namespace, terminated-idle recovery, and transaction exclusion. The bounded-backends regression failed on main; the no-message regression failed on the prior implementation.
Validation: the initial 137 focused unit tests passed (99.03 s wall). After the checkout recovery guard, 56 focused unit tests passed (82.01 s), and all 39 tests in the state-owner, agent-owner, reuse, and hydration PostgreSQL suites passed (198.29 s test runner). The unchanged state-owner loss cases caught an over-broad reconnect in the first CI run and now pass alongside cached recovery. Core and affected test typechecks, typed lint (193.53 s), format, local test-line and diff checks pass. The clean uninstrumented
qaRuntimebuild passed in 213.93 s. The complete change passed a full-context isolated Codex review at P0–P2.Test cost:
pnpm test src/infra/postgres-sync/connection.test.ts src/infra/postgres-sync/bridge-prestart.test.ts src/infra/postgres-sync/protocol.test.ts --maxWorkers=1: 82.01 s wall on the same host. The change adds 234 net test lines. Simplification removed the extra retirement policy and timer-dependent test branches; the existing scope, transport, and cache owners carry the fix. Independent isolated Codex review: scoped-clean at P0–P2; no actionable findings.Exact-head CI
All three PostgreSQL conformance shards, the UI E2E shards, and baseline ratchets passed on
6c199c986851715c6437325a7529353375ada918. The effectiveopenclaw/ci-gateis green.The first
build-artifactsattempt timed out after 120 seconds while generating bundled root help inwrite-cli-startup-metadata. The same head's isolated bundled root-help render passed in 3.81 seconds, and scheduled main passed the corresponding build step. One maintainer-authorized failed-job rerun passed the full artifact job and CI gate with no source change or timeout increase, consistent with the diagnosed runner-load flake.