Repository navigation
perf(sqlite): batch session snapshot and watermark queries - #166041
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 5:24 AM ET / 09:24 UTC (Revision 2). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherOpenClaw’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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +36, Tests +113, Docs +4. Total +153 across 5 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Merged via squash.
|
…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
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_seqneeded 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→ candidate0eddbd708a5dcea920bbffcd9b1dd6c76842e6e7. 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.
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.
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_keyindex 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
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.session-accessor.sqlite-prepared-reads.test.ts0.325 s (new batching case 0.007 s);session-accessor.sqlite-transcript-watermark.test.ts37.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.mjspassed 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:knippassed (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.Potential overlap is intentionally kept to query text: sibling
sqlopt-session,sqlopt-misc,sqlopt-envelope, andsqlopt-schemawork; 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 fix9c66e8f40532, session-authority fix9cbcd2108052, and native session creation fixb636e955661eare 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, andsrc/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.1andv2026.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.