Repository navigation
perf: load retained chat history faster - #133680
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 9:21 PM ET / August 31, 2026, 01:21 UTC. ClawSweeper reviewWhat this changesThe PR replaces per-message SQLite history queries with shared range queries and batched sparse-position reads for retained chat-history pages. Merge readiness✅ Ready for maintainer review Keep open for normal maintainer review. The shared selection owner preserves reset-aware logical ordering and sparse retained positions, while focused regressions cover binding limits and discarded tool-result gaps; no introduced blocking defect was found. Priority: P3 Review scores
Verification
How this fits togetherGateway chat-history requests read a session’s SQLite transcript projection and return reset-aware message pages to chat clients. The change centralizes selection of visible message rows for both payload loading and byte-budget calculation. flowchart LR
A[Chat history request] --> B[Gateway history reader]
B --> C[Transcript projection]
C --> D[Visible message selection]
D --> E[SQLite event rows]
E --> F[Bounded history page]
F --> G[Chat client]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource -24, Tests +57. Total +33 across 4 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Retain the single reset-window selection owner and land after normal maintainer review and exact-head CI confirm the existing history-page invariants. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: the changed path runs from Gateway history paging through the SQLite projection reader, and the supplied evidence exercises real isolated SQLite with contiguous and sparse reset histories. This read-only review did not execute the benchmark. Is this the best way to solve the issue? Yes. Centralizing both payload and byte-metadata selection in the reset-window owner removes the per-message query pattern without duplicating reset-position policy in its callers. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b0fe1062862a. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Landing review for the verified source commit. The root cause was repeated query construction at the reset-window owner: retained payloads used one query per message, and metadata built large position-binding lists. The shared selector now uses the existing index for contiguous tails and batches of 500 exact retained positions for reset history. Metadata sizing and payload reads use the same selection, preserving discarded tool-result gaps, logical ordering, reset/compaction markers, byte limits and snapshot ownership. The expanded-position helper and duplicate metadata query paths are removed. Production delta is -24 lines; tests are +57 lines. No schema, index, persistence, configuration or protocol changes. The recorded Node profiles exercise real isolated SQLite through 69 tests passed across eight owner/Gateway files, with the seven history-event tests rerun after rebase on the published head. Both added binding-limit regressions failed on the original code with node scripts/run-vitest.mjs \
src/config/sessions/session-accessor.sqlite-history-events.test.ts \
src/config/sessions/session-accessor.sqlite-active-events.test.ts \
src/config/sessions/session-accessor.sqlite-byte-size.test.ts \
src/config/sessions/session-accessor.sqlite-bounded-context.test.ts \
src/gateway/session-transcript-readers.test.ts \
src/gateway/session-transcript-readers.markers.test.ts \
src/gateway/server-methods/chat-history-pages.test.ts \
src/gateway/server-methods/chat-history-handler.test.tsTargeted type-aware lint and formatting passed. A fresh independent Codex commit review reported no accepted/actionable findings at the configured P0 threshold. Direct contract inspection included Kysely immutable query builders, the existing active-message index, deferred snapshot ownership and sibling Codex Local proof limitations remain explicit: the full changed gate encountered six existing The ClawSweeper review found no actionable correctness or security defect and requested normal maintainer review plus exact-head CI. Maintainer source/owner review and fresh Codex review are complete. Its automated “vector/embedding metadata” data-model notice is a false positive: Exact-head CI is complete and green: CI run 33346590883, attempt 1, source |
|
Merged via squash.
|
Related: #133635 (earlier chat-history preparation optimizations).
What Problem This Solves
Chat history can still pause while loading a large retained conversation after a session reset. Profiling showed the history reader issuing a separate payload query for each retained message and building large SQL binding lists for ordinary contiguous pages.
Why This Change Was Made
The reset-window owner now prepares one shared selection for payload reads and byte sizing: indexed range predicates for the contiguous tail, and batches of 500 exact retained positions after a reset. Exact positions preserve gaps where tool results were discarded. Both history paging and bounded-tail salvage use this selection, removing duplicated query construction and the expanded-position helper.
Byte selection still happens before payload materialization. Reset boundaries, logical ordinals, ordering, snapshot ownership, and sparse salvage remain intact. There are no schema, index, persistence, cache-lifetime, protocol, or page-size changes.
Production: +89/-113 (net -24 lines). Tests: +74/-17 (net +57 lines).
User Impact
Faster initial history loading and older-page loading after resets, with the same returned messages. Ordinary initial SQLite history reads also show a smaller improvement in paired measurements.
Evidence
Node 26.8.1 on macOS arm64, using real isolated SQLite through
readChatHistoryPage. Each fixture contains 3,000 visible messages; reset fixtures add a reset marker, and the sparse fixture also contains 2,999 discarded orphan tool results. Five warmups and 30 measured rounds per scenario, with rotated scenario order. These are Gateway preparation timings, excluding serialization, fixture setup, assertions, network, and browser paint.Sampled Kysely self time across each complete fixture profile fell from 4,025.6 to 80.8 ms for dense reset history and from 3,008.5 to 71.2 ms for sparse reset history. Row iteration and JSON parsing remain the dominant costs.
The separate-process short-message Gateway timings were noisy and sometimes slower (initial 400: 8.938 → 12.355 ms; repeat 11.192 ms), so this PR does not claim an overall short-message Gateway speedup. A follow-up paired test ran the original and refactored readers against the same database in one process, alternating order, with 20 warmups and 100 measured rounds per case. Initial SQLite reads improved 6.9–12.1%; the initial-400 reader measured 4.256 → 3.894 ms. All 600 paired results, including warmups, were identical without normalization.
Validation:
too many SQL variables; both pass after the refactor. The sparse reset regression verifies 1,001 retained messages, discarded tool-result gaps, marker ordering, and an offset page across a batch boundary.__openclaw.transcriptPosition.source. Source format and within-fixture consistency are checked before normalization; all other fields are compared. Requested counts and pagination totals are asserted during measurement.check:changedpassed repository guards, formatting, export scans, plugin boundaries, and the core graph boundary. It stopped at six existing TS2339 errors insrc/logging/logger.tsfortslog'sattachTransport/settingsdeclarations in the shared local dependency install. No changed-file type errors were reported; later gate stages, including core test typechecking, did not run.Browser-proof limitation: the local runtime/UI build remains blocked by the missing
shiki/wasmmodule in the shared worktree dependency installation (rechecked during landing). Earlier build output also showed unresolvedlit-htmlimports. No new browser capture or browser-paint measurement is claimed; the profiling exercises the real SQLite-to-Gateway history reader and verifies complete returned pages.Measurements and the full test run used base
cf25af4699bfcfdbebd0509b7756045767882714. The four changed files were verified byte-identical after rebasing onto current main. The history-event suite was rerun after rebase.Reproduce the Gateway benchmark
Save the following temporary file as
src/gateway/server-methods/chat-history-window.measurement.test.ts, run it on the baseline and candidate, then remove it. It writes Node CPU profiles and the complete synthetic message arrays. The timing excludes response serialization; serialization is measured separately.