Skip to content

fix: reduce repeated SQLite work in session operations - #148366

Merged
steipete merged 5 commits into
mainfrom
codex/session-sql-query-audit
Sep 14, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/session-sql-query-audit

Conversation

@steipete

@steipete steipete commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Related: #138042, #148057, #148442, #148445, #148504

What Problem This Solves

Cleanup, exact-session searches, and ACP replay appends repeat SQLite work over unrelated or already-protected history as stores grow.

User Impact

Reduces synchronous CPU spent on large session stores while preserving search visibility, cleanup eligibility, replay limits, and byte accounting. No schema change, new index, migration, configuration option, or retention change.

Why This Change Was Made

Cleanup rejects recently updated nodes before scanning transcript timestamps. Exact-session search narrows its dirty-state lookup to the selected session, and transcript generation creation stops reading back an unused value.

ACP replay uses indexed minimum/maximum sequence values to exclude histories that cannot exceed the event cap. Possible overflows still receive an exact count, preserving gapped sequences and stricter limits after reopening.

Evidence

Synthetic CPU measurements on Node 26.8.2 / SQLite 3.53.4, using existing canonical indexes:

Measured operation and fixture Original CPU Updated CPU
ACP replay append, 20 sessions / 100,000 events 6.208 ms 0.707 ms
ACP replay append, over-cap gapped history 7.518 ms 4.756 ms
Full cleanup planner, 12 fresh nodes / 96,000 retained events 17.402 ms 0.397 ms
Exact-session FTS query, 10,000 clean session states 0.248 ms 0.078 ms

Complete result comparisons passed for 6 cleanup shapes, 144 FTS cells, and 9 replay fixtures. The paired replay comparison used one warmed connection, seven alternating pairs of 40 appends, identical seeding, and 21 matching retained-row fingerprints. Its 100,000-event fixture is about 14.4 MB, with an explicit larger byte cap to isolate event-count work. Final emitted ACP SQL matches the measured query exactly.

These are component measurements. The search reconciliation preflight remains a separate cost (6.810 ms in the clean 10,000-state fixture). Removing the unused generation read has no reliable latency claim. A blanket search NOT EXISTS rewrite and a fixed-status partial-index rewrite were rejected after opposite workloads regressed, including a 17× slowdown for a recent delivery hit.

The retained SQL and Custodian source passed 192 focused cases: 142 session/ACP/recovery cases and 50 Custodian cases. After inheriting the canonical CI repairs, another 128 selected routing, recovery, auth, integration, and boundary cases passed. All 45 browser E2E cases across the six publication-helper consumers passed with the final dependency installation. Relevant changed-file gates, typechecks, lint, formatting, and independent P0–P2 reviews passed. Required hosted CI passed on the reviewed head.

Inherited fixes and test synchronization

Inventory counting through compact indexes is already on main (#148445), so this PR removes its superseded count change. All 20 actual-owner comparisons preserve expected counts. The retained SQL changes use existing owners and indexes.

Main also contains the canonical provider-integration and wizard-routing repair (#148504). The five scoped-config assertions reused from #148442 protect exactly one broker-backed recovery registration and exclusion from the thread-based wizard project. The new regression failed with the missing registration and passes with the canonical repair. The Custodian test waits for the enabled immediate-submit choice button introduced on main; its lifecycle assertions remain intact.

The publication LRU fixture could emit branch state for a previous session after navigation because it searched older requests even when the latest subscription was empty. An identical delayed-startup browser diagnostic fails before and passes after the fixture correction, while preserving the original publication retry parameters. The helper now honors only the latest subscription and waits for the selected session. Assertions and timeouts are unchanged; there are no production UI changes.

@clawsweeper

clawsweeper Bot commented Sep 14, 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 14, 2026 16:11
@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 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 14, 2026, 5:52 PM ET / 21:52 UTC (Revision 8).

ClawSweeper review

What this changes

Reduces repeated SQLite reads during session cleanup, transcript searches, and ACP replay recording, and corrects synchronization in supporting tests.

Merge readiness

✅ Ready for maintainer review

Keep open: the retained optimizations remain useful and are absent from current main. No blocking correctness or security defect was found; the component measurements and verified hosted CI support the patch.

Priority: P2
Reviewed head: cbdcd2644343bcc58c18fa914c2a96a0d41242bd

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, behavior-preserving optimization with useful component comparisons, relevant coverage, and successful hosted CI.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured body reports real SQLite component comparisons for replay appends, cleanup planning, and scoped FTS on Node 26.8.2 / SQLite 3.53.4, with improved CPU measurements and matching results across ordinary and gapped histories; browser diagnostics cover the fixture correction. This supports the bounded claims, not whole-Gateway latency.
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 real SQLite component comparisons for replay appends, cleanup planning, and scoped FTS on Node 26.8.2 / SQLite 3.53.4, with improved CPU measurements and matching results across ordinary and gapped histories; browser diagnostics cover the fixture correction. This supports the bounded claims, not whole-Gateway latency.
Evidence reviewed 11 items Introduced scope and current-main necessity: The host verified the merge-base-to-head introduction and test-merge parents. Local comparison confirms all four production optimizations remain absent from fetched main; the secrets files are base-only work, not this PR's changes.
Replay retention invariant: The existing STRICT schema makes sequence values non-null integers unique within each session. Consequently, count above the cap implies max(seq)-min(seq) is at least the cap; candidate histories still receive an exact count before deletion. Existing gapped-history coverage also checks retained rows and byte accounting.
Cleanup and generation semantics: Rejecting a recently updated node early preserves the existing maximum-of-node-and-transcript age predicate. All four generation-creation call sites ignore its return value; insertion and generation rotation retain their existing behavior.
Findings None None.
Security None None.

How this fits together

OpenClaw stores session transcripts and replay history in SQLite. Cleanup requests, transcript searches, and agent-client updates enter these storage owners, which return search results or maintain retained history.

flowchart TD
  A[Session operations] --> B[SQLite storage owners]
  B --> C[Cleanup age checks]
  B --> D[Scoped transcript search]
  B --> E[Replay sequence bounds]
  C --> F[Preserved cleanup eligibility]
  D --> G[Visible search results]
  E --> H[Exact trimming and byte accounting]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +14, Tests +38. Total +52 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 36 22 +14
Tests 5 52 14 +38
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 88 36 +52

Review metrics

None.

Technical review

Best possible solution:

Keep the optimizations within the existing storage owners while preserving exact retention, search visibility, and generation semantics.

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

Not applicable to a functional defect: this is a behavior-preserving optimization with supplied comparative SQLite measurements; the broader Gateway-stall report was not reproduced here.

Is this the best way to solve the issue?

Yes: the patch removes avoidable work without introducing indexes, stored counters, competing owners, or changed retention rules.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: A bounded performance improvement reduces synchronous SQLite work on large session stores without changing product contracts.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 real SQLite component comparisons for replay appends, cleanup planning, and scoped FTS on Node 26.8.2 / SQLite 3.53.4, with improved CPU measurements and matching results across ordinary and gapped histories; browser diagnostics cover the fixture correction. This supports the bounded claims, not whole-Gateway latency.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body reports real SQLite component comparisons for replay appends, cleanup planning, and scoped FTS on Node 26.8.2 / SQLite 3.53.4, with improved CPU measurements and matching results across ordinary and gapped histories; browser diagnostics cover the fixture correction. This supports the bounded claims, not whole-Gateway latency.

Evidence

What I checked:

  • Introduced scope and current-main necessity: The host verified the merge-base-to-head introduction and test-merge parents. Local comparison confirms all four production optimizations remain absent from fetched main; the secrets files are base-only work, not this PR's changes. (src/acp/event-ledger.ts:129, cbdcd2644343)
  • Replay retention invariant: The existing STRICT schema makes sequence values non-null integers unique within each session. Consequently, count above the cap implies max(seq)-min(seq) is at least the cap; candidate histories still receive an exact count before deletion. Existing gapped-history coverage also checks retained rows and byte accounting. (src/acp/event-ledger.prepared.test.ts:153, cbdcd2644343)
  • Cleanup and generation semantics: Rejecting a recently updated node early preserves the existing maximum-of-node-and-transcript age predicate. All four generation-creation call sites ignore its return value; insertion and generation rotation retain their existing behavior. (src/config/sessions/session-accessor.sqlite-lifecycle-artifacts.ts:65, cbdcd2644343)
  • Search visibility and bindings: The additional dirty-state restriction uses the same session ID already required by the outer query, with its placeholder bound in matching order. Namespace, role, ordering, snapshot, and reconciliation behavior remain intact; the added test protects stale-index exclusion when transcript rows are gone. (src/config/sessions/session-transcript-search.ts:204, cbdcd2644343)
  • Supporting tests preserve their contracts: The publication helper now observes the latest subscription and optionally waits for the selected session, matching the production subscription replacement behavior. The Custodian test waits for an enabled choice without weakening lifecycle assertions; the routing assertion protects one broker-backed recovery registration. (ui/src/e2e/chat-github-publication.test-support.ts:58, cbdcd2644343)
  • Captured component proof: The supplied complete PR body, context sourceRevision 3950a6a4aaa4d2edeb0ca4c94dda9a318b5e40730bd781b36d39f76708e1366d, reports Node 26.8.2 / SQLite 3.53.4 comparisons for replay appends, the cleanup planner, and exact-session FTS. It records matching results across 6 cleanup shapes, 144 FTS cells, and 9 replay fixtures, including gapped histories, and explicitly limits the claims to components. It also records the publication fixture's delayed-startup failure before correction and success afterward. These measurements were inspected, not rerun. (cbdcd2644343)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: 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 (7 earlier review cycles)
  • reviewed 2026-09-14T16:34:12.451Z sha ea2b84a4cf05dac16f8bb88d30fc233084dcb8bc :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T17:33:36.851Z sha 35e25d6d022ab0161e4410d31a2ca3086fbeb595 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T17:56:41.667Z sha 3467dad188d02edbf4215b4bbaf219475fed70e7 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T18:47:09.925Z sha 09e255d0f3e45a5172de388047fdb84123c52db3 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T19:32:28.266Z sha f4ea60aa06f2796508414bf4ea72171759846593 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T20:01:16.534Z sha a0b226d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T21:12:36.502Z sha cbdcd26 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/session-sql-query-audit branch from ea2b84a to 35e25d6 Compare September 14, 2026 17:01
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 14, 2026
@steipete
steipete force-pushed the codex/session-sql-query-audit branch from 3467dad to 09e255d Compare September 14, 2026 18:33
@openclaw-barnacle openclaw-barnacle Bot added the app: web-ui App: web-ui label Sep 14, 2026
@steipete
steipete force-pushed the codex/session-sql-query-audit branch 2 times, most recently from f4ea60a to a0b226d Compare September 14, 2026 19:52
@steipete
steipete force-pushed the codex/session-sql-query-audit branch from a0b226d to cbdcd26 Compare September 14, 2026 21:06
@steipete
steipete merged commit 68313e2 into main Sep 14, 2026
204 of 205 checks passed
@steipete
steipete deleted the codex/session-sql-query-audit branch September 14, 2026 21:53
@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 15, 2026
* perf(sessions): reduce redundant SQLite scans

* style(acp): avoid shadowed query builder names

* test(ui): exercise session eviction through the wizard choice button

* test(ui): wait for the current publication subscription

* test(ci): protect wizard recovery broker routing

Retain the routing regression from openclaw#148442 while inheriting the canonical registration repair in openclaw#148504. Require one infra registration and exclusion from the thread-based wizard project.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui 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