Skip to content

improve: reduce overhead when counting transcript events - #149238

Merged
steipete merged 1 commit into
mainfrom
codex/sqlite-history-count-compilation
Sep 15, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/sqlite-history-count-compilation

Conversation

@steipete

@steipete steipete commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Related: #146371

What Problem This Solves

Repeated transcript count reads rebuild the same SQL query trees even when only the session or reset bound changes.

User Impact

Transcript-update fallback counts do less repeated JavaScript work. Counts, visibility, errors, cold restoration and read snapshots retain their existing behavior; no operator action is needed.

Why This Change Was Made

Lazily retain three compiled count-query forms per physical database connection and supply fresh session/reset bindings on every read. The full history reader and count reader still share the same selection predicate and index choices. Native statements and their lifecycle remain with the existing SQLite executor; no rows or authorization results are cached.

Evidence

One complete public-facade comparison on Node 26.8.2 / SQLite 3.53.4 against main 067c75b8aa65607a41d0a5b7cd102d80eec33bd6 passed all 14 timing cells, two branch cells, 14 malformed-data cells, two real cold restorations, and 70 reads across 13 shared-database binding/lifecycle checkpoints. Each timing cell used three warmup pairs and 21 alternating blocks. SQL, runtime bindings and native query plans match exactly; warm count-query compilations drop from one to zero while each native count query still executes once.

The one-marker medians were 1.443 → 1.327 ms before ANALYZE and 1.468 → 1.307 ms afterward (8.1–10.9% less elapsed time). Larger marker fixtures showed smaller observed reductions; the unchanged message-only path varied by roughly ±1%, including a 1.0% regression. Concurrent source-review and Git worktree-copy I/O overlapped this run, so the precise timing differences cannot be isolated from that interference. All samples were retained; no timings were retried or discarded. These are warm synthetic reader measurements, not whole-Gateway throughput or production latency guarantees.

Read-interval schema, typed rows, integrity and persisted database/WAL/journal hashes stayed unchanged. Four sessions share one database in the extra checks, covering fresh session/reset bindings, branch changes, append/replace, ANALYZE, message-only transitions, a new physical handle after close/reopen, and writes after reopening. Cold restore intentionally writes and preserves exact canonical event rows.

Independent review completed with no actionable P0–P2 findings and verified unchanged source. The focused Windows run passed all 28 tests across history-events, history-query-plan, history-marker-gap, and history-window on original head 216eb4bae64a36ce6165d3110aeb64859c252610. The current head 4919a0f6b6f968508ae2a8063b09ff249f6d8d42 is rebased onto main 273b6c5e11462e309ade080d620a03b9fb5021ca; range-diff reports a patch-identical change, and both touched files, the public history readers, and dependency pins retain their exact bytes. This preserves the independent review and focused proof for the unchanged patch.

Current-head CI run 35006650770 has passed all 12 relevant static jobs, covering production/core-test types, lint, schema, architecture, dependencies, and baseline guards. These exact-head hosted results cover the larger checks under local host scheduling constraints. The local changed-check command was inspected in dry-run mode; no full local-controller pass is claimed. All seven supplemental guards passed locally on current head 4919a0f: changelog attribution, extension and SDK wildcard exports, dependency pins, plugin boundaries, media helper use, and runtime sidecar loaders. Targeted formatting and whitespace checks also passed; the source remained clean and the check processes exited. Current-head CI run 35006650770 completed successfully, including the required openclaw/ci-gate (job 104525395303). All five previously failing fixture shards and both Windows jobs passed on this head.
The timing uncertainty identified in review is accepted for this bounded compilation change. Its acceptance criterion is the directly verified removal of repeated query construction (one warm count-query compilation becomes zero), exact SQL/binding/plan equivalence, preserved public behavior, and passing required gates. The retained three query forms per connection are the explicit memory tradeoff. The shared visibility predicate, snapshot owner, invocation-local bindings, and native executor already implement the review's proposed mitigation. Whole-Gateway latency improvement and an isolated percentage speedup are not established or required for this change; the timing table remains descriptive evidence with its interference disclosed.

The previous CI failures were outside the count change. The refreshed base includes the canonical QA fixture repair #149243, native PR fixture repair #149294 (7dc8a1e79659afb833df4bbfe363744c8d775e5c), and Codex model-attribution fixture repair #149301 (273b6c5e11462e309ade080d620a03b9fb5021ca). Both latter repairs have merged after their required CI passed. No failing or cancelled job is counted as a passing gate. The final integrated-main measurement below completed after the verified merge.

Final integrated measurement

Merged as 5b1912fd0cd3d574db201506f31e234c1a983f5c. One fixed comparison on that clean commit, Node 26.8.2 / SQLite 3.53.4 / Windows x64, passed all 14 timing cells, two branch cells, 14 malformed-data cells, two real cold restorations, and 70 fresh-binding/lifecycle reads. The three complete reader-owner modules match the reviewed candidate, and recorded shared dependencies and package pins match the before-owner baseline 067c75b8aa65607a41d0a5b7cd102d80eec33bd6.

The run used three warmup pairs and 21 alternating blocks per cell. All 588 timed block samples were retained; no retries or samples were discarded. The coordinator held other application benchmarks, tests, builds, installs and source snapshots for the run. Ordinary OS activity, lightweight coordination and saved-data audits remained possible. The process ran from 19:38:05.941Z to 19:39:27.439Z on September 15, 2026, exited 0, and left no direct children; source, dependency and harness checks passed after it settled.

Fixture Before → merged median without ANALYZE (ms) Before → merged median with ANALYZE (ms)
Message-only 0.80612 → 0.80873 0.80201 → 0.81478
One marker 1.30670 → 1.21813 1.47078 → 1.35260
100 interleaved markers 1.74909 → 1.61166 1.69694 → 1.62320
1000 interleaved markers 3.71708 → 3.53332 3.83938 → 3.43944
1000 trailing markers 3.72404 → 3.60888 3.63814 → 3.55022
1000 consecutive markers 4.63488 → 4.58608 4.49600 → 4.59076
Reset-kept prefix 3.38196 → 2.88777 2.96827 → 2.83351

One-marker medians were 6.8–8.0% lower and reset-prefix medians 4.5–14.6% lower. The analyzed consecutive-marker case was 2.1% slower, and the unchanged message-only path was 0.3–1.6% slower. All adverse results remain visible. These are descriptive warm synthetic medians, not isolated population estimates, p95 guarantees, whole-Gateway throughput, or a comparison of absolute timings across runs.

All 12 marker-containing cells again reduced warm count-query compilation from one to zero while retaining one native execution and one aggregate row. SQL, fresh bindings, query plans, counts, errors and read-interval storage fingerprints matched. Cold restoration intentionally writes and preserved exact canonical rows. No concurrent-writer race or cold-latency speedup is claimed.

@clawsweeper

clawsweeper Bot commented Sep 15, 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 15, 2026 15:49
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 15, 2026, 3:02 PM ET / 19:02 UTC (Revision 10).

ClawSweeper review

What this changes

Reuse compiled transcript-count queries with fresh session and reset values, and extend tests for counts across sessions and appends.

Merge readiness

✅ Ready for maintainer review

This remains a useful optimization beyond the merged scalar-count work. No actionable correctness or security defect was found, and the documented acceptance of timing uncertainty resolves the earlier decision concern.

Priority: P2
Reviewed head: 4919a0f6b6f968508ae2a8063b09ff249f6d8d42

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with meaningful reader-level proof and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Node/SQLite public-reader comparison exercises the changed count owner across session/reset bindings, appends, replacements, cold restoration, and reopened handles, reporting unchanged results and zero warm count-query compilations. Timing interference limits percentage-speedup claims but does not undermine the accepted compilation-saving criterion.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Node/SQLite public-reader comparison exercises the changed count owner across session/reset bindings, appends, replacements, cold restoration, and reopened handles, reporting unchanged results and zero warm count-query compilations. Timing interference limits percentage-speedup claims but does not undermine the accepted compilation-saving criterion.
Evidence reviewed 8 items Introduced change and current-main necessity: The complete pinned introduction contains only the count-query compilation change and its test extension. Fetched main still constructs and compiles the count selection on every call; this optimization remains absent there.
Fresh bindings and existing execution ownership: The cache has three possible query shapes per physical database. prepareSqliteQueryTakeFirstSync creates invocation-local bindings and executes through the existing executor; no transcript rows, native statements, or authorization decisions enter the new cache.
Snapshot and public entrypoint: readSessionMessageCountAsync calls the history count reader through existing cold-restoration and reconciliation handling. The count reader retains withCurrentProjectionSnapshot, including its deferred transaction and current projection checks.
Findings None None.
Security None None.

How this fits together

OpenClaw counts visible transcript events when Gateway updates need a fallback sequence number. The SQLite history reader combines visible messages and markers within one validated read snapshot.

flowchart TD
  A[Transcript update] --> B[Fallback count reader]
  B --> C[Validated SQLite snapshot]
  C --> D[Choose marker, branch, or reset query]
  D --> E[Reuse compilation with fresh bindings]
  E --> F[Count visible events]
  F --> G[Gateway sequence number]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +61, Tests +13. Total +74 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 73 12 +61
Tests 1 14 1 +13
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 87 13 +74

Review metrics

Metric Value Why it matters
Compilation tradeoff Warm count-query compilations: 1 → 0; at most 3 retained forms per connection The supplied comparison and source establish the intended saving without relying on an isolated latency percentage.

Technical review

Best possible solution:

Keep the shared visibility predicate and snapshot owner while reusing bounded compiled query forms through the existing SQLite executor.

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

Not applicable to a correctness bug: current-main source directly shows repeated query construction, and the supplied public-reader comparison measures its removal.

Is this the best way to solve the issue?

Yes. The patch reuses the established compilation helper while preserving fresh bindings, shared selection semantics, and native execution ownership.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded performance improvement to the transcript-update fallback reader.
  • 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 supplied Node/SQLite public-reader comparison exercises the changed count owner across session/reset bindings, appends, replacements, cold restoration, and reopened handles, reporting unchanged results and zero warm count-query compilations. Timing interference limits percentage-speedup claims but does not undermine the accepted compilation-saving criterion.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Node/SQLite public-reader comparison exercises the changed count owner across session/reset bindings, appends, replacements, cold restoration, and reopened handles, reporting unchanged results and zero warm count-query compilations. Timing interference limits percentage-speedup claims but does not undermine the accepted compilation-saving criterion.

Evidence

What I checked:

  • Introduced change and current-main necessity: The complete pinned introduction contains only the count-query compilation change and its test extension. Fetched main still constructs and compiles the count selection on every call; this optimization remains absent there. (src/config/sessions/session-accessor.sqlite-history-projection.ts:153, 4919a0f6b6f9)
  • Fresh bindings and existing execution ownership: The cache has three possible query shapes per physical database. prepareSqliteQueryTakeFirstSync creates invocation-local bindings and executes through the existing executor; no transcript rows, native statements, or authorization decisions enter the new cache. (src/infra/kysely-sync.ts:184, 4919a0f6b6f9)
  • Snapshot and public entrypoint: readSessionMessageCountAsync calls the history count reader through existing cold-restoration and reconciliation handling. The count reader retains withCurrentProjectionSnapshot, including its deferred transaction and current projection checks. (src/config/sessions/session-accessor.sqlite-history-events.ts:509, 4919a0f6b6f9)
  • Behavioral coverage: The extended existing fixture alternates sessions sharing a database and checks counts before and after append. Existing history tests additionally cover reset-kept prefixes and malformed active versus inactive markers. (src/config/sessions/session-accessor.sqlite-history-marker-gap.test.ts:65, 4919a0f6b6f9)
  • Supplied production-reader proof and review disposition: The complete supplied PR body, captured under sourceRevision 47aaa488174beea632a656cf710abb002dfecee25cf20ee10fe708e61e88d80f, reports actual public-reader comparisons on Node 26.8.2 / SQLite 3.53.4: 14 timing cells, malformed-data checks, two cold restorations, and 70 reads across 13 binding/lifecycle checkpoints. SQL, bindings, plans, counts, and stored bytes matched; warm count-query compilations fell from one to zero. The body explicitly accepts the bounded memory tradeoff and disclosed timing interference. These are supplied observations, not executions performed during this review. (4919a0f6b6f9)
  • Prior merged work and routing history: Current-main history records scalar counting, selective query plans, marker-gap improvements, and paging allocation work. GitHub confirms improve: count marker-heavy transcripts without display metadata #146382 merged at 5b49bdf; it removes display metadata work, whereas this PR removes repeated query construction. (src/config/sessions/session-accessor.sqlite-history-projection.ts:153, 5b49bdf40bad)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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 (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-15T16:09:54.832Z sha 216eb4b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T16:19:02.024Z sha 216eb4b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T16:28:41.731Z sha 216eb4b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T16:40:27.590Z sha f772cd6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T16:59:10.422Z sha f772cd6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T17:40:35.284Z sha f772cd6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T18:28:21.755Z sha 4919a0f :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T18:48:40.503Z sha 4919a0f :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 15, 2026
@steipete
steipete force-pushed the codex/sqlite-history-count-compilation branch from 216eb4b to f772cd6 Compare September 15, 2026 16:32
@steipete
steipete force-pushed the codex/sqlite-history-count-compilation branch from f772cd6 to 4919a0f Compare September 15, 2026 18:18
@steipete
steipete merged commit 5b1912f into main Sep 15, 2026
212 checks passed
@steipete
steipete deleted the codex/sqlite-history-count-compilation branch September 15, 2026 19:15
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 16, 2026
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