Skip to content

perf(sqlite): batch session snapshot and watermark queries - #166041

Merged
steipete merged 3 commits into
mainfrom
dbasync/sqlopt-plans
Oct 6, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/sqlopt-plans

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Warmed chat turns repeatedly read the hot transcript watermark and then fetch cold-archive metadata, and session snapshot replacement executes one UPSERT per field. These already-indexed operations still add unnecessary SQLite statement executions.

Why This Change Was Made

Read the hot rewrite generation and cold-or-hot sequence in one indexed statement. Select only the cold last_seq needed by the watermark, preserving cold precedence (including zero), fresh bindings, and the caller's SQLite snapshot. Batch saved snapshot fields into one multi-row UPSERT while retaining the cleanup DELETE, per-row conflict predicate, revision triggers, and existing transaction owner.

The existing exported watermark functions keep their original locations and signatures. No call-site, admission, transport, authority, FIFO, settlement, schema, index, retention, or durability changes are included. No new OPENCLAW_* names. The published-driver update cell is not applicable to this query-only change.

User Impact

The two changed owners remove 25.7 executed statements per warmed turn: watermark reads 45.4 → 22.7, snapshot writes including cleanup 9 → 6. The complete all-thread workload median falls 2,737.2 → 2,678.1. Total counts also include variable scheduled/background work; the entire aggregate reduction must not be attributed to the two rewrites.

Production LOC: +47 / −11 / net +36, across the existing watermark reader and snapshot writer. Two regression suites and the database reference are updated. This is a bounded query-shape improvement; the campaign's below-500 target still needs the sibling admission/read-reuse work.

Evidence

Matched statement-count workload

Baseline 20306571364c5b8df244fba15e88727b2b7c7a0e → candidate 0eddbd708a5dcea920bbffcd9b1dd6c76842e6e7. Same restored harness hashes, Node 26.10.0 / SQLite 3.53.4, source-mapped QA builds, and three complete local runs on each side. Each run has ten warmed turns plus first turn, child execution, control-plane RPCs, cron, committed compaction, and graceful shutdown. Successful native executions are counted across Gateway, worker threads, and helper processes; prepares are excluded and multi-statement exec is split.

Values are median [min–max]. Warmed values are each run's ten-turn mean; other phases are complete phase counts.

Phase All threads before All threads after
Warmed turn 2,737.2 [2,736.9–2,742.5] 2,678.1 [2,672.7–2,700.1]
First turn 6,896 [6,829–6,924] 6,813 [6,755–7,209]
Compaction 996 [944–1,086] 882 [855–905]

Warmed thread medians: main 4.3 → 0.9, workers 2,699 → 2,642.9, helpers 39.2 → 32.4. Independently computed medians need not add to the overall median. This does not move work from the caller to a worker; the existing worker boundary tests still pass.

Target SQL shape Warm before → after First before → after Compaction before → after
Hot max/rewrite SELECT 22.7 → 0 24 → 0 4 → 0
Cold metadata SELECT, including unchanged callers 44.7 → 22 52 → 28 12 → 8
Combined watermark SELECT 0 → 22.7 0 → 24 0 → 4
Snapshot cleanup DELETE 3 → 3 3 → 3 2 → 2
Single-row snapshot UPSERT 6 → 0 4 → 2 4 → 0
Two-row snapshot UPSERT 0 → 3 0 → 1 0 → 2

Both calibration threads produced 8 native calls, 2 prepares, 7 executed statements, and zero failures. All final runs completed; the measured phases have zero failed SQL executions/prepares and no fixture children remain. No uninstrumented latency improvement is claimed.

An intermediate revision was also measured while validation jobs overlapped: its whole-turn median was 2,738.9 despite the same 25.7 matched-owner reduction. Its longer windows captured more scheduled SQL. That observation is retained in the audit, and the final changed-revision measurement ran after those task-owned jobs settled; no samples were discarded.

Query plans and index proposals

Audited 90 shapes: the top 60 warmed statements plus leading DML/DDL across first turn, warmed turns, and compaction. The canonical synthetic fixture has 400 sessions, 32,000 transcript events, 4,800 participants, and 4,000 completion rows, plus populated snapshot, projection, board, and placement tables.

