Skip to content

improve: speed up loading long session histories - #146286

Merged
steipete merged 2 commits into
mainfrom
codex/session-history-performance
Sep 12, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/session-history-performance

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #126914

What Problem This Solves

Loading a long conversation can block the Gateway while SQLite scans unrelated transcript payloads or repeatedly searches beyond the final message. Chat history also decodes child-session metadata twice per request, making session switches more expensive for parents with many children.

Why This Change Was Made

Keep the canonical history reader and its existing SQLite snapshot. Select the existing marker-type index for whole-session reads and the sequence index for reset windows, skip next-message searches beyond the final active message, and carry the generation already read by the snapshot. The post-await authorization check still rereads the selected session and verifies current access and identity; child metadata is loaded once for the response.

The change preserves history ordering, cursors, byte limits, malformed-data guards, and reset behavior. It adds no schema, migration, or persisted state. A reusable synthetic benchmark records SQL plans, statement/row counts, JSON work, and separate first-read and warm timing.

User Impact

Conversations with many markers open substantially faster, ordinary page reads perform less SQL, and parents with many child sessions avoid duplicate decoding.

Evidence

Warm p50 through the real SQLite history reader, requesting 20 events with planner statistics present (Node 26.8.2, Apple M3 Ultra, 15 samples):

Synthetic history Before After
10 markers among 10,000 messages 13.951 ms 0.613 ms
5,000 trailing compaction markers 613.591 ms 9.173 ms
Post-reset window 3.929 ms 3.735 ms

Ordinary recent reads execute 5 SQL statements instead of 9; dense marked histories execute 7 instead of 12. Selected-event and total counts match across all 18 comparisons; event JSON parsing remains bounded to the requested page. Dense custom-marker metadata still takes about 30 ms in the 5,000-visible-marker fixture.

A controlled alternating benchmark of the 1,000-child session recheck fell from 5.466 to 0.193 ms. The full registered history handler decodes 1,000 child rows instead of 2,000 and returned every child. Its separate before/after median was 14.61 to 8.54 ms.

Timings use synthetic isolated stores on a shared host. Warm timings exclude tracing; OS caches were not flushed. The benchmark reports first-open and RSS separately, and these results do not claim an RSS reduction.

pnpm test:sessions:history:bench --samples 30 --output history.json
pnpm test:sessions:history:bench --profile sparse,trailing,reset --operation recent --analyze --samples 15 --output history-analyzed.json
  • Focused history, active-projection, context-eligibility, Gateway-handler, and bounded-session-manager suites: 98 tests passed. The child-decoding regression failed for both history and startup before the repair.
  • Independent Codex autoreview: no actionable P0–P2 findings.
  • Script formatting, lint, typecheck, and erasability passed.
  • node scripts/check-changed.mjs passed, including core/test/script types, changed-file lint, and repository guards.
  • Benchmark CI repair: all 25 suppression-inventory and package-script tests passed with no new suppression allowance; SQL/JSON traces match the earlier measurements exactly.
  • Production and full-tree unused-file scans passed for the registered benchmark entrypoint.

@clawsweeper

clawsweeper Bot commented Sep 12, 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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: L maintainer Maintainer-authored PR labels Sep 12, 2026
@steipete
steipete marked this pull request as ready for review September 12, 2026 18:13
@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 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 12, 2026, 2:55 PM ET / 18:55 UTC (Revision 3).

ClawSweeper review

What this changes

Reduce SQLite query work and repeated child-session decoding when loading long conversations, and add a reusable history benchmark.

Merge readiness

✅ Ready for maintainer review

This remains a useful, supported performance improvement absent from the pinned main and latest release. No actionable introduced defect was found; the maintainer-authored PR should remain open for normal landing.

Priority: P2
Reviewed head: 2a92bd04c4ab47c568e18b0b2e770c9e80e85687

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with useful production-path measurements, relevant regression coverage, and no identified blocking defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured body reports before/after runs through the real SQLite history owner and registered Gateway handler on isolated synthetic stores, with matching selected-event/count results and all children returned after reducing query and decoding work.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured body reports before/after runs through the real SQLite history owner and registered Gateway handler on isolated synthetic stores, with matching selected-event/count results and all children returned after reducing query and decoding work.
Evidence reviewed 10 items Verified introduced changes: Inspected the merge-base-to-head source diff, independently of endpoint drift. It changes query selection, snapshot generation reuse, and the child-loading option on the second session read.
Snapshot and query semantics: Generation is read within the existing deferred transaction, including the empty-transcript fallback. Marker queries retain active membership, reset-window JSON guards, ordering, and byte accounting; the final-message guard avoids searching an empty suffix.
Access recheck preserved: The second lookup still reloads the selected entry and validates its agent, canonical key, physical session, store, and current sharing permission. Child entries remain loaded by the initial lookup for response metadata; they are not inputs to the sharing filter.
Findings None None.
Security None None.

How this fits together

Gateway chat-history requests read canonical session transcripts through SQLite’s active-branch projection. The reader selects bounded events and supplies ordering and cursor information for the chat response.

flowchart TD
  A[Chat history request] --> B[Session lookup]
  B --> C[SQLite projection snapshot]
  C --> D[Indexed bounded history read]
  D --> E[Chat display projection]
  E --> F[Current session access check]
  F --> G[History and session response]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +47, Tests +27, Config +1, Other +412. Total +487 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 6 76 29 +47
Tests 2 27 0 +27
Docs 0 0 0 0
Config 1 1 0 +1
Generated 0 0 0 0
Other 1 412 0 +412
Total 10 516 29 +487

Review metrics

Metric Value Why it matters
Reported SQL work Ordinary reads: 9→5 statements; dense marked reads: 12→7 The supplied real-reader measurements quantify reduced synchronous Gateway work.
Production and validation growth Production net +47 lines; tests +4; benchmark tooling +412 Production growth selects existing indexes and reuses snapshot facts; most added code provides reusable performance measurement.

Technical review

Best possible solution:

Keep the canonical reader and snapshot semantics while eliminating redundant queries and decoding, with the benchmark documenting remaining dense-marker costs.

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

Yes: current source exposes repeated suffix searches and duplicate child decoding, and the captured benchmarks provide concrete sparse-marker, trailing-marker, and many-child scenarios. No runtime reproduction was executed during this read-only review.

Is this the best way to solve the issue?

Yes: the patch optimizes the existing owner without introducing another projection store, changing persisted data, or weakening the selected-session access check.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This improves long-conversation loading with a bounded implementation and no established urgent outage.
  • 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 captured body reports before/after runs through the real SQLite history owner and registered Gateway handler on isolated synthetic stores, with matching selected-event/count results and all children returned after reducing query and decoding work.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body reports before/after runs through the real SQLite history owner and registered Gateway handler on isolated synthetic stores, with matching selected-event/count results and all children returned after reducing query and decoding work.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Shakker: 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 (2 earlier review cycles)
  • reviewed 2026-09-12T18:19:35.349Z sha f7fa4cc :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T18:43:56.317Z sha 2a92bd0 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit ffa6f5f into main Sep 12, 2026
203 checks passed
@steipete
steipete deleted the codex/session-history-performance branch September 12, 2026 19:02
@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

docs Improvements or additions to documentation 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. scripts Repository scripts size: L 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