Skip to content

fix: prevent PostgreSQL connection exhaustion in multi-agent Gateways - #188614

Merged
steipete merged 2 commits into
mainfrom
pgprep/pgconn
Oct 30, 2026
Merged

steipete merged 2 commits into
mainfrom
pgprep/pgconn

Conversation

@steipete

@steipete steipete commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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 zero 53300 in 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 53300 errors 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_path when 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 1 validation query. A server-closed socket (restart, idle_session_timeout, or termination) is still recovered before the borrower's first statement through the PostgreSQL error event and reconnectIfIdle. A socket that dies silently within the three-minute idle-cache window instead fails the borrower's first statement; for a writer's BEGIN, 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-unconfigured processes 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.

Stores Main peak / startup peak Candidate peak / startup peak Main idle +30s / +3m / +6m Candidate idle +30s / +3m / +6m
1 19 / 13 18 / 12 19 / 12 / 9 18 / 10 / 8
4 43 / 32 18 / 16 43 / 22 / 22 18 / 15 / 11
13 101 / 70 24 / 24 96 / 39 / 49 21 / 14 / 12

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.

Stores Main warm history p50 / p95 (ms) Candidate warm p50 / p95 (ms) Burst fresh connections, main → candidate Candidate path switches
1 8.48 / 25.64 5.53 / 12.94 4 → 3 0
4 7.51 / 14.92 10.32 / 14.31 11 → 4 270
13 26.99 / 48.47 34.47 / 67.32 30 → 5 309

Warm percentiles exclude the first read wave. One- and four-store rows use interleaved runs on base 3b410a688ebf; the 13-store main reference is from 3140acb54221 with unchanged connection owners, and the candidate is the final capacity-only replay on 3b410a688ebf. 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
  • Immediate logical-reader release met capacity but lost admission/schema reuse and caused 13-store history p50/p95 of 6.57/12.51 seconds.
  • Short logical-scope TTLs and fallback-only release still hit the 40-connection startup cap (33 server errors in the final TTL experiment).
  • Separating logical/physical ownership while keeping schema-bound transports met capacity, but caused 312 fresh burst connections versus 30, and warm p50/p95 144.23/232.65 ms versus 55.99/149.31 ms.
  • Schema-switching reuse cut the 13-store burst to five fresh connections. Removing the remaining per-use checkout/release messages then removed 359/358 bridge messages at 13 stores. The one-second retirement override was also removed after the final capacity check passed.

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 qaRuntime build passed in 213.93 s. The complete change passed a full-context isolated Codex review at P0–P2.

pnpm test src/state/openclaw-agent-db-readonly-scope.test.ts src/config/sessions/session-transcript-read-pools.test.ts src/config/sessions/session-transcript-worker-lanes.test.ts src/infra/postgres-sync/connection.test.ts src/infra/postgres-sync/bridge-prestart.test.ts src/infra/postgres-sync/protocol.test.ts src/infra/sql-connection.test.ts src/infra/sqlite-database-admission.retention.test.ts src/config/sessions/session-entry-publication-source.test.ts --maxWorkers=1
node scripts/test-database-conformance.mjs --engine postgres --connection <isolated-dsn> -- src/state/openclaw-state-db.postgres.test.ts src/state/openclaw-agent-db.postgres.test.ts src/infra/postgres-sync/reuse.postgres.test.ts src/infra/postgres-sync/transcript-hydration.postgres.test.ts
pnpm tsgo:core

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 effective openclaw/ci-gate is green.

The first build-artifacts attempt timed out after 120 seconds while generating bundled root help in write-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.

@clawsweeper

clawsweeper Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T19:18:46.728865Z 6c199c9 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Oct 30, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 30, 2026
@clawsweeper

clawsweeper Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: The reported capped control produced 209 connection-limit errors and completed 42 of 130 history reads.
  • After: The reported final replay peaked at 24 connections and completed all 130 history reads without connection-limit errors.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful lifecycle repair with relevant Gateway measurements and distinct regression coverage; CI failure attribution is incomplete.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied public measurements exercise real isolated PostgreSQL 17 Gateways through startup, six idle minutes, history reads, and usage refresh; final 13-store replay stayed below the 40-connection limit with all reads successful and no 53300 errors.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Multi-agent PostgreSQL Gateways can exhaust server connection capacity while idle, causing history and maintenance operations to fail.
Reason: The reported failure is concrete, the repair preserves existing owners and configuration, and maintainer authorship plus the recorded acceptance settles the direction and latency tradeoff.

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
Reviewed head: 4d34636e96bd1495e4851c98934843e3c6a55bf1

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway 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
Loading

Technical review

Best 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

  • Retained logical reader lifetime changes intended behavior with a stated reason (1e2d50c: Agent stores adopted the selected database engine while retaining the existing reader lifecycle; earlier SQLite retention avoided repeated handle setup.)
  • Transport reuse identity and idle validation changes intended behavior with a stated reason (9a35d1a: perf(database): reuse PostgreSQL connections per worker #175146 reused exclusive idle backends with schema-bound keys and checkout validation to avoid repeated authentication; this PR explicitly replaces schema binding with request-time switching and documents the disconnect race.)
  • Prepared bridge identity keeps the original intent (029ca2b: Prepared transports overlap worker initialization without connecting early; the separate prepared key preserves exact schema and store matching.)
  • Idle transport expiration keeps the original intent (238ded8: Quiet returned connections expire after three minutes while checked-out transports remain protected; this PR preserves that lifetime and lowers retained capacity.)
  • Prepared-statement reuse keeps the original intent (f7d9d71: SQL-text identity avoids repeated planning, with PostgreSQL reanalysis after search-path changes; the new cross-schema regression exercises that existing contract.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5e78ec6 adds src/infra/postgres-sync/connection.ts:34 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5e78ec6881c2; files: src/infra/postgres-sync/connection.ts)
  • Mitchell Etzel: Raw commit f7d9d71 adds src/infra/postgres-sync/bridge.worker.ts:56 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f7d9d711f86d; files: src/infra/postgres-sync/bridge.worker.ts)

