Skip to content

improve: reduce repeated work when loading session history - #146607

Merged
steipete merged 1 commit into
mainfrom
codex/session-history-loader-dedup
Sep 13, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/session-history-loader-dedup

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Related: #146390

What Problem This Solves

Loading and paging session history repeats query construction and array work even when each request returns only a small number of messages.

User Impact

Warm ordinary history reads use 21–31% less median wall time and 25–34% less CPU in paired measurements. The surrounding Gateway-tail operation improves about 6–9% in median wall time for ordinary histories. Messages, byte limits, paging, cursors, and authoritative active-leaf metadata are preserved. No schema change, new configuration, migration, or operator action is required.

Why This Change Was Made

Separate numeric range descriptions from SQL construction and reuse the two compiled Kysely range queries on each database connection. Every invocation binds current values; payload iterators retain private native statements and their existing lazy execution and cleanup. Sparse reset batches keep their existing selection, and metadata sizing remains separate from payload loading.

Current and historical anchors share one page-range calculation, visible delta rows reuse the existing parser, and compactions avoid an identity Set/filter and per-record singleton arrays. The SQLite Gateway adapter stops constructing an unused transcript-events array; archive adapters retain their existing fallback data.

Evidence

Paired actual-reader measurements use Node 24.21.0 / SQLite 3.53.4, 100 warmups, and 32 alternating batches of 50 reads per variant. Nine frozen reader modules from main f1c1f27 provide the baseline; both variants share unchanged dependencies and the synthetic database owner in the same process. Both include the upstream marker-search improvement. Values are medians of per-read batch timings.

Warm reader Main baseline Candidate
Recent 20 of 80 messages 0.1591 ms 0.1105 ms
20-message page, offset 40 of 80 0.1419 ms 0.1073 ms
Recent 20 of 10,000 messages 0.1689 ms 0.1283 ms
20-message page, offset 40 of 10,000 0.1500 ms 0.1179 ms

Ordinary direct reads still execute three SQL statements, but repeated Kysely compilation falls from two calls to zero. The Gateway-tail operation retains eight statements and goes from three compiler calls to one. SQL text, statement order, bindings, JSON parse counts, and parsed bytes match exactly across all 12 ordinary, marker, and reset cases. Direct results are deeply equal. Gateway comparisons explicitly verify the sole internal shape difference—the retired transcript-events array—and exact equality of every remaining field.

The 10,000-event full-history guard is effectively flat in median wall time (36.640 to 36.695 ms); CPU time is 40.864 to 41.541 ms. Results and decoded bytes remain identical. Reset recent/offset reads improve roughly 8–16%; marker-heavy cases are approximately flat. Some p95 values worsen, including the full-history guard's 38.134 to 46.669 ms across 12 single-read batches. These measurements cover warm backend reads; database opening, first-use compilation, and complete RPC/browser latency are outside the timing claims.

All 169 focused loader tests pass across 13 files. Complete changed-file checks pass, including production/test types, core/script lint, dead-export scans, formatting, and architecture guards. Independent Codex P2 review is scoped-clean. The parser cleanup removes one duplicate assertion, and its baseline count shrinks accordingly.

CI exposed two separate fixture problems, both now repaired upstream. The branch includes the upgrade-cohort argument fix in #146606 and the primary-provider request synchronization fix in #146644. Our equivalent catalog-test patch was dropped during conflict resolution, keeping one upstream implementation. The loader optimization rebased patch-identically onto main 65db526, and all six measured production files retain their benchmarked hashes. The existing cross-session/page-bounds assertions remain alongside #146614's shared fixture constructors.

All 26 tests across the overlapping history-events and catalog-freshness fixtures pass after the refresh. Exact-head hosted CI passed for 4854ae8: https://github.com/openclaw/openclaw/actions/runs/34733562981. Fresh ClawSweeper review of this head found no actionable defects.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Sep 13, 2026
@steipete
steipete marked this pull request as ready for review September 13, 2026 00:59
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 12, 2026, 10:59 PM ET / September 13, 2026, 02:59 UTC (Revision 6).

ClawSweeper review

What this changes

The PR reduces session-history loading overhead by reusing compiled SQLite queries, sharing pagination calculations, and removing unnecessary array construction.

Merge readiness

✅ Ready for maintainer review

The PR remains useful beyond the merged history-query optimization. Source review found no actionable defects, and the supplied measurements support its bounded performance claims.

Priority: P2
Reviewed head: 4854ae83d8f76398b5e39097279e965d93e8cafd

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with strong bounded measurements, useful lifecycle coverage, and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied production-reader measurements exercise recent, offset, marker, reset, and full-history reads against real SQLite, showing improved warm-read medians and preserved results; complete RPC latency is explicitly outside the claim.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied production-reader measurements exercise recent, offset, marker, reset, and full-history reads against real SQLite, showing improved warm-read medians and preserved results; complete RPC latency is explicitly outside the claim.
Evidence reviewed 9 items Introduced optimization: The complete range-reader module retains sparse reset selection and byte-only metadata queries while caching two compiled readers per database connection; each invocation supplies fresh session and range values.
Iterator lifecycle: The new prepared iterator captures invocation-local bindings and delegates to the existing lazy iterator, which creates a private native statement and preserves error handling and iterator cleanup.
Removed array has a preserved metadata owner: SQLite recent and offset readers always supply activeLeafEntryId from the projection snapshot. The Gateway consumer prefers that field, while archive adapters retain transcriptEvents for their existing fallback contract.
Findings None None.
Security None None.

