Skip to content

improve(postgres): one fewer blocking round trip per read snapshot - #188952

Closed
etzelm wants to merge 2 commits into
openclaw:mainfrom
etzelm:perf/pg-r2-l4-readonly-txn
Closed

etzelm wants to merge 2 commits into
openclaw:mainfrom
etzelm:perf/pg-r2-l4-readonly-txn

Conversation

@etzelm

@etzelm etzelm commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Related: #182810, #176626

What Problem This Solves

On the PostgreSQL engine, every read snapshot sends BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY as its own blocking bridge request before its first statement. Most snapshots run only one statement, so a one-row read costs three blocking requests (BEGIN, statement, ROLLBACK) instead of one.

User Impact

PostgreSQL read paths (session lists, history, pending-input reads, workboard reads) spend less time blocked in Atomics.wait. A one-statement snapshot read drops from about 0.98 ms to 0.54 ms at p50 on our ported data. Results are unchanged. SQLite is unaffected.

Why This Change Was Made

Under REPEATABLE READ, PostgreSQL takes the snapshot at the transaction's first statement, not at BEGIN. Sending BEGIN together with that first statement therefore leaves every snapshot's view unchanged. PostgresSyncConnection now holds a lone read-only BEGIN and attaches it to the next query request, and the bridge worker runs it just before the statement. A snapshot that ran no statement skips both BEGIN and ROLLBACK. readRecoveryGeneration sends a pending BEGIN first. Write transactions, savepoints and batched BEGINs are untouched.

Callers can't decide this up front: the hottest one (session-pending-input-history.kernel.ts) runs count-then-page and needs the snapshot only when the count is non-zero. So the deferral sits in the connection, not in a per-caller opt-out.

Real behavior proof

Real Gateway on PostgreSQL 17, built from this PR's head f2541ec2faf9 and from its merge base on main 9f14244a6067 (the two trees differ only in the 4 files of this PR). The reported buildId confirms the arm in every run.

Setup (Mac Studio, Node 24, scratch PostgreSQL 17 over a Unix socket):

  • Fresh state with two agents and the workboard plugin, seeded through the Gateway's own RPCs: 20 sessions (sessions.create) with 40 chat.inject messages each, plus 30 workboard cards. No private data.
  • That state is frozen as a template DB plus a copy of the home dir. Every run restores both, boots the Gateway, settles for 20 s, then makes 1 warm-up call plus 200 sequential calls per RPC over one operator WebSocket connection.
  • Runs are interleaved base, head, head, base, base, head. Host load average was 21.8 to 29.7 (other jobs were running).
  • To count blocking bridge requests I used a small preload outside the tree (NODE_OPTIONS=--import, every thread). It wraps MessagePort.prototype.postMessage and counts bridge commands. PostgresSyncConnection.request() posts exactly one per blocking Atomics.wait round trip, so one counted message equals one blocking round trip. It records how many query requests carry begin, how many are a lone BEGIN, and how many are ROLLBACK.
  • Each response payload is hashed after dropping ts, snapshotAt and the per-process epoch UUID, the only fields that differed between calls or between runs of the same arm.

Blocking bridge requests per call (200 calls, counter delta / 200; 0 requests in a 3 s idle window before each run):

RPC Arm Runs Requests/call Lone BEGIN Query with begin ROLLBACK Response sha256 (all 200 calls, all 6 runs)
chat.history (limit 100, 40 messages) main 9f14244a6067 1, 4, 5 8, 8, 8 2 0 2 98a362757e788335...
chat.history (limit 100, 40 messages) this PR f2541ec2faf9 2, 3, 6 6, 6, 6 0 2 2 98a362757e788335...
agents.list main 1, 4, 5 3, 3, 3 1 0 1 41729f786c5bf84c...
agents.list this PR 2, 3, 6 2, 2, 2 0 1 1 41729f786c5bf84c...
sessions.list, workboard.boards.list, workboard.cards.list both 1 to 6 0 0 0 0 identical across arms
workboard.cards.stats both 1 to 6 1 0 0 0 7f4df2ca8db1c45c...

Each run printed this per-RPC summary (excerpt; distinct = number of different response hashes across the 200 calls):

