Skip to content

improve(postgres): reuse prepared statements so PostgreSQL stores stop re-planning every query - #184013

Merged
steipete merged 2 commits into
openclaw:mainfrom
etzelm:feat/pg-named-statements
Oct 30, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
etzelm:feat/pg-named-statements

Conversation

@etzelm

@etzelm etzelm commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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 = auto decides.

  • Bounded: at most 256 statements per connection (pgjdbc's default), least recently used is DEALLOCATEd.
  • Batches unchanged: parameterless SQL keeps the simple protocol, which multi-statement batches need.
  • Schema identity: the cache lives on one connection, whose search_path is its store namespace. PostgreSQL re-analyzes a prepared statement when search_path changes (for example SET LOCAL search_path during schema verification); the test covers it.
  • DDL on the same connection (Doctor migrations) drops every cached statement right after it runs, so later statements in the same migration transaction re-prepare.
  • DDL on another connection can change a cached statement's result type (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 with 0A000 and 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 cached SELECT *-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 parsedStatements map, so the worker removes names from that map whenever it deallocates them (pg is pinned at 8.23.1; the one type assertion for that map carries a SAFETY: 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:

  1. a role- or database-level plan_cache_mode that operators choose (no code; affects every query, including search), or
  2. SET plan_cache_mode = force_generic_plan only for named statements on hot write paths, keeping search on auto (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 at cf802649e15; 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 is src/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:

  • base: fails, expected +0 to be 1 (no prepared statement on the connection after three identical calls)
  • this branch: passes, along with the other 11 tests in the file

It also checks: the right schema's rows under a changed search_path, autocommit recovery after ALTER TABLE on 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:

writers base turns/10 s (median, range) this PR base p50 / p95 ms this PR p50 / p95 ms
1 1,159 (1,127–1,181) 1,440 (1,298–1,594), +24% 8.66 / 12.82 7.09 / 9.92
4 2,839 (2,672–4,016) 3,525 (3,365–3,809), +24% 13.75 / 20.98 11.21 / 15.70

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):

mode base p50 / p95 ms this PR p50 / p95 ms
vector 166.2 / 170.9 166.0 / 169.7
keyword 12.8 / 14.3 12.4 / 13.5
hybrid 180.8 / 184.2 178.7 / 182.8

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 the state and agent families on PostgreSQL 17.11 over a Unix socket, isolated database and role; openclaw doctor --fix --non-interactive created the schemas; openclaw gateway run on a loopback port with token auth; every turn sent with openclaw agent --agent main --session-id named-proof-real --message … through the Gateway). The model is anthropic/claude-haiku-5-5 served through the bundled anthropic plugin's Claude Code CLI backend (agentRuntime: { id: "claude-cli" }), a real hosted model; the Gateway log shows cli turn: provider=claude-cli model=claude-haiku-5-5 for each turn. Timestamps are local, replies are verbatim:

06:57:54  gateway ready (6 s); worker startup state: postgresBridgeCount=4
06:58:00  turn 1  status ok  5.3 s  "READY"
06:58:01  turn 2  status ok  1.5 s  "My previous reply was the word READY."
06:58:02  turn 3  status ok  1.4 s  "Red, Yellow, Blue"
06:58:03  ALTER TABLE <agent schema>.transcript_events ADD COLUMN named_probe int   (separate psql connection, Gateway running)
06:58:04  turn 4  status ok  1.5 s  "I just listed red, yellow, and blue."
06:58:04  ALTER TABLE <agent schema>.transcript_events DROP COLUMN named_probe
06:58:05  turn 5  status ok  1.4 s  "1, 2, 3, 4, 5"
06:58:07  turn 6  status ok  1.5 s  "6"
06:58:08  Gateway SIGTERM (exited after 1 s); gateway run again; ready after 6 s
06:58:20  turn 7  status ok  5.6 s  "READY"        (first reply recalled across the restart)
          transcript_events rows in the agent schema: 15
          Gateway log: 0 lines matching error|0A000|26000 (363 lines across both Gateway lives)
07:00:36  Gateway started a third time: `gateway call sessions.list` returns the one session;
          `gateway call chat.history` returns 14 messages, the seven user/assistant pairs above in order

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-engine and src/state PostgreSQL suites on real PostgreSQL pass, including the Doctor version-migration rollbacks. The only failures were 9 tests that need CREATE 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 in src/ or extensions/ issues DISCARD or DEALLOCATE besides 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.ts module 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.

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
@clawsweeper

clawsweeper Bot commented Oct 26, 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Each execution sends an unnamed statement and repeats parsing.
  • After: All executions return the same rows while sharing one named server statement.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused connection-owned optimization with strong shipped-entry-point proof and no actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The updated body supplies exact-head CLI/Gateway terminal output exercising PostgreSQL state and agent stores with a real model, seven persisted turns, external DDL, Gateway restart, context recall, and ordered history readback; the reported regression and throughput/search comparisons support the changed statement-reuse path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: PostgreSQL-backed session persistence repeatedly parses identical parameterized SQL, adding latency while writers hold the store transaction lock.
