Repository navigation
improve(postgres): reuse prepared statements so PostgreSQL stores stop re-planning every query - #184013
Conversation
Parameterized bridge statements were sent unnamed, so PostgreSQL parsed and planned every call again. Each bridge connection now keeps a bounded LRU of named statements (256, DEALLOCATE on eviction), drops them after DDL it runs, and retries an autocommit statement once when DDL on another connection changed a cached result type. Plan selection stays on PostgreSQL's default. Closes openclaw#183698
|
🦞👀 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: needs maintainer review before merge. What this changesThis PR reuses bounded, connection-local PostgreSQL prepared statements while preserving automatic plan selection and parameterless SQL batches. Example: Execute SELECT id FROM t WHERE id > ? three times with parameter 0 on one connection.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR provides a useful PostgreSQL performance improvement, resolves the prior findings, and now supplies sufficient real-model Gateway proof; no actionable defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherStore owners send SQL and bindings through the synchronous PostgreSQL bridge; its worker owns the database connection and returns rows, transaction status, and mutation information. flowchart LR
A[Store owner] --> B[PostgresSyncConnection]
B --> C[Bridge worker]
C --> D[Connection statement cache]
D --> E[node postgres client]
E --> F[PostgreSQL backend]
F --> B
Technical reviewBest possible solution: Retain bounded statement reuse in the existing connection owner and evaluate forced generic plans separately. Do we have a high-confidence way to reproduce the issue? Current-main bridge code and the pinned driver's preparation logic establish repeated unnamed parsing; the supplied real-PostgreSQL regression reports the intended base failure, but this read-only review executed no target code. Is this the best way to solve the issue? The change removes repeated parsing at the existing physical-connection owner, bounds retained statements, preserves simple-protocol batches and automatic planning, and avoids new configuration or parallel infrastructure. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 46dc8ad71f70. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +97, Tests +37. Total +134 across 2 files. Added test files: 0. View PR surface stats
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 (2 earlier review cycles)
Reviewed October 26, 2026, 10:11 AM ET / 14:11 UTC (Revision 3). |
…sertion Use one SAFETY-documented assertion for node-postgres's parsedStatements map, and say in the cache comment that only parsing is reused; plan choice stays automatic.
|
Addressed both findings in 98582b6: the driver map now uses one typed assertion with a @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Real-model proof added to the PR body (replacing the stub run): same head, isolated Gateway on PostgreSQL 17, seven turns through @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…p re-planning every query (openclaw#184013) * improve(postgres): reuse named prepared statements per bridge connection Parameterized bridge statements were sent unnamed, so PostgreSQL parsed and planned every call again. Each bridge connection now keeps a bounded LRU of named statements (256, DEALLOCATE on eviction), drops them after DDL it runs, and retries an autocommit statement once when DDL on another connection changed a cached result type. Plan selection stays on PostgreSQL's default. Closes openclaw#183698 * improve(postgres): type the driver statement map without a chained assertion Use one SAFETY-documented assertion for node-postgres's parsedStatements map, and say in the cache comment that only parsing is reused; plan choice stays automatic.
Closes #183698
What Problem This Solves
With the PostgreSQL engine, every parameterized store statement is sent as a new unnamed statement and parsed again on each call, so session turn writes spend a large share of each round trip re-preparing the same SQL.
User Impact
User impact: agent and state stores on PostgreSQL commit session turns about 24% faster (one writer and four concurrent writers), with the same results and no configuration change. SQLite is unaffected.
Why This Change Was Made
The bridge worker sent parameterized queries through node-postgres as unnamed statements, which repeat Parse on every execution. Each bridge connection now names its parameterized statements by SQL text, so the server parses each one once per session and reuses the prepared statement afterwards. Plan choice stays automatic: PostgreSQL may keep a generic plan or keep building custom plans per execution, as
plan_cache_mode = autodecides.DEALLOCATEd.search_pathis its store namespace. PostgreSQL re-analyzes a prepared statement whensearch_pathchanges (for exampleSET LOCAL search_pathduring schema verification); the test covers it.0A000 cached plan must not change result type). An autocommit statement is re-prepared and run once more (it failed before executing). Inside a transaction it cannot be retried: that transaction fails once with0A000and the statement is re-prepared on next use. Base never hits this (it re-parses every time), so this is the one new failure mode; it needs a column change on a table while another connection holds a cachedSELECT *-style statement on it in an open transaction. I did not find a path that runs schema DDL against a store a live Gateway is using, but I have not proven there is none.node-postgres has no deallocate API and skips Parse for names in its per-connection
parsedStatementsmap, so the worker removes names from that map whenever it deallocates them (pgis pinned at 8.23.1; the one type assertion for that map carries aSAFETY:note).Open design question: generic plans (not in this PR)
Forcing generic plans gave much more for turn writes in my earlier measurements (one writer 727 → 1,757 turns/10 s, see #183698), but forcing them globally made the memory vector search about 10% slower (50 vs 45 ms), because that query benefits from custom plans. If maintainers want that gain, the options are:
plan_cache_modethat operators choose (no code; affects every query, including search), orSET plan_cache_mode = force_generic_planonly for named statements on hot write paths, keeping search onauto(needs a per-statement opt-in from the store owners).I left this out so this PR is a pure statement-reuse change with default planning.
Evidence
Base
8ad3d6f8922(origin/main). Benchmarks ran atcf802649e15; the current head adds only the typed assertion and comment wording from review (the regression test was re-run on it and passes). The only difference between the two arms issrc/infra/postgres-sync/bridge.worker.ts(base vs this branch), swapped in the same checkout. PostgreSQL 17.11 on a Mac mini (Unix socket, isolated database,synchronous_commit=off).Regression test (
src/infra/postgres-sync/reuse.postgres.test.ts, "parses each parameterized SQL text once per connection and survives DDL elsewhere"), real PostgreSQL:expected +0 to be 1(no prepared statement on the connection after three identical calls)It also checks: the right schema's rows under a changed
search_path, autocommit recovery afterALTER TABLEon another connection, one failure then recovery inside a transaction, and that DDL on its own connection drops the statements.Turn writes through the public owner (
persistSessionTranscriptTurn, two-message turns, gateway database role, agent+state on PostgreSQL), 10 s windows, interleaved base/fix, 6 runs each, 0 errors, load1 3–5:Memory search, no regression with default planning (
scripts/bench-memory-search.mjs, production SQL through the bridge, 20,000 chunks, 100 queries per mode after warmups, 2 runs per arm, interleaved; mean of the per-run p50/p95):All 600 per-query result hashes are identical between base and this PR. (This is the cost that forcing generic plans globally made worse, so it was the regression to check.)
For context, the turn round-trip work in #182810 measured bridge transport at 0.03–0.07 ms per trip on the same base (comment). That leaves per-statement parse (and planning) as the remaining per-trip cost; this removes the repeated parse.
Shipped entry point, isolated Gateway, real model (CLI built from this head,
OpenClaw 2026.10.7 (98582b6); a fresh state dir with thestateandagentfamilies on PostgreSQL 17.11 over a Unix socket, isolated database and role;openclaw doctor --fix --non-interactivecreated the schemas;openclaw gateway runon a loopback port with token auth; every turn sent withopenclaw agent --agent main --session-id named-proof-real --message …through the Gateway). The model isanthropic/claude-haiku-5-5served through the bundledanthropicplugin's Claude Code CLI backend (agentRuntime: { id: "claude-cli" }), a real hosted model; the Gateway log showscli turn: provider=claude-cli model=claude-haiku-5-5for each turn. Timestamps are local, replies are verbatim:The only SQLite files in that state dir are the 8 KB anchors that PostgreSQL-backed stores keep; the transcript exists only in PostgreSQL.
Other checks: the
src/infra/postgres-sync,src/infra/database-engineandsrc/statePostgreSQL suites on real PostgreSQL pass, including the Doctor version-migration rollbacks. The only failures were 9 tests that needCREATE DATABASE/CREATE ROLE, which my test role lacks (they fail in setup).pnpm tsgo:core,pnpm tsgo:core:test, oxlint and oxfmt on the touched files pass.An independent automated review of the branch found no actionable issues; its one open question (anything else deallocating statements behind the cache, such as
DISCARD ALL) does not apply: nothing insrc/orextensions/issuesDISCARDorDEALLOCATEbesides this worker.Not measured: provider transports other than the Claude Code CLI backend, a Gateway running for hours (server memory per backend is bounded by the 256 limit, but I have not watched it over a long run), and PostgreSQL versions other than 17.
Simplification pass: an earlier draft had a separate
statement-cache.tsmodule plus a unit test against a fake server. I folded the cache into the bridge worker that owns the connection and dropped the fake-server test in favor of the single real-PostgreSQL regression test. Delta vs merge base: +98/-1 production lines in one file, +37 test lines in an existing suite.