Skip to content

perf(database): reuse PostgreSQL connections per worker - #175146

Merged
steipete merged 2 commits into
mainfrom
pgprep/pg-conn-reuse
Oct 17, 2026
Merged

steipete merged 2 commits into
mainfrom
pgprep/pg-conn-reuse

Conversation

@steipete

@steipete steipete commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated existing-state opens during PostgreSQL memory indexing create a new bridge worker and authenticated backend each time.

User Impact

Short state reads and one-shot writes can reuse an idle backend within their worker instead of paying connection establishment and session setup on every open. Each caller still receives its own logical handle and exclusive transport lease. No configuration, dependency, schema, or SQLite behavior changes.

Why This Change Was Made

An opt-in, four-entry idle transport cache is keyed by the DSN identity, namespace, store ID, and session timeouts. Taking an entry removes it from the cache. Active transactions are discarded on close, including transactions discovered through PostgreSQL's server status rather than the caller's local flag. An idle liveness check reconnects a failed backend before handing it out; application statements are never replayed. Session setup runs only on physical connection establishment, and cached transports close when their worker exits.

Only the existing-state PostgreSQL open path opts in. The common engine changes are an optional forwarding field in contract.ts/open.ts and its consumption in the PostgreSQL branch of adapters.ts. Existing Gateway ownership and transaction advisory-lock code are unchanged. The PR wrapper source inventory also retains the new helper so extracted wrappers remain complete.

Evidence

Homebrew PostgreSQL 17 with pgvector, pg_trgm, and unaccent; throwaway databases; 257 synthetic files, 5,633 chunks, deterministic four-dimensional embeddings. Logical open requests, physical backends, and setup statements are counted separately. Backend counts are cross-checked against PostgreSQL connection logs, and pg_stat_activity reports zero remaining workload clients after the measured head process exits.

Metric Base (6d578912da6) Candidate (b74a6c0bf5b)
Logical connect requests 263 263
Unique bridge backends 263 7
Setup statements 789 21
Forced index wall time 219.734 s 153.289 s
20 warm lexical searches 5.836 s 3.775 s

Counts cover preparation, manager acquisition, indexing, search, and close; the index wall time measures the forced sync() itself. Both runs completed with exactly 257 files and 5,633 chunks, full-text rows, and vectors. PostgreSQL's authorized-connection log independently counted 263 versus 7 workload backends. After process exit, pg_stat_activity showed zero remaining workload clients in both databases. pg_stat_database.sessions, including diagnostic clients, recorded 285 versus 28 at the final observation.

Twenty warm lexical searches took 5.836 s on base and 3.775 s on the candidate, with no new connections or setup statements in that phase. The index wall time fell about 30% in this pair; concurrent host build load makes the connection/setup reduction the stronger result than the single-pair timing. First-search timings were slower on the candidate: lexical 139 ms versus 293 ms, hybrid 223 ms versus 693 ms. These noisy timings do not establish a general search-latency improvement. This is a local loopback benchmark, not a measured WAN latency claim.

Passed: canonical memory indexing and lexical/hybrid search; standalone Node checks through the real connection class for idle reuse, exclusive concurrent transactions, rollback on close, server transaction status, namespace separation, and reconnect after pg_terminate_backend; SQLite adapter smoke (same native connection, commit and rollback); core typecheck and targeted lint; independent Codex autoreview with no actionable P0–P2 findings. Formatting and git diff --check are clean. The change adds/removes 197/25 production lines, 108/1 test lines, seven documentation lines, and one wrapper-inventory line. No pool library or dependency was added.

CI initially found the missing wrapper-inventory dependency; that one-line repair passed independent review, all three static import-closure checks, and 22 tests across the two closure suites. The local provisioning suite timed out in its first case at the existing 120-second limit; the corresponding final-head CI suite has now passed. Neither the local timeout nor the earlier failed attempts are counted as passing local tests.

