Repository navigation
fix(postgres): chat history slows under concurrent reads - #190129
Conversation
- PostgreSQL history workers spend most of a request blocked on bridge replies, so the shared two-worker reader cap queued concurrent chat.history requests while CPU sat idle. - History on PostgreSQL agent stores now uses two workers per CPU above one, capped at four. SQLite and unset engines keep the reader size. - The history pool resolves its size on first use, because boot installs the database engine after the lane module is imported. - Transcript search and the other transcript lanes are unchanged. - Tests: per-engine sizing table, and a lane test that installs the engine after import (PostgreSQL 4, SQLite 2). - Docs: runtime architecture sizing note and the PostgreSQL backend budget.
|
🦞👀 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 raises PostgreSQL history capacity to at most four workers and resolves its size after boot selects the database engine. Example: Eight clients concurrently load chat.history from PostgreSQL in the supplied interleaved benchmark.
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, measured concurrency improvement, with no actionable patch defects found; accepting the higher PostgreSQL history resource budget remains an owner decision. Priority: P2 Decision needed
Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway history requests enter the foreground transcript pool, whose workers read the selected agent database and return history pages; existing resource owners retain admission, cleanup, and retirement. flowchart LR
A[History clients] --> B[Gateway history RPC]
B --> C[History worker pool]
D[Boot engine selection] --> C
C --> E[Transcript workers]
E --> F[PostgreSQL bridge]
F --> G[Agent database]
Technical reviewBest possible solution: Adopt the bounded PostgreSQL-only history exception through the existing sizing and lifecycle owners if the owner accepts its measured resource cost. Do we have a high-confidence way to reproduce the issue? Current-main source retains the two-worker bottleneck, and inspected contributor artifacts reproduce it through real Gateway RPCs on documented recent revisions; this read-only review ran no target code. Is this the best way to solve the issue? The patch is a focused capacity improvement using existing owners; first-use construction correctly accommodates boot-time engine selection, and the paired snapshot benchmark confirms a distinct remaining throughput benefit. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 869734209368. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +40, Tests +117, Docs +5. Total +162 across 7 files. Added test files: 2. 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 (4 earlier review cycles)
Reviewed November 16, 2026, 2:04 PM ET / 19:04 UTC (Revision 5). |
|
@clawsweeper re-review No code change. The bench is re-run on current |
|
🦞👀 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 trimmed to the history worker sizing, so this PR closes it. The per-page snapshot part moved to #197313, addressed by #190001. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…0129) - PostgreSQL history workers spend most of a request blocked on bridge replies, so the shared two-worker reader cap queued concurrent chat.history requests while CPU sat idle. - History on PostgreSQL agent stores now uses two workers per CPU above one, capped at four. SQLite and unset engines keep the reader size. - The history pool resolves its size on first use, because boot installs the database engine after the lane module is imported. - Transcript search and the other transcript lanes are unchanged. - Tests: per-engine sizing table, and a lane test that installs the engine after import (PostgreSQL 4, SQLite 2). - Docs: runtime architecture sizing note and the PostgreSQL backend budget.
…law#194384) * docs: clarify PostgreSQL conformance coverage * fix(cron): keep one-shot finalization working on PostgreSQL 16 * test(database): reuse cron conformance for JSON conversion regression * test(postgres): accept fractional explain row counts (cherry picked from commit 7ab0143) Release adaptation: Only engine-owned jsonValue and retained cron enabled JSON replacement; preserve native boolean type with PG16 explicit ::json and SQLite json(). Omit unrelated PG docs/EXPLAIN test edits; retained one-shot enabled-transition caller present on baseline. Follow-up dispositions: e029e18 docs: document isolated PostgreSQL restore drills (openclaw#202704); 49f0740 fix(database): report disabled memory after a port (openclaw#202630); a80b564 fix: keep database workers healthy after silent connection loss (openclaw#201856); 3d91af2 fix(config): reject reserved PostgreSQL schema prefixes (openclaw#202097); 835d722 fix: catch incompatible ownership before porting to SQLite (openclaw#202101); 67796a6 fix: keep scheduled Git backups current on PostgreSQL (openclaw#201870); cc849dd fix: recover lease heartbeats after a PostgreSQL connection loss (openclaw#201858); 6594caf fix: prepare macOS runtime pins without the PostgreSQL secret (openclaw#202102); 6ca56cd docs: clarify PostgreSQL storage and backup coverage (openclaw#202086); a079190 fix(postgres): chat history slows under concurrent reads (openclaw#190129); 2ff4256 feat(database): keep PostgreSQL rollback captures in PostgreSQL (openclaw#196236); 96c685b feat(backup): restore PostgreSQL stores into a staging database for restore drills (openclaw#194808); fb83d65 fix: reduce transcript allocation when preparing native context seeds; 71ec4d2 fix(config): keep Workboard PostgreSQL upgrades readable (openclaw#194648); b6ed907 perf(sessions): persist active transcript facts for hydration (openclaw#193682) Validation: Baseline cron generated json(bound text) on PostgreSQL where json(text) is unavailable; helper and focused boolean regression retained. Exact PostgreSQL16 server proof unavailable; focused SQLite/helper tests queued. diff check passed. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 38fdd9b52704d588d9ca24ef8e391d644961c985) (cherry picked from commit fb935e6912388314851b05cb698ef038b83bbd07)
Closes #188956
Related: #197313, #190001 (#197313 tracks the repeated read snapshots inside each history page, which #190001 addresses)
What Problem This Solves
Fixes: on PostgreSQL,
chat.historyrequests queue behind two history workers when several clients load history at once, so tail latency grows with concurrency while the CPU sits mostly idle.User Impact
User impact: concurrent
chat.historyon PostgreSQL waits much less for a history worker. Re-measured on currentmain(medians of 8 interleaved runs per build): at 8 concurrent clients p50 drops from 19.6 to 12.02 ms, p99 from 54.31 to 31.76 ms, and throughput rises from 378.1 to 622.95 requests/s; at 32 clients p99 drops from 163.13 to 103.1 ms. Single-client p50 is unchanged; single-client p99 rose from 15.08 to 17.07 ms over all runs (14.87 to 15.13 ms in the quieter block). SQLite keeps its current lane size.Cost, measured on the same runs (medians of 8 runs per build):
isolates × (active + 2)) now notes up to four history isolates.Decision for review: should PostgreSQL history use up to four workers, accepting the cost above? This revises the two-worker reader cap from #167295 and #169110 for one lane on one engine.
main(see Evidence): lower queue wait at 16 clients, at about two and a half times the extra memory and with more backends.Recommended: (a). The extra workers exist only on PostgreSQL agent stores and only under concurrent history reads, they retire through the existing idle timeout and cleanup owners, and SQLite, transcript search and every other lane keep the current cap. The memory bound stays fixed (at most four history isolates on any host), and the latency it buys is the symptom #188956 reports.
Why This Change Was Made
On PostgreSQL a history worker spends most of a request blocked in
Atomics.waiton bridge replies, so sizing the lane like a CPU-bound reader leaves requests queued while CPU is free. The history lane on PostgreSQL agent stores now gets two workers per CPU above one, capped at four (two on a two-CPU host). Transcript search, the other transcript lanes, and every SQLite lane keep the existing reader size from #167295 and #169110. No new setting.The database engine is installed during boot, after the lane module is imported, so the history pool now resolves its size on first use instead of at import. Production code: +47/-7 lines ignoring whitespace (the pool options block is re-indented inside the first-use constructor); tests +117; docs +9/-4.
Scope: this closes #188956 (the queueing in front of the history workers). The transaction round trips inside each page are #197313, addressed by #190001; the two touch different files and are measured separately.
Evidence
Evidence files: https://github.com/etzelm/openclaw/tree/assets/pg-r2-l3d-history-reader-lane-evidence/current-main-2026-11-07 (paths below are relative to it; method, host and store in
README.md). The earlier bench on31866655fd6stays at the root of the same branch.Acceptance rule: through a running Gateway on PostgreSQL, at 8 or more concurrent clients, queue wait per worker request and p50 drop, throughput rises and p99 at 8 clients drops; single-client latency holds; the memory and backend cost is reported, and the extra isolates retire once history load stops.
main078033289a3: a per-engine sizing table (src/infra/worker-pool-sizing.test.ts) and a lane test that installs the engine after importing the lane, as boot does (src/config/sessions/session-history-lane-sizing.test.ts: PostgreSQL 4, SQLite 2, search 2). Both pass, as do the consumer suites for the transcript lanes, the search worker, reconcile readiness, the chat history worker and worker-pool preparation: 12 files, 161 tests (tests/unit-head.log). Onmainthe sizing table fails because the resolver does not exist, and the PostgreSQL lane case gets 2 instead of 4 while the SQLite case passes (tests/unit-base-red.log).pnpm check:changedon the merged head passes every check except two repo-wide audits that fail the same way on plainmain078033289a3: changelog attributions (bot credits inCHANGELOG/files) and the dead export scan (scripts/lib/control-ui-gesture-probe.ts,src/process/command-reservation-census.ts) (tests/check-changed.log,tests/base-changelog-attr.log,tests/base-deadcode.log). CI on987348094ebwas green.main4a0e45492b8(head3e55cf3ef68):maindropped the history worker'sprewarmHistoryoption (improve(sessions): reduce memory for lightweight transcript reads #198512), so the lazy pool no longer passes it; sizing is unchanged. The sizing table, the lane test and the consumer suites above plus the prewarm and history worker lifecycle suites pass: 14 files, 169 tests. One test insession-transcript-worker-lanes.test.ts(releases pressure subscriptions after native settlement and rearms reopened lanes, added onmainby fix: reduce Gateway stalls under filesystem pressure #197510) fails on this head and on plainmain4a0e45492b8alike, 3 of 3 runs each on a macOS arm64 host.pnpm check:changedpasses every step except the dead export scan, whose findings are all in files this PR does not touch.chat.historybench on currentmain: basemain078033289a3vs this head merged into it, both built withpnpm build. A fresh Gateway on PostgreSQL 17.11 per run, seeded through its own RPCs with 200 sessions (170 sessions across 6 agents with 2 to 4,675 messages each, plus 30 imported Claude CLI sessions with tool rows hidden between visible turns). Limit 100, 45 s per arm, 16 runs (8 per build) in two interleaved blocks (base head head base base head head base). No run was dropped. Medians over all 16 runs (bench/block-all/medians.tsv; every run inbench/block-all/arms.tsv; raw scrapes inbench/runs/):Queue wait is
openclaw_worker_queue_wait_seconds{kind="sessionTranscript"}; handler mean isopenclaw_gateway_rpc_handler_seconds{method="chat.history"}. The host is shared, and the wide p99 ranges come from runs under other load, so the two blocks are also reported separately:Block 2 (
bench/block-b2/, started only below a 1-minute load of 12; arms at load 4 to 25): p99 at 1, 8, 16 and 32 clients 14.87 / 30.47 / 68.2 / 115.94 ms base vs 15.13 / 25.1 / 64.69 / 88.53 ms fix; p50 at 8 clients 18.11 vs 11.73 ms, throughput 431.6 vs 651.05 requests/s. At 16 clients p99 is about even while p50 drops from 35.98 to 24.6 ms.Block 1 (
bench/block-b1/, load 6 to 55): p50, throughput and queue wait improve at 8, 16 and 32 clients as above, but p99 does not improve consistently: 69.65 vs 73.11 ms at 8 clients, 147.19 vs 113.72 ms at 16, 198.87 vs 281.24 ms at 32. The worst fix tails arepg-head-r1(the highest 1-minute load in the bench, 37 to 55) andpg-head-r2(load 25 to 33, started with 25% of host memory free); the other two fix runs in the block have p99 21.7 and 36.16 ms at 8 clients. When the host's CPU is already saturated, extra workers add little.Moved the wrong way: memory and backends (see User Impact: +120 MiB peak transcript heap, +388 MiB peak RSS, +219 MiB RSS 100 s after load, +2 peak backends); single-client p99 15.08 to 17.07 ms over all runs (14.87 to 15.13 ms in block 2; p50 6.09 to 6.00 ms over all runs, 5.71 to 5.94 ms in block 2; single-client p95 10.69 to 11.02 ms over all runs) and 19.35 to 33.27 ms in block 1 (driven by
pg-head-r2, single-client p99 106.71 ms); single-client throughput 156.4 to 154.4 requests/s over all runs (163.6 to 155.65 in block 2); and in block 1, under the heaviest host load, p99 at 8 clients 69.65 to 73.11 ms and at 32 clients 198.87 to 281.24 ms. In the pair bench on currentmain, single-client p95 12.75 vs 10.47 ms (+22%), p99 21.33 vs 12.85 ms and throughput 136.4 vs 159.0 calls/s (-14%) (pair-bench/medians.tsv). These are part of the decision above.Memory and connections (
bench/block-all/memory-medians.tsv, per run inmemory.tsv): see User Impact. Heap and isolate counts come from the Gateway's worker metrics, sampled by the 30 s diagnostic heartbeat; RSS and backend counts are sampled every 2 s.SQLite: the lane size is unchanged by construction (the resolver returns the existing reader size for every non-PostgreSQL agent engine; covered by the sizing table and lane test). The earlier bench on
31866655fd6measured SQLite p50, throughput and transcript isolates unchanged; not re-measured here.Cap of four vs eight (earlier bench on
31866655fd6, 3 runs each,bench/medians.tsvandbench/memory-medians.tsvat the branch root, rowsbase-a,fix4andfix8): eight gave 0.07 ms queue wait at 8 clients and 1.66 ms at 16, at +325 MiB peak transcript heap, +974 MiB peak RSS and 27 peak backends overbase-a, against +120 MiB heap, +382 MiB RSS and 25 peak backends for four (fix4overbase-a).Pair bench on current
main82210a2bbdb0(pair-bench/): four builds from onemain(main,main+ improve(postgres): read each chat history page from one database snapshot #190001,main+ this PR,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: unit 12 files / 162 tests pass with this PR (the new sizing and lane tests fail on plainmain); with both PRs unit 28 / 386 and PostgreSQL conformance 15 / 165 pass. Medians of 4 runs, this PR vsmain: at 8 clients p50 13.84 vs 19.65 ms, p99 26.26 vs 46.48 ms, 555 vs 385 calls/s, queue wait per worker request 1.06 vs 5.28 ms; at 16 clients p50 29.21 vs 41.94 ms, 507 vs 362 calls/s; at 32 clients p50 58.09 vs 79.41 ms, p99 88.81 vs 199.78 ms, 545 vs 372 calls/s. At 1 client p50 is 6.31 vs 6.01 ms and p99 is noisier (12.12 to 60.43 ms across runs vs 11.74 to 23.23 ms onmain; the two highest runs had the highest arm-start load of this build's four runs, 13.1 and 17.9 inpair-bench/arms.tsv). Cost: peak Gateway RSS 2789 vs 2468 MiB (+321 MiB), peak transcript worker heap 456 vs 332 MiB (+124 MiB), peak transcript workers 8 vs 6, peak PostgreSQL backends 23 vs 21; 100 s after load, 4 workers vs 3 and the same 13 backends. With improve(postgres): read each chat history page from one database snapshot #190001 as well, p50 is the same at 16 and 32 clients (29.57 and 58.06 ms) but p99 is higher (81.27 vs 67.81 ms, 128.55 vs 88.81 ms). At 8 clients the pair has p50 15.21 ms, p99 55.06 ms and 480.2 calls/s: p99 is above this PR alone (26.26 ms) and also abovemain(46.48 ms), and throughput is below this PR alone (555.25 calls/s) in all four paired runs (arms.tsv), so host load does not explain it. The cost comes from improve(postgres): read each chat history page from one database snapshot #190001 on this dense-page store (history worker time per request 3.741 vs 3.229 ms at 8 clients,pair-bench/worker-time.tsv) and is reported there.Gaps
maindoes not admit apg_restoreof a production store. Its shape follows the production bench in [Feature]: chat.history on PostgreSQL queues behind two history workers under concurrent reads #188956.arms.tsv). Two fix runs (pg-head-r2in block 1,pg-head-r8in block 2) started while another job held most host memory; both are kept.scripts/instrument-*.diff). Isolate counts and heap cover every transcript lane, not only history, and 30 s sampling can miss the exact peak. RSS was watched for 100 s after load here; the earlier 300 s pair on31866655fd6(bench/runs/pg-*-idle-r1at the branch root) showed no lasting RSS difference with the same isolate count (1,676 vs 1,745 MiB at 300 s).pair-bench/run-order-and-load.txt, and 3.8 to 22.2 at arm start,pair-bench/arms.tsv). Tails at 1 and 8 clients move with that load; medians at 8 or more clients do not. Idle retirement past 100 s was not sampled in the pair bench; the earlier bench above covers it.