Repository navigation
improve: load session history with fewer SQLite queries - #146390
Conversation
|
🦞👀 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: needs maintainer review before merge. Reviewed September 12, 2026, 7:39 PM ET / 23:39 UTC (Revision 6). ClawSweeper reviewWhat this changesThe PR combines SQLite session-history readiness checks, reuses query compilation, extends empty-history and archive-race coverage, and repairs a Gateway test fixture’s cached handler. Merge readiness✅ Ready for maintainer review This remains a useful, bounded optimization beyond the earlier merged history work. No actionable correctness or security defect was found, and the supplied production-reader measurements support the stated improvement. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw’s session-history reader turns stored transcript events into bounded message pages and cursors for Gateway clients. Its shared snapshot owner checks archive status and index readiness before reading those pages. flowchart TD
A[History request] --> B[Resolve session and database]
B --> C[SQLite read transaction]
C --> D[Combined readiness query]
D --> E{Transcript ready?}
E -->|Yes| F[Bounded messages and cursors]
E -->|Archived or stale| G[Existing error and recovery path]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +32, Tests +53. Total +85 across 5 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep one transactional history reader, reuse its compiled query with fresh bindings, and preserve bounded payload loading and existing recovery behavior. Do we have a high-confidence way to reproduce the issue? Not applicable as a functional bug report: this is a performance optimization supported by paired production-reader measurements; this review did not rerun them. Is this the best way to solve the issue? Yes. Consolidating readiness within the existing snapshot owner removes repeated work without introducing another cache of session data or changing storage contracts. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 51caa9442e47. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
5e783b6 to
23cadd2
Compare
|
Merged via squash.
|
Related: #146286
What Problem This Solves
Loading and paging session history incurs avoidable latency and CPU work, especially when many requests ask for a small number of messages.
Why This Change Was Made
Combine archive presence, projection state, generation, latest sequence, and unclassified-row checks into one query. Reuse its compiled Kysely program through the existing synchronous executor, binding the session ID and reading current rows on every invocation. A singleton target preserves missing, cleared, and archived transcripts, including empty-history generations. The existing deferred transaction continues to own the complete read snapshot.
The same snapshot owner serves read-only catalogs through their existing read-only acquisition path. Missing storage remains an error, and reconciliation remains the writer's responsibility.
Keep byte selection and JSON loading separate: measured window-query variants did not show a reliable query-level improvement, while eager payload loading can read 80 MiB to return at most 1 MiB. This change adds no schema, persisted cache, migration, or configuration.
User Impact
Warm ordinary history reads execute three queries instead of five and spend less CPU on repeated query construction. Returned messages, byte limits, cursors, cold-storage errors, and projection-readiness behavior remain unchanged. The improvement to the larger Gateway tail operation is smaller; these measurements do not represent the full chat.history RPC or browser latency.
Evidence
Paired measurements call the actual original and candidate readers in the same process against the same isolated synthetic SQLite database, using refreshed main af0056b as the baseline. Each comparison alternates 32 batches of 50 reads after 100 warmups. Full results are deep-equal outside timing; SQL tracing is also outside timing. Runtime: Node 24.21.0, SQLite 3.53.4. Values below are medians of per-read batch timings.
Direct-reader wall time falls 22–29% in this run. Repeating after ANALYZE showed a 23–36% direct-reader improvement. The measurement includes both joining and compilation reuse. The measured readIncrementalChatHistoryTail operation goes from 10 queries to 8; its wall-time improvement ranges from roughly 5–13% across the two runs, with about 8–11% less CPU. Counts are executed prepared statements, exclude transaction-control statements, and include two user_version PRAGMAs in the Gateway tail. The optimized SQL programs match the earlier Node 26 measurement in all six cases.
EXPLAIN with 10,000 sessions after ANALYZE uses primary-key lookups for state, watermark, frontier, and archive presence, plus the existing pending-classification partial index. SQLite bytecode confirms MAX(seq) seeks to the last indexed event. Tiny analyzed fixture tables can appropriately use scans for their one or two state/watermark rows.
These warm fixtures contain ordinary messages. Initial database opens, reset/marker processing, cold restoration, and projection rebuilding are outside the count and timing claims. Some p95 batch values worsen; this evidence supports a median and CPU improvement rather than a universal tail-latency improvement.
Payload experiments include native execution, byte selection, and JSON decoding, but exclude admission and Kysely compilation. For recent 20 × 64 KiB, the current split took 0.148 ms versus 0.170 ms for a streaming window CTE; for oversized-first 20 × 1 MiB, 0.606 ms versus 0.668 ms. These experiments support retaining the current split, not a claim that every possible combined implementation is slower.
Validation on refreshed main: all 86 focused cases pass—66 history/projection, seven read-only catalog, and 13 byte-size cases. Catalog coverage includes byte-identical source storage, fresh paging, stable cursors, and missing storage. Full changed-file checks pass, including production/test typechecks, lint, dead-export scans, and architecture guards. Independent Codex P2 reviews are scoped-clean for the production change, test-recorder correction, and read-only integration.
CI exposed two test-fixture problems that are corrected here. The byte-size recorder now recognizes the joined readiness result as well as the standalone form; its partial-index and overflow-bytecode assertions are unchanged. Both original failures were reproduced before the correction, all 13 cases pass afterward, and dropping the pending index in a disposable fixture still fails the guard.
The shared-worker profile-authorization case could reuse a cached fake runtime handler, acknowledge the request, and never enter the current authorization callback. Each stage now installs a fresh facade factory; the profile stage delegates to the actual router through vi.importActual. Production authorization, all assertions, cleanup, and the 120-second timeout are unchanged. The original-size, two-worker batch reproduced the failure before this repair and passes all 101 files / 2,264 tests afterward; the formerly stuck case completed in 380 ms. The standalone four-case file, type-aware lint, and independent P2 review also pass.
An intervening main-branch TLS sidecar integration failure was fixed separately in #146412 before refreshing this branch. Exact-head hosted CI: https://github.com/openclaw/openclaw/actions/runs/34724979078 (passed at ea45c3e; no failed or pending checks).