Reason: Reported interleaved measurements show approximately 24% higher turn-write throughput with equivalent results and no measured search regression; automatic plan selection remains unchanged.

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
Reviewed head: 98582b66f954b281400adc5ccc00b36f6bda1294

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

  • Physical connection ownership and worker topology keeps the original intent (b378654: Share PostgreSQL I/O workers to reduce process footprint while retaining independent store connections.)
  • Connection reuse and uncertain-write handling keeps the original intent (9a35d1a: Reuse exclusive idle backends without replaying application statements after connection loss.)
  • Mutation classification and scoped receipts keeps the original intent (271f240: Preserve scoped invalidation and transaction settlement while treating schema work conservatively.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main boundary: The pinned introduction adds statement reuse only in the existing bridge worker and one real-PostgreSQL regression case; fetched main retains unnamed client.query execution. (src/infra/postgres-sync/bridge.worker.ts:73, 98582b66f954)
  • Distinct regression coverage: The added case checks statement reuse, search_path isolation, external-DDL recovery in autocommit, transaction failure followed by recovery, and invalidation after local DDL; the author reports the intended base failure and passing head. (src/infra/postgres-sync/reuse.postgres.test.ts:272, 98582b66f954)
  • Updated shipped-entry-point proof: The current PR body supplies exact-head terminal output from an isolated PostgreSQL 17 Gateway with a real hosted model: seven CLI turns, external DDL, restart, recalled context, and history readback; this replaces the earlier stub proof. (98582b66f954)
  • Supported migration boundary: The operator guide requires stopped writers for PostgreSQL schema upgrades, and the Doctor and agent maintenance owners enforce custody; the disclosed failure after external live column changes does not establish a supported upgrade regression. Public docs: docs/gateway/postgresql.md. (docs/gateway/postgresql.md:791, 98582b66f954)
  • Feature history and original intent: History traces the bridge to the PostgreSQL pilot, then connection reuse, scoped receipts, durability preservation, and worker sharing; the change retains those owners and contracts rather than replacing their topology. (src/infra/postgres-sync/bridge.worker.ts:135, b378654d5e8d)
  • Pinned driver contract: OpenClaw directly imports pg and pins 8.23.1, making its protocol implementation relevant: named queries consult parsedStatements, ParseComplete records the name, and submitted-name bookkeeping is cleared on completion or error; the release tag resolves to this commit. (packages/pg/lib/query.js, 0980cefebe0a)

Likely related people:

  • Peter Steinberger: Raw commit b378654 adds src/infra/postgres-sync/bridge.worker.ts:43 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b378654d5e8d; files: src/infra/postgres-sync/bridge.worker.ts)

PR surface

Source +97, Tests +37. Total +134 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 98 1 +97
Tests 1 37 0 +37
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 135 1 +134

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A measured performance improvement for PostgreSQL-backed stores with limited blast radius and no demonstrated urgent availability or correctness failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster 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.

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 (2 earlier review cycles)
  • reviewed 2026-10-26T01:04:18.767Z sha cf80264 :: needs real behavior proof before merge. :: [P2] Replace the chained assertion with precise driver connection typing | [P3] Describe parse reuse without promising a single query plan
  • reviewed 2026-10-26T01:52:43.641Z sha 98582b6 :: needs real behavior proof before merge. :: none

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.
@etzelm

etzelm commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both findings in 98582b6: the driver map now uses one typed assertion with a SAFETY: note (lint:no-chained-type-assertions and check:assertion-safety pass, as do the CI ratchet/boundary jobs), and the comment and body say only parsing is reused while plan choice stays automatic. The body now also has an isolated Gateway run through openclaw agent on PostgreSQL, built from this head: 7 turns, including DDL from another connection while the Gateway was running and a restart. The model was a local stub because no real endpoint was reachable here; that gap is stated in the body.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 26, 2026
@etzelm

etzelm commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Real-model proof added to the PR body (replacing the stub run): same head, isolated Gateway on PostgreSQL 17, seven turns through openclaw agent with anthropic/claude-haiku-5-5 via the Claude Code CLI backend, external DDL mid-run, a Gateway restart, and the history read back with chat.history. No errors, no 0A000/26000.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 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. 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 26, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 28, 2026
@steipete
steipete merged commit f7d9d71 into openclaw:main Oct 30, 2026
141 of 143 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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

Labels

clawtributors PR from a clawtributor 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: S 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.

[Feature]: PostgreSQL bridge re-parses and re-plans every statement; reuse named statements per connection

3 participants