The combined watermark uses the existing cold/rewrite primary indexes and the covering (session_id, seq) transcript index. The batch UPSERT scans only its bounded VALUES input. Result equivalence was checked for 401 fixture identities and ten unequal/zero/negative/missing hot/cold cases.

Approval-only index recommendations were delivered separately, with scratch-copy EXPLAIN and storage/write-cost evidence: participant display ordering removes a temporary sort; a completion session_key index improves parent deletion/repair. Neither removes external statement executions. The apparent completion scan in the hot UPSERT is guarded in VDBE and is not claimed as a per-turn scan. No proposed index was added to repository schemas.

Correctness and checks

  • Both count regressions failed on the original code (watermark 2 vs 1; snapshot replacement up to 4 vs 2) and pass after the rewrites. Coverage includes foreign commits, pinned WAL snapshots, cold zero precedence, rewrites/reopen, unchanged revisions, deletion, rollback, and another session's retained fields.
  • Focused suites: 77 tests passed, 467.97 s wall, using pnpm test ... --maxWorkers=1; existing worker tests cover zero caller SQL, FIFO, live authority and accepted settlement. Runtime build-graph/import-closure proof: 13 tests passed, 42.86 s. The owner-location correction reran 27 tests, 751.89 s, including 306.9 s of compiled-worker preparation on the loaded host.
  • Changed test-body totals in the initial focused run: session-accessor.sqlite-prepared-reads.test.ts 0.325 s (new batching case 0.007 s); session-accessor.sqlite-transcript-watermark.test.ts 37.506 s (extended WAL case 3.505 s). The watermark suite retains its existing lifecycle fixtures and adds no new process/Gateway fixture. The exact-head CI run linked below passed; the durations above are local wall/test-body measurements, not aggregate CI time.
  • node scripts/check-changed.mjs passed for the query rewrites (2,578.25 s). The owner-location correction passed typechecks, all 27 dependent test graphs, ratchets and export scans, then identified an inline-only type import. That one-line fix passed the exact targeted lint step (19.70 s) and formatting; unchanged guard proof is retained from the full run.
  • pnpm deadcode:knip passed (103.98 s); all three additional export scans passed. Madge reports 0 cycles (130.24 s on the owner correction). Database-worker ratchets show no T1 growth against the pinned base and the correction parent.
  • SDK proof: the complete rendered surface after restoring the original function owner was byte-identical to the baseline. The final lint fix was emitted again with the canonical native declaration compiler: both exported signatures and all import targets are unchanged; only equivalent type-import spelling differs.
  • P2 Codex autoreview is clean for the complete query change, owner correction, and final type-import fix. No schema/update migration is required.

