Repository navigation
improve(postgres): read each chat history page from one database snapshot - #190001
Conversation
…shot The chat.history page task in the history worker now holds one PostgreSQL read-only snapshot from its first read until the page is assembled, covering the Claude CLI import check and every page and tail-scan read. Each read still passes read-scope admission; a failed read rolls the snapshot back and the next read opens a fresh one. SQLite is unchanged. Related: openclaw#188956
|
🦞👀 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: ready, awaiting a maintainer decision. What this changesThis PR shares one PostgreSQL read-only snapshot across the reads that assemble a chat history page. Example: Request limit 2 from a conversation containing two visible messages separated by 250 silent replies.
Review scores
ProductKind: Performance · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⏳ Ready, awaiting maintainer decision Keep open: this PR provides a distinct, demonstrated PostgreSQL history optimization that current main does not provide. Priority: P2 Decision needed
Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Gateway sends history requests to a serialized transcript worker, whose admitted database readers assemble messages and pagination before returning the encoded page. flowchart LR
A[Gateway history request] --> B[Serialized transcript worker]
B --> C[Existing read scope]
C --> D[PostgreSQL read snapshot]
D --> E[CLI check and page reads]
E --> F[Messages and pagination]
Technical reviewBest possible solution: Preserve page-scoped snapshot reuse while removing the dense-page slowdown, unless the PostgreSQL/history owner explicitly accepts that measured tradeoff. Do we have a high-confidence way to reproduce the issue? Current-main source retains separate read snapshots, and supplied Gateway traces independently demonstrate three or seven transactions for the affected page shapes; no target code was executed during this review. Is this the best way to solve the issue? The scoped hold is a focused implementation using existing transaction and reader owners, but its measured dense-page cost prevents an unconditional performance recommendation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 0c103b02991a. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +87, Tests +146, Other +2. Total +235 across 5 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. 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 (9 earlier review cycles; latest 8 shown)
Reviewed November 11, 2026, 12:50 PM ET / 17:50 UTC (Revision 10). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review The previous re-review run stopped before producing a review ("Review blob metadata was unavailable"). No change since the last request. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review No code change. Rebuilt and retested on current |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review No code change. #188956 is now split: this PR closes #197313 (one read snapshot per history page), and #188956 keeps the history worker sizing that #190129 addresses. |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…shot (openclaw#190001) Read each PostgreSQL chat.history page through one worker-owned read-only snapshot, preserving per-read admission, messages and pagination. Keep SQLite unchanged and rollback/retire failed connections through their existing owners. Patrick-Erichsen instructed landing after disclosure of the network-hop savings and measured dense-loopback throughput/tail-latency regressions; the accepted tradeoff is recorded in the PR. Validation: fresh independent source review and source-qualified Gateway/PostgreSQL behavioral and benchmark proof at their recorded executing revisions; exact-head CI/security/dependency statuses successful. No universal performance improvement is claimed. Co-authored-by: Mitchell Etzel <[email protected]> Co-authored-by: Patrick-Erichsen <[email protected]>
Closes #197313
Related: #188956, #190129 (#188956 tracks the worker queueing in front of
chat.historyon PostgreSQL, which #190129 addresses)What Problem This Solves
On PostgreSQL, some
chat.historypages open a new read-only transaction for each step of the page read instead of one: a sparse page (few visible replies among many silent ones) takes threeBEGIN ... READ ONLY/ROLLBACKround trips over the database bridge, and a Claude CLI session after a provider switch takes seven. When the database is across a network hop, every extra round trip adds to the page's response time.User Impact
User impact: each
chat.historypage on PostgreSQL is read from one database snapshot. Sparse pages and Claude CLI sessions after a provider switch now take one transaction for the page instead of three or seven, which makes those pages faster when PostgreSQL is not on loopback: with about 3.4 ms added round trip, median latency drops by 14 to 26 ms for a sparse page and about 40 ms for a Claude CLI session after a provider switch (see Evidence). Pages that already took one transaction read the same rows with the same SQL, but cost more on a loopback database: the history worker spends about 0.25 ms more per request at 1 and 8 clients, which shows as 9.5 to 12.9% lower throughput alone and 13.5% lower at 8 clients with #190129, with higher p95 and p99 (see the pair bench under Evidence). Returned messages and pagination are unchanged, and SQLite is unchanged.Why This Change Was Made
The history worker runs one task at a time, and no read snapshot outlives a task. The
chat.historypage task now holds one PostgreSQLREPEATABLE READ READ ONLYsnapshot from its first read until the page is assembled. That covers the Claude CLI import check (revision read and, after a provider switch, its tail read) and every page and tail-scan read. Every read still goes through the read scope's admission (acquire), so validation and path checks run per read as before. A failed read rolls the held snapshot back and the next read opens a fresh one. A failed rollback retires the connection, asrunPostgresTransactionSyncdoes, and the snapshot uses the sameBEGINand read-snapshot scope.Scope: this changes the page task only. The pending-input read that the handler issues before the page is its own worker request with its own snapshot, and the history reader cap (#169110) is untouched. It keeps the eager read-only
BEGIN(the deferredBEGINin #188952 was closed unmerged).Scope: this closes #197313 (one read snapshot per history page). The worker queueing in #188956 is separate and is #190129; the two changes touch different files and are measured on their own. This one removes 2 or 6 read-only transactions (4 or 12 round trips) per affected page with no other behavior change.
Accepted decision: PostgreSQL latency tradeoff
On November 13, 2026, @Patrick-Erichsen instructed landing after the network-hop benefits and measured dense-loopback regressions were disclosed in the review and landing discussion. This records acceptance of the current one-snapshot-per-page proposal and its disclosed tradeoff, including one-client throughput of 159.0 to 138.55 calls/s and p99 of 12.85 to 15.84 ms, and eight-client p99 of 26.26 to 55.06 ms when paired with #190129. It is not a universal performance improvement. The linked discussion is for team reference and requires sign-in.
No code or benchmark data changed for this decision. Existing proof keeps its actual executing revisions and the coverage limits below.
Evidence
Evidence files: https://github.com/etzelm/openclaw/tree/assets/pg-r2-l3c-history-snapshot-evidence/current-source (paths below are relative to it;
README.mdthere describes each file). PostgreSQL 17.11, isolated Gateways built withpnpm buildfrom each tree.Original experimental acceptance rule (the dense-loopback exception is explicitly accepted above): through a running Gateway, sparse and Claude CLI provider-switch pages read in one page snapshot with the same reads and messages; with a real network hop, their p50 and p95 drop by roughly the saved round trips times the round trip time; pages that already use one snapshot do not change; no metric moves the wrong way.
Gateway A/B with a network hop (
network-hop/). Base3c130c7268e(this head'smainparent), fix213409bf(same PR source as the current head). The Gateway reaches PostgreSQL through toxiproxy with 1 ms latency toxics on each stream. MeasuredSELECT 1round trip: 0.44 ms without the toxics, 3.77 ms before the runs and 3.85 ms after (network-hop/rtt.txt). The store was seeded through the Gateway's own RPCs. It has a sparse session (1 visible reply, 250 silent replies, 1 visible reply) and a Claude CLI session made by one realchat.sendturn through a stubclaudebinary onPATH(the stream-json stub fromtest/e2e/qa-lab/runtime/reply-run-plugin-reload.product-proof.e2e.test.ts, no API key), followed by 250 silent replies and a visible one, and then switched to the default OpenAI model withsessions.patch. Both uselimit: 2. There were 5 runs per arm in ABBA order (base fix fix base base fix fix base base fix). Each run restores the same database template and boots the arm. It warms, traces 3 calls per session, then runs a 20 s closed-loopchat.historyload per session at concurrency 1 and 8 after a 5 s warmup, with statement logging off. A run starts only when the 1-minute load average is below the 32 cores (network-hop/load-gates.txt).Read-only transactions per call (
network-hop/SUMMARY-snapshots.txt; runs N4 to N10 carry a statement trace, N1 to N3 latency only):Latency, median of the 5 per-run values (range) in ms, no errors in any run (
network-hop/SUMMARY-latency.txt, per run innetwork-hop/runs/*/load-*.jsonwith the 1-minute load recorded at start and end):The sparse page saves 2
BEGINand 2ROLLBACKround trips, about 15 ms at 3.8 ms each, and its p50 drops by 13.85 ms at concurrency 1 and 26.44 ms at concurrency 8. At concurrency 1 the sparse p95 is flat (101.18 vs 103.37, within the run ranges), and at concurrency 8 it drops by 29.68 ms. The Claude CLI page saves 6 and 6, about 46 ms, and its p50 drops by 41.66 and 39.34 ms and its p95 by 62.70 and 63.67 ms. The runs started below the core count, but the 1-minute load during them ranged from 4.3 to 37.0 because the host is shared. No cell got worse beyond its range.Running Gateway statement trace on loopback (
gateway-trace/, previous head27ab37717afvs itsmainparent7c2ff8f775a, same code): sparse session 3.0 vs 1.0 page snapshots (7 x 3 calls per arm, reads 11 = 11); imported Claude Code threads and a 12-sessionlimit: 100shape stay at 1.0 on both arms. On loopback the latency did not move (gateway-trace/SUMMARY-latency.txt), as expected when a round trip costs well under a millisecond.Regression test (new, live PostgreSQL), red on base and green with the change (
tests/conformance-red.log,tests/conformance-green.log). Read-onlyBEGINs for one page, base vs fix: sparse page 3 vs 1, Claude CLI session after a provider switch 7 vs 1. A third test checks that a failed statement inside the held snapshot is rolled back and the next read works.Live PostgreSQL conformance (PostgreSQL 17.11): the new test plus the bridge, read-facts, reuse, publication, hydration, agent and state database suites, 15 files and 165 tests pass on head
213409bf(tests/conformance-green-new-head.log) and again on head5af7f878merged into currentmain10592dacdc6(ci-lanes/conformance-merge-into-main-10592dac.log). Consumer unit tests for the changed modules pass on the previous head, 16 files and 223 tests (tests/unit-fix.log).pnpm check:changedon the previous head merged intomain638a1851e7e(ci-lanes/check-changed-merge-into-current-main.log): typecheck, format, lint (0 errors), Knip (0 unused exports) and the guards pass. The one failure ischangelog attributionson existingCHANGELOG/2026.6.8.mdandCHANGELOG/2026.7.1.mdentries, which fails the same way on thatmain(ci-lanes/changelog-attributions-current-main.log).CI lanes: the red lanes on head
5af7f878came from themainthat CI merged it into (4ca233c908c), not from this branch, which touches noui/files and allocates exactly the 146 test lines it adds.checks-fast-baseline-ratchetsfailed onlytest-lines(over by: 50; net delta: +146,ci-lanes/ci-run-42356893636-excerpt.txt). Plainmain4ca233c908cis already over by 50 with no change at all (ci-lanes/test-lines-plain-main-4ca233c9.log), and the CI merge tree reproduces the CI result (ci-lanes/test-lines-ci-merge-5af7f878-into-4ca233c9.log).mainreconciled the ceiling in fix(ci): clear inherited test budget and unused export failures #194509. Merged into currentmain10592dacdc6,pnpm check:baseline-ratchetspasses all 10 checks (test lines slack 21;ci-lanes/baseline-ratchets-merge-into-main-10592dac.log).checks-ui-e2e (1/2)failed one test,ui/src/e2e/gateway-fresh-visit.http.e2e.test.ts:175("Matcher did not succeed in time"). It fails the same way on plainmain4ca233c908c(ci-lanes/ui-e2e-gateway-fresh-visit-plain-main-4ca233c9.log) and was fixed onmainby fix(ui): fresh-browser checks fail on redesigned startup fallback #194504. Merged into currentmain, that file passes 3 of 3 (ci-lanes/ui-e2e-gateway-fresh-visit-merge-into-main-10592dac.log), and the other 18 files of that shard pass (ci-lanes/ui-e2e-shard1-files-merge-into-main-10592dac.log; the one WebKit test there needed WebKit installed locally and then passed 2 of 2,ci-lanes/ui-e2e-mcp-fullscreen-webkit-rerun-merge-into-main-10592dac.log).openclaw/ci-gateonly aggregates the two lanes above.Pair bench on current
main82210a2bbdb0(pair-bench/): four builds from onemain(main,main+ this PR,main+ fix(postgres): chat history slows under concurrent reads #190129,main+ both), four runs each in interleaved order, PostgreSQL 17.11, closed-loopchat.historyat 1, 8, 16 and 32 clients. Gate results on the samemain: PostgreSQL conformance 15 files / 165 tests pass with this PR and with both PRs (3 tests fail on plainmain); unit 16 / 224 with this PR, 28 / 386 with both (pair-bench/tests/). This store has dense pages only, which already read in one page snapshot onmain, so the database work is the same on all four builds (BEGIN2.00 per call at 1 client, statements per call within 0.1,pgss.tsv). End to end, this PR is slower on it at 1 and 8 clients, alone and together with fix(postgres): chat history slows under concurrent reads #190129. Medians of 4 runs (medians.tsv), p50 / p95 / p99 in ms and calls/s:mainMoved the wrong way with this PR, against
main: at 1 client p50 +15% (6.90 vs 6.01 ms), p95 +13% (11.79 vs 10.47 ms), p99 +23% (15.84 vs 12.85 ms) and throughput -12.9% (138.55 vs 159.0 calls/s); at 8 clients p50 +6% (20.75 vs 19.65 ms), p95 +15% (37.58 vs 32.55 ms), p99 +17% (54.23 vs 46.48 ms) and throughput -9.5% (348.35 vs 385.0 calls/s); at 32 clients p50, p95 and p99 within 1.2%. Against #190129 alone, with both PRs: at 1 client p50 +15% (7.24 vs 6.31 ms), p95 +4% (13.3 vs 12.75 ms) and throughput -7.9% (125.6 vs 136.4 calls/s); at 8 clients p50 +10% (15.21 vs 13.84 ms), p95 +28% (26.02 vs 20.29 ms), p99 from 26.26 to 55.06 ms (also abovemain, 46.48 ms) and throughput -13.5% (480.2 vs 555.25 calls/s); at 16 clients p99 +20% (81.27 vs 67.81 ms); at 32 clients p95 +34% (91.12 vs 67.92 ms), p99 +45% (128.55 vs 88.81 ms) and throughput -2.9% (529.4 vs 545.0 calls/s).Host load: at 8 clients, this PR alone is slower than
mainin 3 of 4 rounds, butmainstarted those arms at lower load (3.8 to 4.4 vs 5.5 to 10.1,arms.tsv), so these rounds alone do not rule load out. With both PRs it is slower than #190129 alone in 4 of 4 rounds, including round 3 where it started at lower load (6.7 vs 12.8) and round 2 at about equal load (6.1 vs 5.9). In the profiled runs below, this PR started both 8-client runs at lower load thanmain(6.5 and 8.0 vs 8.6 and 9.3,cpu-profile/run-order-and-load.txt) and was still slower (p50 28.72 and 28.88 vs 26.78 and 28.14 ms,cpu-profile/runs-h8.txt).The database runs the same statements on all builds; the extra time shows in the history worker. Worker time per request (
worker-time.tsv) is 2.043 vs 1.804 ms at 1 client and 2.630 vs 2.373 ms at 8 clients againstmain, 3.741 vs 3.229 ms at 8 clients against #190129 alone, and equal at 16 and 32 clients. A CPU profile of the history workers at 8 clients (2 runs per build,cpu-profile/; profiling slows every build, so only the difference is used) shows the workers busier by 123 µs per worker request with this PR. Of that, 62 µs is waiting for database replies to the same statements, about 10 µs is garbage collection, and the rest is spread thinly, with no other function moving by more than 6 µs. With statement counts unchanged, the average wait per statement is longer; why was not isolated, and the profile does not separate database time from bridge transport time. The saving on sparse and provider-switch pages, which grows with the database round trip, is measured innetwork-hop/above.Gaps