Skip to content

improve: load session history with fewer SQLite queries - #146390

Merged
steipete merged 3 commits into
mainfrom
codex/session-history-joined-admission
Sep 12, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/session-history-joined-admission

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

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.

Reader Five queries Three queries
Recent 20 of 80 messages 0.2175 ms 0.1643 ms
20-message page, offset 40 of 80 0.2127 ms 0.1513 ms
Recent 20 of 10,000 messages 0.1999 ms 0.1564 ms
20-message page, offset 40 of 10,000 0.1942 ms 0.1391 ms

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).

@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.

@steipete
steipete marked this pull request as ready for review September 12, 2026 20:08
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 12, 2026
@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, 7:39 PM ET / 23:39 UTC (Revision 6).

ClawSweeper review

What this changes

The 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
Reviewed head: ea45c3e9544138c25e3c70f756ba8f8ceab2a7c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with convincing bounded measurements, preserved contracts, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured PR body reports paired execution of the actual history readers against real SQLite storage, with equal returned results and fewer statements after the change; focused tests supplement that evidence. These measurements substantiate the internal optimization without claiming full browser or RPC improvement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured PR body reports paired execution of the actual history readers against real SQLite storage, with equal returned results and fewer statements after the change; focused tests supplement that evidence. These measurements substantiate the internal optimization without claiming full browser or RPC improvement.
Evidence reviewed 9 items Introduced production behavior: The pinned introduced delta changes the shared projection query while preserving its deferred transaction, cold-storage error, readiness predicates, and read-only acquisition path. The singleton target preserves empty transcripts.
Fresh bindings and existing execution owner: prepareSqliteQuerySync compiles once, creates invocation-local bindings, and executes through the existing synchronous statement-cache owner; the PR does not cache query results or native statements independently.
Behavioral coverage: The added history test checks fresh generations, append-after-clear cursors, and switching session bindings. The archive-race table now exercises the history reader against a second SQLite connection. The byte-size guard retains its pending-index and overflow-read assertions.
Findings None None.
Security None None.

How this fits together

OpenClaw’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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +32, Tests +53. Total +85 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 1 84 52 +32
Tests 4 62 9 +53
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 146 61 +85

Review metrics

Metric Value Why it matters
Measured warm-read work History: 5 → 3 statements; Gateway tail: 10 → 8 Supplied paired measurements demonstrate reduced database work while keeping the performance claim narrower than full RPC latency.
Production versus test growth Production net +32 lines; tests net +53 lines Production growth implements combined readiness and compilation reuse; test growth protects binding freshness and archive consistency.

Technical review

Best 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.

Labels

Label justifications:

  • P2: This is a measured, bounded history-loading performance improvement with no demonstrated 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 captured PR body reports paired execution of the actual history readers against real SQLite storage, with equal returned results and fewer statements after the change; focused tests supplement that evidence. These measurements substantiate the internal optimization without claiming full browser or RPC improvement.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured PR body reports paired execution of the actual history readers against real SQLite storage, with equal returned results and fewer statements after the change; focused tests supplement that evidence. These measurements substantiate the internal optimization without claiming full browser or RPC improvement.

Evidence

What I checked:

  • Introduced production behavior: The pinned introduced delta changes the shared projection query while preserving its deferred transaction, cold-storage error, readiness predicates, and read-only acquisition path. The singleton target preserves empty transcripts. (src/config/sessions/session-accessor.sqlite-active-projection.ts:80, ea45c3e95441)
  • Fresh bindings and existing execution owner: prepareSqliteQuerySync compiles once, creates invocation-local bindings, and executes through the existing synchronous statement-cache owner; the PR does not cache query results or native statements independently. (src/infra/kysely-sync.ts, ea45c3e95441)
  • Behavioral coverage: The added history test checks fresh generations, append-after-clear cursors, and switching session bindings. The archive-race table now exercises the history reader against a second SQLite connection. The byte-size guard retains its pending-index and overflow-read assertions. (src/config/sessions/session-accessor.sqlite-history-events.test.ts:132, ea45c3e95441)
  • Gateway fixture repair: Each case installs a fresh runtime factory; the profile-authorization case still delegates to the actual router. Assertions and cleanup remain intact, and no production authorization code changes. (src/gateway/server/ws-connection/authenticated-request-dispatch.lifetime.test.ts:52, ea45c3e95441)
  • Current-main necessity: Fetched main still performs the separate archive, projection, and unclassified-row checks. The merged improve: speed up loading long session histories #146286 optimized other history work and carried generation into the snapshot; it does not supersede this query consolidation. (src/config/sessions/session-accessor.sqlite-active-projection.ts, 51caa9442e47)
  • Supplied production-reader measurements: The complete captured PR body, context sourceRevision a81bd595e67366a9c7a6094427c500000ab1fede85eef88abc5d45974af89a5f, reports paired original/candidate executions against real synthetic SQLite storage on Node 24.21.0 and SQLite 3.53.4. Warm recent/page reads drop from five statements to three, with deep-equal results and 22–29% lower median reader time; the Gateway tail drops from ten statements to eight. The body explicitly excludes full RPC/browser latency, cold opens, restoration, and rebuilding from those claims. (ea45c3e95441)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • openclaw/openclaw-secops: 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-12T20:16:11.844Z sha 1c36877 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T20:32:59.937Z sha 5e783b6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T20:45:36.299Z sha 5e783b6 :: blocked before merge. :: none
  • reviewed 2026-09-12T21:53:26.315Z sha 23cadd2 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T23:22:41.644Z sha ea45c3e :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/session-history-joined-admission branch from 5e783b6 to 23cadd2 Compare September 12, 2026 21:43
@steipete
steipete requested a review from a team as a code owner September 12, 2026 23:16
@steipete
steipete merged commit 11c9589 into main Sep 12, 2026
191 of 193 checks passed
@steipete
steipete deleted the codex/session-history-joined-admission branch September 12, 2026 23:46
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
)

* perf(sessions): reduce history projection admission work

* test(sessions): trace joined readiness checks in byte-size guard

* test(gateway): isolate profiled dispatch fixture runtime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: S 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