Final-head CI run passed at b74a6c0bf5baa7eee44250409c2a74eb3f7dfee8 (56 successful jobs). PostgreSQL conformance actually ran and passed: 413 tests across 75 files and seven Vitest shards, including all four new live reuse cases. The exact command was node scripts/test-database-conformance.mjs --engine postgres --connection <throwaway-dsn>. Schema parity checks also reported zero unexplained differences. ClawSweeper reviewed this head with no actionable findings; the remaining Gateway end-to-end proof limitation is explicit below.

Full Gateway proof is blocked on the base too: fresh isolated Gateway startup fails with PostgreSQL cannot use SQLite repair on both 6d578912da6 and the candidate. Consequently, two fully running Gateways and duplicate-store refusal are not claimed here; lower-level namespace/transaction and connection-recovery proof is recorded above. Earlier attempts also encountered host connection timeouts and a CLI build-publication service-inspection refusal. No live service was modified, and no test or production timeout was relaxed.

Retain exclusive idle bridge transports for existing-state PostgreSQL opens. Preserve transaction ownership, discard broken sessions, and close cached backends with the worker lifecycle.
@clawsweeper

clawsweeper Bot commented Oct 17, 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 17, 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-17T05:24:15.990938Z f8faf4d PR opened
ℹ️ 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: M labels Oct 17, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 17, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 17, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses idle PostgreSQL bridge connections for existing-state operations while preserving exclusive logical handles.

Example: Index 257 synthetic files containing 5,633 chunks using PostgreSQL.

  • Before: The reported baseline opened 263 physical backends and executed 789 setup statements.
  • After: The reported candidate opened 7 physical backends and executed 21 setup statements for the same workload.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused optimization with real PostgreSQL boundary coverage, green exact-head CI, and no actionable findings.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate. The body reports canonical memory indexing/search on PostgreSQL 17 and real-client lifecycle probes; exact-head conformance execution is verified. Full Gateway startup remains blocked on base and head, so multi-Gateway behavior is not claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: PostgreSQL memory indexing repeatedly pays worker startup, authentication, and session setup costs for short state operations.
Reason: The feature-history owner authored this narrow optimization, and the recorded workload shows substantially fewer physical connections with unchanged indexing results.

Merge readiness

✅ Ready for maintainer review

This PR provides a useful PostgreSQL performance improvement, with green exact-head CI and no actionable defects found.

Priority: P2
Reviewed head: b74a6c0bf5baa7eee44250409c2a74eb3f7dfee8

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: A completed shipped Gateway flow is not supplied because startup fails on both base and head; the new live reuse tests also lack a recorded pre-fix failure run.
Agent review details

How this fits together

Existing-state readers and one-shot writers open engine-neutral handles; the PostgreSQL adapter leases a bridge worker that executes SQL against the selected store namespace.

flowchart TD
  A[State reader or writer] --> B[Existing state opener]
  B --> C[Database engine adapter]
  C --> D[Exclusive logical connection]
  D --> E[Worker local idle cache]
  D --> F[PostgreSQL bridge worker]
  E --> F
  F --> G[PostgreSQL store]
Loading

Technical review

Best possible solution:

Retain the focused transport cache within the existing connection owner and preserve current admission, transaction, and publication contracts.

Do we have a high-confidence way to reproduce the issue?

Current-main source constructs a fresh bridge worker and PostgreSQL client for each open; the reported base/head indexing workload independently measures the resulting connection churn.

Is this the best way to solve the issue?

A bounded cache of exclusively leased transports addresses connection setup overhead without pooling active handles, replaying statements, or creating another database-state owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against dca14adbd870.