== run 1 base 23:25:00 load { 22.73 28.43 23.21 }
   {"name": "chat.history", "requests": 8, "withBegin": 0, "beginOnly": 2, "rollback": 2, "distinct": 1, "sha": "98a362757e78"}
   {"name": "agents.list", "requests": 3, "withBegin": 0, "beginOnly": 1, "rollback": 1, "distinct": 1, "sha": "41729f786c5b"}
== run 2 head 23:25:47 load { 24.87 27.99 23.33 }
   {"name": "chat.history", "requests": 6, "withBegin": 2, "beginOnly": 0, "rollback": 2, "distinct": 1, "sha": "98a362757e78"}
   {"name": "agents.list", "requests": 2, "withBegin": 1, "beginOnly": 0, "rollback": 1, "distinct": 1, "sha": "41729f786c5b"}

Runs 3 to 6 repeat the same counts and hashes for their arm.

So each snapshot that runs a statement saves exactly one blocking request (chat.history opens 2 snapshots: 8 to 6; agents.list opens 1: 3 to 2), and responses are byte-identical. RPCs that don't open a snapshot are unchanged.

PostgreSQL still receives the same statements in the same order. One cold chat.history call per arm with log_min_duration_statement = 0 (timestamps, backend pid, duration; set_config/validation lines omitted, statement text cut):

main 9f14244a6067
23:31:28.273 [97567] 0.027ms  BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY
23:31:28.275 [97567] 0.007ms  select count("input_id") as "total" from "session_pending_inputs" where ...
23:31:28.275 [97567] 0.266ms  ROLLBACK
23:31:28.286 [97567] 0.039ms  BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY
23:31:28.293 [97567] 0.181ms  select "watermark"."generation", "window"."transcript_updated_at", ...
23:31:28.297 [97567] 0.055ms  select "active"."event_seq", "active"."message_position", ...
23:31:28.298 [97567] 0.123ms  select "active"."event_seq", "active"."message_position", "event"."event_json", ...
23:31:28.299 [97567] 0.128ms  ROLLBACK

this PR f2541ec2faf9
23:32:21.609 [98185] 0.013ms  BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY
23:32:21.609 [98185] 0.003ms  select count("input_id") as "total" from "session_pending_inputs" where ...
23:32:21.609 [98185] 0.102ms  ROLLBACK
23:32:21.618 [98185] 0.028ms  BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY
23:32:21.621 [98185] 0.104ms  select "watermark"."generation", "window"."transcript_updated_at", ...
23:32:21.623 [98185] 0.057ms  select "active"."event_seq", "active"."message_position", ...
23:32:21.624 [98185] 0.124ms  select "active"."event_seq", "active"."message_position", "event"."event_json", ...
23:32:21.625 [98185] 0.124ms  ROLLBACK

With this PR, BEGIN reaches the server together with the snapshot's first statement instead of one bridge round trip earlier. The statement sequence matches line for line; agents.list matches too.

On this loaded host the per-RPC p50 did not separate the arms (for example chat.history 3.67 to 4.14 ms on main vs 3.90 to 4.57 ms here). The latency claim stays with the bridge microbenchmark below, not end to end.

Bridge request counter used for the proof (not part of this PR)
import { writeFileSync } from "node:fs";
import { MessagePort, threadId } from "node:worker_threads";

const dir = process.env.PRR_COUNTER_DIR;
if (dir) {
  const ops = new Set(["connect", "query", "recovery-generation", "release", "close"]);
  const c = { requests: 0, byOperation: {}, query: { total: 0, withBegin: 0, beginOnly: 0, rollback: 0, commit: 0, other: 0 } };
  let dirty = false;
  const file = `${dir}/${process.pid}-${threadId}.json`;
  const flush = () => {
    if (dirty) {
      dirty = false;
      writeFileSync(file, JSON.stringify(c));
    }
  };
  const post = MessagePort.prototype.postMessage;
  MessagePort.prototype.postMessage = function (msg, ...rest) {
    if (msg && typeof msg === "object" && typeof msg.id === "number" && ops.has(msg.operation)) {
      c.requests++;
      c.byOperation[msg.operation] = (c.byOperation[msg.operation] ?? 0) + 1;
      if (msg.operation === "query") {
        const q = c.query;
        q.total++;
        if (msg.begin) q.withBegin++;
        const sql = String(msg.sql ?? "").trim().toUpperCase();
        if (sql.startsWith("BEGIN")) q.beginOnly++;
        else if (sql.startsWith("ROLLBACK")) q.rollback++;
        else if (sql.startsWith("COMMIT")) q.commit++;
        else q.other++;
      }
      dirty = true;
    }
    return post.call(this, msg, ...rest);
  };
  setInterval(flush, 50).unref();
  process.on("exit", flush);
}

Evidence

Setup: real Gateway data (13 stores: state, 11 agents, and a 336-card workboard), ported to PostgreSQL 17.11 over a Unix socket, on a shared Mac Studio. Base is main 00bfbf1f7ca.

How often this happens (every statement logged, 120 s idle plus a 120 s read mix at concurrency 8, 17,988 RPCs): 20,545 read-only snapshots ran.

Statements in the snapshot Snapshots Share
0 261 1.3%
1 11,168 54.4%
2 3,313 16.1%
3 4,660 22.7%
4+ 1,143 5.6%

The single-statement ones include all 5,704 session_pending_inputs counts, 3,744 of the 10,239 session window reads, and all agent_provenance, user_profiles and update_runs lookups. The read mix averages about 1.1 snapshots and 4.9 statements per RPC. This change removes about one of those ~4.9 blocking bridge requests per RPC.

Cost per read (microbenchmark through the real PostgresSyncConnection bridge, on the ported data): the hottest single-statement snapshot read (session_pending_inputs count), alternating 4 s phases of runSqliteReadSnapshotSync(read) and the bare statement. One connection per process, 3 interleaved rounds per arm. The host's load average was 22 to 67.

Concurrency Arm Snapshot read p50 Bare statement p50 Wrapper cost Snapshot reads/s
1 main 0.98 ms 0.31 ms 0.67 ms 452
1 this PR 0.54 ms 0.28 ms 0.26 ms 1,111
8 main 3.81 ms 1.35 ms 2.47 ms 662
8 this PR 1.50 ms 1.08 ms 0.42 ms 1,216

On main the snapshot read costs 3.0 to 3.4x the bare statement at c1 (three requests). With this PR it costs 1.9 to 2.2x (two requests). The c8 rows are noisier: process start spread was 5 to 32 s on the shared host.

End to end, 3 interleaved Gateway runs per arm on the same read mix could not separate the arms on this host. At c1 the median was 75 vs 97 rps, at c8 196 vs 179 rps, and runs of the same arm varied 40 to 50%. I'm not claiming an end-to-end throughput number.

Tests:

  • src/infra/postgres-sync/connection.test.ts: two new cases. One checks that a snapshot sends its first statement with begin and that an empty snapshot sends nothing. The other checks that a failing first statement still rolls back. Red on main (2 failed / 23 passed), green with the change (25 passed).
  • PostgreSQL conformance (scripts/test-database-conformance.mjs --engine postgres): read-facts, reuse, session-publication, transcript-hydration, commit-receipts, session-accessor read-hold, state-read-admission and openclaw-agent-db postgres tests. 8 files / 52 tests pass on main and with the change.
  • pnpm check:changed: everything passes except the Knip production unused-export scan, which flags prepareClientPluginNodeCapabilities in src/gateway/plugin-node-capability.ts. That file isn't touched here, and the export is already on main.
Not changed / follow-ups
  • PostgreSQL still receives BEGIN as its own protocol message, because node-postgres sends one query at a time, so the server-side statement count is unchanged. What this saves is the blocking bridge round trip.
  • The closing ROLLBACK of a non-empty snapshot is still a blocking request. Releasing it without waiting would save another round trip, but it needs ordering guarantees in the bridge and is left out of this change.

- A lone `BEGIN ... READ ONLY` is held by PostgresSyncConnection and sent in
  the same bridge request as the transaction's first statement; the bridge
  worker runs it right before that statement.
- A read snapshot that runs no statement skips both BEGIN and ROLLBACK.
- REPEATABLE READ takes its snapshot at the first statement, not at BEGIN,
  so snapshot semantics are unchanged.
- readRecoveryGeneration sends a pending BEGIN first.
- Saves one blocking bridge round trip per non-empty read snapshot.
@clawsweeper

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

…y-txn

# Conflicts:
#	src/infra/postgres-sync/bridge.worker.ts
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR sends a read-only BEGIN with its first statement and skips empty snapshot transactions.

Example: An agents.list RPC opens one PostgreSQL read snapshot.

  • Before: Three blocking bridge requests.
  • After: Two blocking bridge requests with the same response hash.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with production-entry-point evidence, reported red/green regressions, successful PostgreSQL conformance checks, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Exact-head Gateway RPC output on PostgreSQL 17 demonstrates fewer blocking requests for chat.history and agents.list, matching response hashes, and unchanged server statement ordering; end-to-end latency improvement is explicitly unclaimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: PostgreSQL reads block database workers for a separate BEGIN exchange before executing useful statements.
Reason: The measured bridge-request reduction serves existing read flows without adding configuration, changing stored data, or weakening snapshot consistency.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused, useful reduction in PostgreSQL bridge requests with no actionable correctness findings; exact-head CI passes.

Priority: P2
Reviewed head: f2541ec2faf9a426552c7ed083300c36fa11c36e

Before merge

None.

Findings

None.

Agent review details

How this fits together

Database workers call a synchronous SQL connection that exchanges requests with a PostgreSQL bridge worker and returns decoded rows and transaction status.

flowchart LR
  A[Gateway RPC] --> B[Database worker]
  B --> C[PostgresSyncConnection]
  C --> D[Bridge worker]
  D --> E[PostgreSQL]
  E --> D
  D --> C
Loading

Technical review

Best possible solution:

Keep this connection-owned optimization while preserving the existing snapshot, rollback, schema-selection, and write-settlement owners.

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

Baseline source sends BEGIN through its own blocking request, and the supplied Gateway comparison exercises that path; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The existing connection is the appropriate owner because callers can conditionally issue multiple statements, and the patch removes a bridge exchange without changing the server's statement sequence.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Read-only snapshot lifecycle keeps the original intent (271f240: Use consistent read-only snapshots without broad write invalidation, retaining separate write-receipt ownership.)
  • Idle transport reuse keeps the original intent (f3009a5: Separate logical reader retention from physical PostgreSQL backend retention to prevent connection exhaustion.)
  • Prepared-statement execution keeps the original intent (f7d9d71: Reuse parameterized statements while preserving parameterless batches and transaction-sensitive error handling.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 271f240 adds src/infra/postgres-sync/connection.ts:54 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 271f240ec5a6; files: src/infra/postgres-sync/connection.ts)
  • Mitchell Etzel: Raw commit f7d9d71 adds src/infra/postgres-sync/bridge.worker.ts:99 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 +39, Tests +32. Total +71 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 40 1 +39
Tests 1 32 0 +32
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 72 1 +71

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Reduces synchronous waiting on PostgreSQL read paths while preserving results; no urgent availability or data-integrity failure is established.
  • 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 (1 earlier review cycle)
  • reviewed 2026-10-31T02:15:17.977Z sha f2541ec :: needs real behavior proof before merge. :: none

Reviewed October 31, 2026, 2:58 AM ET / 06:58 UTC (Revision 2).

@etzelm

etzelm commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 31, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 31, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @etzelm for the careful bridge-request measurements and PostgreSQL evidence. Closing after checking the current owner on main and the transaction semantics.

Main already opens read snapshots with one BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY, as introduced in #169214. There is no separate isolation/read-only statement to consolidate. This PR's additional bridge reduction is distinct and has not landed.

Deferring that BEGIN preserves the first-query MVCC snapshot rule, but moves the transaction clock. In an isolated PostgreSQL 17.11 probe, a writer inserted a timestamped row during the interval before the reader's first query. Both eager and deferred arms used repeatable read/read only and saw that row, but WHERE created_at <= CURRENT_TIMESTAMP returned 0 rows with eager BEGIN and 1 with deferred BEGIN. PostgreSQL defines CURRENT_TIMESTAMP/now() at transaction start.

We are keeping the existing transaction-start contract, so this does not fit a semantics-identical round-trip reduction. The measured bridge counts remain useful evidence for #188956. Thank you for making that cost concrete.

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.

2 participants