Potential overlap is intentionally kept to query text: sibling sqlopt-session, sqlopt-misc, sqlopt-envelope, and sqlopt-schema work; the provided admission/incognito/locked-write chains (#165680, #165552, #165885, #165895, #165890, #165901, #165859, #165894, #165904, #165921); and the standing #162433 overlap. No sibling call-site or ownership redesign is included. Approved for native landing.

Landing validation

The reviewed head remains 0eddbd708a5dcea920bbffcd9b1dd6c76842e6e7. The source-map-js fix 9c66e8f40532, session-authority fix 9cbcd2108052, and native session creation fix b636e955661e are already ancestors of this head. GitHub reports it mergeable; no integration change is needed for those fixes.

Fresh focused proof passed: 23 tests across the two changed suites, test/scripts/runtime-process-build-graph.test.ts, and src/auto-reply/reply/get-reply.imports.test.ts, using the repository test runner with --maxWorkers=1 (168.17 s wall, including 81.01 s compiled-worker preparation). No worker ownership or callback boundary is changed, and no additional worker-test routing is required.

Released SDK inspection compared the watermark owner with v2026.10.1-beta.1 and v2026.9.8: both exported functions retain their locations, synchronous signatures, parameters, and return types. The saved SDK report and final declaration comparison confirm no API change; no compatibility adapter or deprecation record is needed.

ClawSweeper completed its exact-head review at 2026-10-06 09:15 UTC with no actionable correctness or security findings. The initial PR-context check failed before the authored body was available; the subsequent body-triggered run passed. This was a publication-timing failure, not a code defect.

Exact-head GitHub CI passed: run 37440733579. No code fixes, integration commits, or CI reruns were required for landing.

Read retained transcript positions and rewrite generations in one indexed statement, and upsert saved entry snapshots as one batch. Preserve current snapshots, foreign-commit visibility, per-field revisions, and rollback behavior without changing schemas or worker ownership.
Keep the retained watermark function in its original module while combining its indexed reads. Preserve the released reachable declarations and leave the hot-only reader 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: S 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 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 5:24 AM ET / 09:24 UTC (Revision 2).

ClawSweeper review

What this changes

The PR combines transcript change-marker reads and batches saved session metadata writes to reduce SQLite statement executions.

Merge readiness

✅ Ready for maintainer review

The optimization remains useful on current main. The pinned patch preserves existing storage semantics, and no actionable correctness or security findings remain.

Priority: P2
Reviewed head: 0eddbd708a5dcea920bbffcd9b1dd6c76842e6e7

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with relevant production workload evidence, meaningful regression coverage, and no actionable introduced defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured body maps both changed SQLite owners to matched real local Gateway workloads on the baseline and reviewed head, recording fewer executions and zero measured SQL failures. Inspected regressions support value, revision, rollback, and snapshot equivalence; no stored-data contract change requires migration proof.
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 maps both changed SQLite owners to matched real local Gateway workloads on the baseline and reviewed head, recording fewer executions and zero measured SQL failures. Inspected regressions support value, revision, rollback, and snapshot equivalence; no stored-data contract change requires migration proof.
Evidence reviewed 9 items Pinned introduced change: Read the complete merge-base-to-head diff. The patch changes query shapes, regression coverage, and database reference prose while retaining exported watermark locations and signatures.
Watermark equivalence: The combined selection preserves cold last_seq precedence, including zero, and obtains generation from the existing hot rewrite table. The shared prepared-query executor binds fresh values on every execution rather than caching query results.
Snapshot storage compatibility: Production snapshot splitting emits at most three named fields. Batching preserves the transaction requirement, cleanup DELETE, and per-row conflict predicate. Existing insert/update/delete triggers retain per-field snapshot_revision increments; schemas, serialized values, and persistence policy do not change.
Findings None None.
Security None None.

How this fits together

OpenClaw’s session storage saves conversation metadata and supplies transcript change markers used to validate derived results. These operations use admitted SQLite connections and the existing read snapshots and write transactions.

flowchart TD
  A[Session operations] --> B[Existing database admission]
  B --> C[Transcript marker reader]
  D[Hot transcript and cold archive] --> C
  C --> E[Cache validation facts]
  B --> F[Session snapshot writer]
  G[Saved metadata fields] --> F
  F --> H[Committed fields and revisions]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +36, Tests +113, Docs +4. Total +153 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 47 11 +36
Tests 2 118 5 +113
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 169 16 +153

Review metrics

Metric Value Why it matters
Matched SQL reduction 25.7 fewer executed statements per warmed turn The captured workload attributes this reduction specifically to the two changed storage owners.
Production and regression growth production net +36 lines; tests net +113 lines The production growth implements one combined indexed read; regression growth protects statement counts and existing storage semantics.

Technical review

Best possible solution:

Retain the existing storage owners and their compatibility contracts while reducing redundant statement executions through these bounded query rewrites.

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

Not applicable as a bug reproduction: source establishes redundant statement executions, and the captured matched Gateway workloads report the after-change reduction.

Is this the best way to solve the issue?

Yes. Combining indexed selections and batching the existing bounded field writes is a focused improvement that preserves transaction ownership, row semantics, and public signatures.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded session-storage performance improvement with measured statement reductions and no demonstrated urgent user-facing failure.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured body maps both changed SQLite owners to matched real local Gateway workloads on the baseline and reviewed head, recording fewer executions and zero measured SQL failures. Inspected regressions support value, revision, rollback, and snapshot equivalence; no stored-data contract change requires migration proof.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured body maps both changed SQLite owners to matched real local Gateway workloads on the baseline and reviewed head, recording fewer executions and zero measured SQL failures. Inspected regressions support value, revision, rollback, and snapshot equivalence; no stored-data contract change requires migration proof.

Label justifications:

  • P2: This is a bounded session-storage performance improvement with measured statement reductions and no demonstrated urgent user-facing failure.
  • 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 maps both changed SQLite owners to matched real local Gateway workloads on the baseline and reviewed head, recording fewer executions and zero measured SQL failures. Inspected regressions support value, revision, rollback, and snapshot equivalence; no stored-data contract change requires migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body maps both changed SQLite owners to matched real local Gateway workloads on the baseline and reviewed head, recording fewer executions and zero measured SQL failures. Inspected regressions support value, revision, rollback, and snapshot equivalence; no stored-data contract change requires migration proof.

Evidence

What I checked:

  • Pinned introduced change: Read the complete merge-base-to-head diff. The patch changes query shapes, regression coverage, and database reference prose while retaining exported watermark locations and signatures. (0eddbd708a5d)
  • Watermark equivalence: The combined selection preserves cold last_seq precedence, including zero, and obtains generation from the existing hot rewrite table. The shared prepared-query executor binds fresh values on every execution rather than caching query results. (src/config/sessions/session-accessor.sqlite-transcript-watermark.ts:23, 0eddbd708a5d)
  • Snapshot storage compatibility: Production snapshot splitting emits at most three named fields. Batching preserves the transaction requirement, cleanup DELETE, and per-row conflict predicate. Existing insert/update/delete triggers retain per-field snapshot_revision increments; schemas, serialized values, and persistence policy do not change. (src/config/sessions/session-entry-snapshots.ts:102, 0eddbd708a5d)
  • Meaningful regression coverage: Read both complete changed suites. Coverage checks persisted values, unchanged revisions, field removal, rollback, another session’s retained fields, cold zero precedence, foreign commits, pinned WAL snapshots, fresh bindings, rewrites, and reopened connections. Tests were inspected without execution during this read-only review. (src/config/sessions/session-accessor.sqlite-prepared-reads.test.ts:80, 0eddbd708a5d)
  • Production workload evidence: The captured PR body reports three complete local Gateway workloads per revision on Node 26.10.0 / SQLite 3.53.4, comparing the pinned baseline with the reviewed head. Watermark executions fall 45.4 to 22.7 and snapshot writes including cleanup fall 9 to 6 per warmed turn, with zero measured SQL failures. The body separates these owner-specific reductions from variable background work and claims no uninstrumented latency improvement. (0eddbd708a5d)
  • Still necessary on current main: Fetched main still performs separate hot-watermark and cold-metadata reads and retains the per-field snapshot UPSERT loop. The supplied admission, authority, and incognito PRs address adjacent responsibilities rather than superseding these query rewrites. (src/config/sessions/session-accessor.sqlite-transcript-watermark.ts:28, 9ad97b209d6e)

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 (1 earlier review cycle)
  • reviewed 2026-10-06T09:15:39.025Z sha 0eddbd7 :: needs maintainer review before merge. :: none

@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
@steipete
steipete merged commit bcae52b into main Oct 6, 2026
190 of 191 checks passed
@steipete
steipete deleted the dbasync/sqlopt-plans branch October 6, 2026 09:36
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

* perf(sqlite): batch session snapshot and watermark queries

Read retained transcript positions and rewrite generations in one indexed statement, and upsert saved entry snapshots as one batch. Preserve current snapshots, foreign-commit visibility, per-field revisions, and rollback behavior without changing schemas or worker ownership.

* fix(sqlite): preserve watermark SDK declarations

Keep the retained watermark function in its original module while combining its indexed reads. Preserve the released reachable declarations and leave the hot-only reader unchanged.

* style(sqlite): use a type-only watermark import
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. 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