Repository navigation
Conversation
- 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.
|
🦞👀 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. |
…y-txn # Conflicts: # src/infra/postgres-sync/bridge.worker.ts
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherDatabase 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
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +39, Tests +32. Total +71 across 4 files. Added test files: 0. View PR surface stats
LabelsLabel 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 31, 2026, 2:58 AM ET / 06:58 UTC (Revision 2). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
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 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 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. |
Related: #182810, #176626
What Problem This Solves
On the PostgreSQL engine, every read snapshot sends
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLYas 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.
PostgresSyncConnectionnow 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.readRecoveryGenerationsends 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
f2541ec2faf9and from its merge base on main9f14244a6067(the two trees differ only in the 4 files of this PR). The reportedbuildIdconfirms the arm in every run.Setup (Mac Studio, Node 24, scratch PostgreSQL 17 over a Unix socket):
sessions.create) with 40chat.injectmessages each, plus 30 workboard cards. No private data.NODE_OPTIONS=--import, every thread). It wrapsMessagePort.prototype.postMessageand counts bridge commands.PostgresSyncConnection.request()posts exactly one per blockingAtomics.waitround trip, so one counted message equals one blocking round trip. It records how many query requests carrybegin, how many are a loneBEGIN, and how many areROLLBACK.ts,snapshotAtand the per-processepochUUID, 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):
BEGINbeginROLLBACKchat.history(limit 100, 40 messages)9f14244a606798a362757e788335...chat.history(limit 100, 40 messages)f2541ec2faf998a362757e788335...agents.list41729f786c5bf84c...agents.list41729f786c5bf84c...sessions.list,workboard.boards.list,workboard.cards.listworkboard.cards.stats7f4df2ca8db1c45c...Each run printed this per-RPC summary (excerpt;
distinct= number of different response hashes across the 200 calls):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.historyopens 2 snapshots: 8 to 6;agents.listopens 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.historycall per arm withlog_min_duration_statement = 0(timestamps, backend pid, duration;set_config/validation lines omitted, statement text cut):With this PR,
BEGINreaches the server together with the snapshot's first statement instead of one bridge round trip earlier. The statement sequence matches line for line;agents.listmatches too.On this loaded host the per-RPC p50 did not separate the arms (for example
chat.history3.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)
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.
The single-statement ones include all 5,704
session_pending_inputscounts, 3,744 of the 10,239 session window reads, and allagent_provenance,user_profilesandupdate_runslookups. 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
PostgresSyncConnectionbridge, on the ported data): the hottest single-statement snapshot read (session_pending_inputscount), alternating 4 s phases ofrunSqliteReadSnapshotSync(read)and the bare statement. One connection per process, 3 interleaved rounds per arm. The host's load average was 22 to 67.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 withbeginand 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).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 flagsprepareClientPluginNodeCapabilitiesinsrc/gateway/plugin-node-capability.ts. That file isn't touched here, and the export is already on main.Not changed / follow-ups