Provenance checked

  • PostgreSQL bridge and logical connection lifecycle changes intended behavior with a stated reason (5e78ec6: The original PostgreSQL pilot used a dedicated bridge to own its client while preserving synchronous kernels, transaction isolation, and uncertain-outcome handling.)
  • Generic engine admission and shared-state cleanup keeps the original intent (58c0073: The existing state acquisition owner retains the selected engine connection and native anchor with paired cleanup; this PR retires logical handles while allowing only their idle transport to survive.)
  • Recovery-generation transport keeps the original intent (407c309: Exact updater rollback requires generation inspection and locking through the existing engine connection; those operations and their transaction owner remain unchanged.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduction and current main: The introduced diff adds transport reuse only to existing-state PostgreSQL opens; fetched main still creates a bridge worker for every logical connection. (src/state/openclaw-state-db-engine.ts:252, b74a6c0bf5ba)
  • Exclusive reuse and transaction retirement: Taking a cached bridge removes it from the cache; keys include the connection string, namespace, store identity, and session timeouts. Release requires PostgreSQL's idle transaction status, and reconnect occurs before application statements. (src/infra/postgres-sync/bridge.worker.ts:85, b74a6c0bf5ba)
  • Exact-head CI verified: CI run 39007043134 completed successfully at the reviewed head with 56 successful jobs; the PostgreSQL service startup, conformance execution, and service shutdown steps all succeeded. Raw log retrieval was blocked by the artifact host allowlist, so the reported 413-test total was not independently recounted. (b74a6c0bf5ba)
  • Updated workload evidence: The full current body records a PostgreSQL 17 memory-index workload with unchanged file/chunk results, independently counted backend reductions, and zero remaining workload clients after process exit. (b74a6c0bf5ba)
  • Feature ownership and original intent: History traces the bridge to feat: experimental PostgreSQL engine for the workboard store #169214 and subsequent adapter, state-owner, and rollback work by steipete; this PR preserves the original exclusive transaction, publication, and no-replay contracts. (src/infra/postgres-sync/connection.ts:71, dca14adbd870)
  • Owner-approved optional SDK extension: The existing worker SDK exports openEngineStore, whose options gain an optional reuse field. The maintainer-authored direction explicitly limits reuse to opted-in existing-state opens and accepts retaining up to four idle transports per worker; existing callers retain their behavior. (src/plugin-sdk/database-engine-worker-runtime.ts:2, b74a6c0bf5ba)

Likely related people:

  • Peter Steinberger: Raw commit 5e78ec6 adds src/infra/postgres-sync/connection.ts:49 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)

PR surface

Source +172, Tests +107, Docs +7, Other +1. Total +287 across 12 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 197 25 +172
Tests 2 108 1 +107
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 12 313 26 +287

Review metrics

Metric Value Why it matters
Production versus test changes Production +197/-25 LOC; tests +108/-1 LOC Production growth implements bounded transport custody, retirement, and shutdown; live tests exercise distinct PostgreSQL lifecycle contracts.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Connection establishment adds demonstrated overhead to experimental PostgreSQL indexing, with limited blast radius.
  • merge-risk: 🚨 compatibility: The exported worker opener gains an optional reuse parameter; owner-approved opt-in behavior preserves existing callers and SQLite defaults.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-17T05:57:57.434Z sha b74a6c0 :: needs maintainer review before merge. :: none

Reviewed October 17, 2026, 2:15 AM ET / 06:15 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The body now records the successful final-head CI run, including PostgreSQL conformance: 413 tests across 75 files, with all four live reuse cases passing. The base/head Gateway startup limitation remains explicitly documented.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 17, 2026
@steipete
steipete merged commit 9a35d1a into main Oct 17, 2026
183 checks passed
@steipete
steipete deleted the pgprep/pg-conn-reuse branch October 17, 2026 06:23
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

* perf(database): reuse PostgreSQL connections per worker

Retain exclusive idle bridge transports for existing-state PostgreSQL opens. Preserve transaction ownership, discard broken sessions, and close cached backends with the worker lifecycle.

* build(pr): retain PostgreSQL idle bridge sources
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant