Repository navigation
perf(database): reuse PostgreSQL connections per worker - #175146
Conversation
Retain exclusive idle bridge transports for existing-state PostgreSQL opens. Preserve transaction ownership, discard broken sessions, and close cached backends with the worker lifecycle.
|
🦞👀 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 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherExisting-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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +172, Tests +107, Docs +7, Other +1. Total +287 across 12 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
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 HistoryReview history (1 earlier review cycle)
Reviewed October 17, 2026, 2:15 AM ET / 06:15 UTC (Revision 2). |
|
@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. |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
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.tsand its consumption in the PostgreSQL branch ofadapters.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_activityreports zero remaining workload clients after the measured head process exits.6d578912da6)b74a6c0bf5b)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_activityshowed 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 andgit diff --checkare 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 wasnode 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 repairon both6d578912da6and 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.