PR surface

Source +57, Tests +223, Docs +25, Other +1. Total +306 across 15 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 172 115 +57
Tests 6 250 27 +223
Docs 1 39 14 +25
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 15 462 156 +306

Labels

Label changes:

  • add P2: PostgreSQL connection exhaustion breaks history reads and maintenance for multi-agent installations, with no demonstrated data loss or process crash.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: PostgreSQL connection exhaustion breaks history reads and maintenance for multi-agent installations, with no demonstrated data loss or process crash.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Determine the causes of the failed test-line ratchet and UI gutter checks before landing.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 30, 2026, 2:57 PM ET / 18:57 UTC.

@steipete
steipete merged commit f3009a5 into main Oct 30, 2026
242 of 246 checks passed
@steipete
steipete deleted the pgprep/pgconn branch October 30, 2026 20:09
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@etzelm

etzelm commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

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 openclaw_runtime. pg_stat_activity sampled every 2 s. Each arm: fresh DB from the same template, startup, 6 min idle, then a read-only RPC mix for 120 s at concurrency 8 (sessions.list, chat.history, sessions.search, workboard, config, agents).

Runtime backends base, no limit PR, no limit PR, CONNECTION LIMIT 40 base, CONNECTION LIMIT 40
Startup peak 98 29 31 40 (cap), startup failed
After 6 min idle 73 17 17 -
Under the mix, max / median 87 / 76 20 / 19 20 / 19 -
53300 (server log) 0 0 0 6 / 6 / 13
Requests OK / errors 48,770 / 0 43,566 / 0 44,346 / 0 -
  • With the limit, base failed to start 3 of 3 times (Gateway failed to start: ... 53300 too many connections for role). The PR started, idled and served the full mix with 0 errors and 0 53300 in both server and gateway logs.
  • The PR needs about 75% fewer backends at idle (17 vs 73) and holds flat around 19 to 20 under load.
  • Possible cost, worth checking: throughput fell from 406.2 rps (base) to 362.8 rps (PR, same conditions) and 369.4 rps (PR, capped). chat.history p50 rose from 19.7 to 23.5 ms (p99 140.0 to 158.5). sessions.search p50 was 73.2 vs 76.2 ms. Lists and config were within about 0.3 ms.
p50 / p99 ms, no limit base PR
all ops 8.37 / 137.8 9.06 / 148.1
chat.history 19.7 / 140.0 23.5 / 158.5
sessions.search 73.2 / 202.6 76.2 / 201.8
  • Gateway CPU under the mix was 178.5% (base) vs 169.6% (PR), and RSS was 3.0 vs 2.9 GB. One run per arm on a shared Mac Studio (load average 2.5 to 9). The throughput gap showed up in both PR runs. Our earlier runs of the same mix on this host ranged from 350 to 370 rps, so we can't separate it from noise with one run per arm.

steipete added a commit that referenced this pull request Oct 30, 2026
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.
@etzelm

etzelm commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

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.

Run Arm Load avg at mix start rps all p50 / p95 ms chat.history p50 / p95 ms
1 base 35.0 479.8 5.86 / 74.0 13.53 / 87.3
2 PR 12.6 732.8 4.55 / 48.5 10.45 / 47.5
3 PR 4.3 942.9 3.78 / 38.5 9.07 / 22.3
5 base 3.6 1,015.3 3.53 / 38.3 7.64 / 18.6
6 PR 3.3 1,018.1 3.50 / 35.6 8.41 / 20.5
7 base 5.5 1,025.5 3.49 / 36.5 7.73 / 20.3
8 PR 5.5 1,021.9 3.51 / 36.0 8.34 / 19.6
  • Throughput follows host load, not the arm. At matched low load (runs 5 to 8) base and PR land within 1% of each other: 1,015 / 1,026 vs 1,018 / 1,022 rps. Our earlier 406 vs 363 rps came from one run per arm at load 2.5 to 9.8 on a busy host. Errors and 53300s were 0 in every run.
  • One small effect is consistent: chat.history p50 is about 0.6 to 0.8 ms higher on the PR in every comparable run (8.3 to 9.1 vs 7.6 to 7.7 ms), while its p95 is about the same. At matched load every other op is within 0.15 ms between arms or faster on the PR (agents.list by 0.2 to 0.5 ms, sessions.search by 1 to 3 ms).
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 SELECT set_config(search_path) switches, about 0.4 per RPC.

With pg_stat_statements.track_planning on (one run per arm, load about 6.5):

120 s mix base PR
Statement calls 546,199 568,219
Plans 41,780 176,708
Plan time 3.5 s 13.7 s
Exec time 194.7 s 192.1 s

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, postgresBridgeReuseKey no longer includes the schema or store. retainIdlePostgresBridge closes any idle bridge already held under the same key (idle-bridges.ts:59-63). So with one connection-settings key, an isolate keeps at most one returned transport rather than two. When two read scopes in the same worker overlap, the second opens a fresh backend, and the older one is closed on release. The next read then starts on an empty plan cache or switches search_path, which also forces re-planning of its named statements. Keeping a small number of returned transports per key, rather than one, would probably remove most of this churn, but I haven't tested that. The backend savings are the main win of this PR, and the remaining cost is well under a millisecond at p50.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 31, 2026
…openclaw#188614)

* fix: bound idle PostgreSQL connections across agent stores

* fix: preserve checked-out PostgreSQL failure semantics
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 31, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants