Skip to content

perf(sqlite): trim reader admission and transaction envelopes - #166074

Merged
steipete merged 5 commits into
mainfrom
dbasync/sqlopt-envelope
Oct 6, 2026
Merged

steipete merged 5 commits into
mainfrom
dbasync/sqlopt-envelope

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Chat turns execute avoidable SQLite freshness probes and transaction controls. New agent readers probe freshness twice during admission, point transcript reads open explicit transactions, and pure nested transcript reads create savepoints inside an existing snapshot.

User Impact

Session reads do less SQLite bookkeeping while preserving stored data, consistency, and write-admission guarantees.

Why This Change Was Made

Share the initial agent-admission probe, use statement snapshots for point statistics, mutation clocks, pending archives and retained watermarks, and let pure transcript readers join the caller's transaction. Restore temporary busy policy once after write admission and reuse inherited lock deadlines without an unused timeout query.

Main already owns the combined hot/cold watermark query (#166041) and the shared-state admission/query freshness scope (#166053). Integration preserves those implementations and removes their duplicate production hunks from this PR. General write transactions retain BEGIN IMMEDIATE, rollback savepoints, FIFO, live transaction/commit authority, original lock budgets, and accepted-write settlement.

No schema, index, persistent cache, retention, durability, worker service, environment name, or SDK contract changes. Updates and persisted-state admission policy are unchanged; no published-driver migration cell is required.

Evidence

Current candidate: 146a71a92f308b2a6acd5a105116c4a4eb3f2f5c, integrated with main b2fab204731e3e4e3f3bab2d46d910115494ad3f using merge commits. Both watermark conflicts preserve main's combined query and cold/hot precedence coverage. The later state-reader conflict preserves main's result wrapping around the same synchronous freshness scope.

  • Fresh Codex P2 autoreview is scoped-clean on the integrated candidate. ClawSweeper completed its exact-head review at 2026-10-06T11:30:18.644Z (run 37456274387); its remaining next step was to record the matched measurements and generated SDK report, both now present below. It reported no actionable correctness/security defect.
  • Initial integrated proof: 188 tests in 14 files passed (node scripts/run-vitest.mjs <focused paths> --maxWorkers=1, 791.37 s wall); 57 additional transaction/import tests passed in 44.47 s. This includes runtime-process-build-graph, get-reply/history/reconciliation import closures, deadline/restoration, peer-commit freshness, WAL snapshots, archive settlement, FIFO and authority revocation.
  • After the second integration, all 85 selected state/entry-reader tests passed (224.67 s wall). The existing native worker fixtures and cold compilation dominate these costs; assertions reuse owner fixtures. Current-head core production types pass. The second integration passed all 27 refreshed core-test type graphs (369.30 s wall) and Madge with zero cycles. The latest main integration passes core production types, all 27 core-test graphs (771.64 s), Madge (zero cycles, 156.75 s), and 52 Copilot/settlement/import tests (915.48 s), including all 37 Copilot journal cases and the previously failing rollback assertion.
  • Released SDK check against v2026.10.1-beta.1: exported signatures, sync/async behavior, parameters, callback shapes and export availability are unchanged, including reachable runSqliteImmediateTransaction and openOpenClawAgentDatabaseReadOnly. No compatibility adapter or deprecation record is required. The generated exact-base/head API comparison completed successfully in 1,560.20 s and reports no Plugin SDK API changes (digest ff7b090f); no acknowledgement waiver or normalizer change was used.
  • No worker cutover or new host-owner requirement is introduced. Existing fork routing remains appropriate. No module was added/extracted; imported dependencies already belong to the compiled-wrapper inventory.
  • Matched three-run measurements completed successfully against the exact integrated baseline and candidate using identical restored-harness hashes, full Git tree identities, selected source hashes and isolated synthetic Gateways. Both sides use Node 24.21.0 / SQLite 3.53.4; calibration independently proves 8 native calls, 2 prepares and 7 successful SQL statements on main and worker. All 13 turns, child completion, control-plane RPCs, cron, committed compaction and graceful shutdown pass in every run. These are successful statement counts on a loaded Mac, not latency measurements.
All-thread SQL phase Before median (range) After median (range) Change
First turn 7,062 (7,030–7,283) 6,954 (6,870–7,184) -108 (-1.53%)
Per warmed turn 3,094.0 (3,092.6–3,104.2) 3,000.1 (2,996.4–3,001.2) -93.9 (-3.03%)
Compaction 1,115 (1,104–1,133) 1,099 (1,078–1,122) -16 (-1.43%)
Full workload, including boot/shutdown 58,308 (58,079–58,504) 56,690 (56,655–57,229) -1,618 (-2.77%)

The three requested phase medians improve; the historical first-turn regression is absent in this matched comparison. busy_timeout medians are first turn 173→163, warmed turn 93.1→94.4, and compaction 31→31; no aggregate warmed busy-timeout reduction is claimed. Warmed main/worker/helper medians are 7.1/3,054.0/32.0→8.7/2,961.0/30.8 (component medians need not sum to the median total). All target phases have zero execution/prepare errors. Each side records three unsuccessful BEGIN IMMEDIATE attempts during successful shutdowns, excluded by the fixed observer contract. All fixture processes exited and tracked source stayed clean. The campaign remains above its 500-statements-per-warmed-turn target.

Hosted CI on 51d4370 failed the Copilot journal rollback fixture before its intended failure injection: the persistent fail_copilot_tool_result trigger violated canonical schema admission. The test blob is identical on baseline and candidate (a5bfc8c7f524170449ec705504152c5d2836bcd2); main already fixed it in b2fab204731e3 using the existing worker-local TEMP fault fixture while retaining the injected-error and complete-group rollback assertions. This integration includes that fix. CI run 37453164206 had one failed test job plus the aggregate gate and 62 fail-fast cancellations; those cancellations are not passing coverage. No CI rerun or admin exception was used. The earlier PR-description check failure was corrected by matching the current template headings, and its replacement check passed.

Current-head CI run 37456193481 reported a 30-second agent.wait client timeout in the startup-recovery WebChat test; 68 jobs passed and 16 were cancelled by fail-fast. The same failure independently occurs in scheduled main job 112247264184, at the same line 323 / caller 329 with CLIENT_TIMEOUT, method agent.wait, timeoutMs 30000 and requestSent true. Its 54.811-second test duration is below the outer budget. Sixteen causal test/wait/queue/client paths are byte-identical across the actual CI baseline, PR, tested merge, scheduled main and inspected current main.

The race predates this PR: #165156 used a terminal wait to synchronize queue insertion; #165996 correctly made that insertion nonterminal. An early waiter is therefore not awakened by queue registration, and its client deadline can precede the equal server deadline while the test deliberately holds recovery. Five serial local file runs on each revision were completed without edits: PR run 3 reproduced the exact CI error; four other PR runs and all five baseline runs exceeded the outer 90-second budget under host load, sometimes with 11 skills watchers reported during teardown. Those outer timeouts are inconclusive, not matching main reproductions. The scheduled-main log supplies independent inheritance proof.

This failure is qualified for the explicitly authorized native inherited-failure route. The evidence binds run attempt 1, actual checkout e889011859eb3561a81a9f19c536ce9fd67f396e (parents ace67a3 / 146a71a), the single failed test job, its aggregate gate, and all 16 monitor-caused cancellations. Cancelled work is not passing coverage. No CI rerun was requested. A separate fixture follow-up can use the existing dispatch-settlement observer before the queued-state probe; no larger timeout or weaker assertion is needed.

The prior local large-graph timeout remains unexplained. The unchanged case passed on Linux Testbox in 1.864 s as part of 76 passing tests (run 37436198513); that replay is not claimed as a fix. No timeout or assertion was relaxed.

Historical pre-integration measurement

Original baseline 4304c49a8ea76, candidate f54374536873c; three fresh fixtures and ten warmed turns per revision. Median all-thread SQL executions: warmed turn 2,733.4 → 2,636.4; first turn 6,840 → 6,927; compaction 902 → 844; full workload 52,658 → 51,345. First-turn and aggregate busy-timeout counts increased, so no first-turn improvement is claimed from those samples. The completed matched integration measurements above replace this historical comparison for landing.

Campaign overlaps include #165680, #165552, #165885, #165895, #165890, #165901, #165859, #165894, #165904, #165921, #162433, #166041, #166053 and #166054. Hunks remain focused on reader/transaction envelopes and preserve landed sibling behavior. The original base includes #165804's unrelated cleanup. Release-note context: reduce redundant SQLite admission and transaction work during session reads without changing stored data or concurrency guarantees.

Share the first agent admission probe and shared-state read scope, use single-statement transcript snapshots, and reuse existing read transactions. Fuse hot/cold watermark queries and avoid redundant busy-timeout restoration and inherited-deadline probes.

Preserve foreign-commit freshness, pinned snapshots, write FIFO and live authority. No schema, index, retention, durability, or SDK contract changes.
Keep the combined watermark query private in its original declaration owner. Retain the one-statement snapshot while leaving the hot-only module and indirectly reachable SDK signatures unchanged.
@clawsweeper

clawsweeper Bot commented Oct 6, 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 size: M labels Oct 6, 2026
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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 Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 6, 2026, 7:30 AM ET / 11:30 UTC (Revision 3).

ClawSweeper review

What this changes

The PR reduces SQLite freshness probes and transaction bookkeeping for session reads while preserving existing snapshots and write-admission behavior.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR retains useful optimizations beyond the merged sibling work. Source review found no actionable correctness or security defect; the previously identified validation prerequisite remains unfinished in the captured evidence.

Priority: P2
Reviewed head: 146a71a92f308b2a6acd5a105116c4a4eb3f2f5c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The implementation is focused and source review found no blocking defect; its declared final comparative and SDK validation remains unfinished.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies MEMBER authorship, so the ordinary external-contributor proof gate does not apply. The captured evidence reports isolated Gateway statement counts on an earlier candidate and integrated SQLite boundary validation; final matched measurements remain explicitly pending. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies MEMBER authorship, so the ordinary external-contributor proof gate does not apply. The captured evidence reports isolated Gateway statement counts on an earlier candidate and integrated SQLite boundary validation; final matched measurements remain explicitly pending. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduced changes: Reviewed the verified b2fab20-to-146a71a92f308b2a6acd5a105116c4a4eb3f2f5c delta and corresponding original implementation. Remaining changes concern admission probes, point-read envelopes, nested read snapshots, busy-policy restoration, and inherited deadlines.
Admission safeguards preserved: Initial admission shares its freshness probe with existing version, persistence, ownership, and canonical-validation checks. Revalidation of an existing reader still explicitly requests a fresh probe; dynamic authorizers retain the uncached path.
Snapshot ownership: Point statistics and mutation fences each execute one combined statement. Composite hot reads retain a deferred transaction when none exists and otherwise join the caller's snapshot with transaction-usability checks. The changed regression exercises a peer archive during a retained WAL snapshot and refusal after that snapshot ends.
Findings None None.
Security None None.

How this fits together

OpenClaw stores session transcripts and metadata in per-agent SQLite databases. Readers supply history and freshness information to chat processing, while transaction helpers coordinate writes and lock admission.

flowchart TD
  A[Chat and history requests] --> B[Agent database admission]
  B --> C[Session readers]
  C --> D{Read shape}
  D --> E[Single statement snapshot]
  D --> F[Composite transaction snapshot]
  E --> G[Transcript and metadata results]
  F --> G
Loading

Before merge

  • Complete next step (P2) - Complete and record the matched first-turn, warmed-turn, and compaction measurements plus the generated SDK API comparison for the pinned candidate against the integrated baseline.
Agent review details

Security

None.

PR surface

Source -2, Tests +98, Docs +10. Total +106 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 9 70 72 -2
Tests 8 106 8 +98
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 186 80 +106

Review metrics

None.

Technical review

Best possible solution:

Keep admission and snapshot decisions with their existing owners, eliminating redundant controls while preserving consistency, stored data, and lock budgets.

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

Not applicable as a bug reproduction: this is a performance optimization, and source inspection establishes the redundant controls it removes.

Is this the best way to solve the issue?

Yes. The patch reuses existing admission and snapshot owners, retains transactions for composite reads, and introduces no competing cache or persistence contract.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded session-storage performance improvement without a demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository State identifies MEMBER authorship, so the ordinary external-contributor proof gate does not apply. The captured evidence reports isolated Gateway statement counts on an earlier candidate and integrated SQLite boundary validation; final matched measurements remain explicitly pending. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced changes: Reviewed the verified b2fab20-to-146a71a92f308b2a6acd5a105116c4a4eb3f2f5c delta and corresponding original implementation. Remaining changes concern admission probes, point-read envelopes, nested read snapshots, busy-policy restoration, and inherited deadlines. (146a71a92f30)
  • Admission safeguards preserved: Initial admission shares its freshness probe with existing version, persistence, ownership, and canonical-validation checks. Revalidation of an existing reader still explicitly requests a fresh probe; dynamic authorizers retain the uncached path. (src/state/openclaw-agent-db-readonly-open.ts:61, 146a71a92f30)
  • Snapshot ownership: Point statistics and mutation fences each execute one combined statement. Composite hot reads retain a deferred transaction when none exists and otherwise join the caller's snapshot with transaction-usability checks. The changed regression exercises a peer archive during a retained WAL snapshot and refusal after that snapshot ends. (src/config/sessions/session-cold-storage-read.ts:44, 146a71a92f30)
  • Write guarantees preserved: Inherited deadlines avoid an unused timeout query. Preparation, BEGIN IMMEDIATE, transaction and commit admission, rollback handling, and refusal to join an existing transaction remain intact. Busy-policy restoration stays early and becomes idempotent. The patch does not materially transfer or extend authority. (src/infra/sqlite-transaction.ts:524, 146a71a92f30)
  • Merged overlap remains distinct: GitHub verifies perf(sqlite): batch session snapshot and watermark queries #166041 and perf(sqlite): batch placement and session metadata reads #166053 as merged. Current-main comparison still shows the reader and transaction-envelope optimizations proposed here; those merged query-batching changes do not supersede the remaining work. (src/config/sessions/session-accessor.sqlite-transcript-watermark.ts:63, 146a71a92f30)
  • Review continuity: The captured body identifies the current candidate and explicitly leaves matched first-turn, warmed-turn, and compaction measurements plus the generated SDK comparison as merge prerequisites. The previous completed review requested that same concrete validation. Historical pre-integration measurements and older passing suites are retained with their original revision scope, rather than treated as final-candidate performance proof. No target code or tests were executed during this read-only review. (146a71a92f30)

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the completed matched measurements and generated SDK comparison for the pinned candidate against its integrated baseline.

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-10-06T10:34:57.199Z sha f543745 :: needs changes before merge. :: none
  • reviewed 2026-10-06T11:05:13.323Z sha 51d4370 :: needs changes before merge. :: none

Preserve the landed combined transcript watermark query and cold/hot precedence coverage while retaining statement snapshots, shared freshness scopes, and the original write deadline policy. Post-integration P2 review is scoped-clean; core production types, formatting, and import-cycle checks pass.
Preserve the shared-state admission and operation freshness scope now owned by main. Keep the remaining transaction-envelope changes and their regression coverage. Fresh P2 review is scoped-clean; focused state and entry-reader tests pass.
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 6, 2026
Include the existing main fix for the inherited canonical-schema rejection in the Copilot rollback test. The PR delta remains the same 18 reader and transaction-envelope files; the merge is conflict-free and fresh P2 review is scoped-clean.
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 608f153 into main Oct 6, 2026
165 of 186 checks passed
@steipete
steipete deleted the dbasync/sqlopt-envelope branch October 6, 2026 12:18
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
…aw#166074)

* perf(sqlite): trim reader admission and transaction envelopes

Share the first agent admission probe and shared-state read scope, use single-statement transcript snapshots, and reuse existing read transactions. Fuse hot/cold watermark queries and avoid redundant busy-timeout restoration and inherited-deadline probes.

Preserve foreign-commit freshness, pinned snapshots, write FIFO and live authority. No schema, index, retention, durability, or SDK contract changes.

* fix(sqlite): preserve reachable watermark SDK declarations

Keep the combined watermark query private in its original declaration owner. Retain the one-statement snapshot while leaving the hot-only module and indirectly reachable SDK signatures unchanged.
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 P2 Normal backlog priority with limited blast radius. 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