How this fits together

Session-history readers turn stored SQLite transcript events into bounded message pages for Gateway clients. They preserve reset boundaries, byte limits, cursors, and active-branch metadata.

flowchart TD
  A[History request] --> B[Transcript read snapshot]
  B --> C[Visible message ranges]
  C --> D[Reused query compilation]
  D --> E[Fresh session and page bindings]
  E --> F[SQLite metadata and payload reads]
  F --> G[Messages and pagination metadata]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +95, Tests +54, Other 0. Total +149 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 6 208 113 +95
Tests 2 99 45 +54
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 9 308 159 +149

Review metrics

Metric Value Why it matters
Production versus test growth Production net +95 lines; tests net +54 lines Production growth implements connection-scoped compiled readers with a stated, measured reduction in repeated query construction.
Warm query compilation Direct reads: 2 to 0 calls; Gateway tail: 3 to 1 Supplied paired measurements isolate reduced compilation work without changing executed SQL statement counts.

Technical review

Best possible solution:

Keep query compilation connection-scoped while preserving fresh bindings, snapshot ownership, private iterators, and separate metadata sizing.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a functional bug: this is a performance optimization, supported by paired actual-reader measurements rather than a failing behavior reproduction.

Is this the best way to solve the issue?

Yes. Reusing the existing binding compiler and iterator owner avoids a competing execution path while preserving SQL selection and pagination semantics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9ac1ceb51537.

Labels

Label justifications:

  • P2: This is a measured, bounded performance improvement to session-history loading without an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied production-reader measurements exercise recent, offset, marker, reset, and full-history reads against real SQLite, showing improved warm-read medians and preserved results; complete RPC latency is explicitly outside the claim.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied production-reader measurements exercise recent, offset, marker, reset, and full-history reads against real SQLite, showing improved warm-read medians and preserved results; complete RPC latency is explicitly outside the claim.

Evidence

What I checked:

  • Introduced optimization: The complete range-reader module retains sparse reset selection and byte-only metadata queries while caching two compiled readers per database connection; each invocation supplies fresh session and range values. (src/config/sessions/session-accessor.sqlite-reset-window.ts:104, 4854ae83d8f7)
  • Iterator lifecycle: The new prepared iterator captures invocation-local bindings and delegates to the existing lazy iterator, which creates a private native statement and preserves error handling and iterator cleanup. (src/infra/kysely-sync.ts:170, 4854ae83d8f7)
  • Removed array has a preserved metadata owner: SQLite recent and offset readers always supply activeLeafEntryId from the projection snapshot. The Gateway consumer prefers that field, while archive adapters retain transcriptEvents for their existing fallback contract. (src/config/sessions/session-accessor.sqlite-history-events.ts:544, 4854ae83d8f7)
  • Meaningful regression coverage: Reviewed tests exercise changing session IDs and page bounds, nested prepared iterations, early iterator return, callback re-entry, and preservation of original SQLite errors. (src/infra/kysely-sync.test.ts:308, 4854ae83d8f7)
  • Actual-reader performance evidence: The complete supplied PR body records paired production-reader measurements against synthetic SQLite storage on Node 24.21.0 / SQLite 3.53.4: 100 warmups and 32 alternating batches of 50 reads. Ordinary warm-reader medians improve 21–31%; twelve scenarios preserve SQL, bindings, decoded bytes, and results apart from the explicitly retired internal array. Cold opens and full RPC/browser latency are excluded, and worse p95 samples are disclosed. The media manifest contains screenshots belonging to the related TUI PR, which are not evidence for this optimization. Captured context sourceRevision: e30ba79a6e6986499c412685218267a8ab578d9c2a8c8a7733969368647fe542. (4854ae83d8f7)
  • Still distinct from current main: Fetched main retains the ordinary compile-on-read iterator and lacks prepareSqliteQueryIterator. The merged improve: load session history with fewer SQLite queries #146390 optimizes projection admission instead; it does not supersede this range-query optimization. No local release tag contains the reviewed head. (src/infra/kysely-sync.ts:169, 9ac1ceb51537)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-13T01:06:18.258Z sha e88e912ca3ac64f5e7909c2e9265c5cb6d1082d1 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T01:31:09.191Z sha c0847b8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T02:11:43.202Z sha 6344669 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T02:31:27.921Z sha 6344669 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T02:45:51.970Z sha 4854ae8 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/session-history-loader-dedup branch from e88e912 to c0847b8 Compare September 13, 2026 01:25
@steipete
steipete force-pushed the codex/session-history-loader-dedup branch from 6344669 to 4854ae8 Compare September 13, 2026 02:38
@steipete
steipete merged commit db0d918 into main Sep 13, 2026
187 checks passed
@steipete
steipete deleted the codex/session-history-loader-dedup branch September 13, 2026 03:00
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant