Skip to content

perf(sqlite): batch placement and session metadata reads - #166053

Merged
steipete merged 2 commits into
mainfrom
dbasync/sqlopt-misc
Oct 6, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/sqlopt-misc

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Problem: Warmed chat turns repeat shared-state and session metadata reads even when their connection revision is unchanged or their related facts can be selected together. On the pinned base, the shared campaign workload executes a median 2,740.8 SQLite statements per warmed turn across all threads.

Solution

  • Read placement, move, pending-result, journal, and environment facts in one indexed statement per 250-session batch. Keep the existing transaction across batches and evaluate journal/result predicates from that snapshot.
  • Reuse up to 128 ACP metadata rows per native connection under the existing admitted schema, foreign-commit, and local-mutation revisions. Transactions, pinned snapshots, and authorizers retain SQL reads; close invalidates reuse.
  • Select Board presence with the exact session entry, including the single-key conversion-error fallback.
  • Reuse a supplied shared-state writer handle and retain its authoritative schema/ownership checks after BEGIN, removing its duplicate pre-transaction ownership read.

The JSON projection preserves native rejection of unsafe SQLite integers. Current caller authority, physical store ownership, FIFO writes, and accepted-work settlement remain with their existing owners.

Impact

88.4 fewer statements per warmed turn (3.2%), with unchanged normal behavior. No schema, index, persistent-cache, retention, durability, or environment-name additions. Production LOC: +457 / −103 / net +354, across 10 files.

The SDK diff adds no entrypoints or direct exports. Two reachable implementation declarations gain compatible additions: the optional Board presence/read option and a placement row decoder. Existing calls remain compatible; the reviewed diff digest is 0a6019b8 (130 dependent closure hashes).

Evidence

Baseline 20306571364c5b8df244fba15e88727b2b7c7a0e → candidate 8ad5047fc0437cfbc599cc1569a8de9f0129f9ca. Three fresh fixtures per revision on the same restored harness, Node 26.10.0 / SQLite 3.53.4, with identical workload/observer/analyzer hashes. Counts include successful native statements on the Gateway, workers, and helper processes; these are statement counts, not latency measurements.

Phase Before median (range) After median (range)
First turn, including creation 6,856 (6,821–6,899) 6,751 (6,743–6,751)
Warmed turn, 10-turn mean per repetition 2,740.8 (2,737.6–2,748.1) 2,652.4 (2,637.0–2,666.9)
Compaction 918 (907–1,019) 872 (870–879)
Targeted statement class, warmed executions/turn Before After
Four placement table batch SELECTs, combined 61.6 0
Combined placement snapshot statement 0 15.1
ACP metadata cohort SELECT 18.8 4.5
Standalone Board presence SELECT 17.8 0
Indexed Gateway ownership SELECT 25.5 20.9
Config schema-content SELECT, separate owner 53.4 52.9
Cold-archive metadata SELECT, separate watermark work 44.8 44.8

Both calibrations produced 8 native calls, 2 prepares, 7 successful statements, and zero failures independently on the main thread and a worker. Every fixture completed all 13 top-level turns, the child turn, control-plane RPCs, cron, compaction, and clean shutdown with no fixture children remaining. Failed native attempts were confined to retried shutdown BEGIN IMMEDIATE contention: before 2/0/1, after 1/1/0; none occurred in the measured turn or compaction phases.

EXPLAIN QUERY PLAN retains indexed placement lookups and the existing board_tabs covering index. No index addition was needed.

Validation:

  • 25 focused files / 204 distinct passing cases, using pnpm test … --maxWorkers=1, including zero-caller-thread-SQL boundaries, foreign commits, pinned snapshots, schema replacement, lifecycle binding, exact-key error isolation, and unsafe-integer refusal.
  • Negative controls fail on the removed work: ACP unchanged reads 2 → 0; placement snapshot reads 9 → 2 for two batches; Board standalone reads 1 → 0; duplicate ownership SELECT removed. The unsafe-integer worker regression also failed before its decoder guard.
  • node scripts/check-changed.mjs passed, including core and all 27 selected test typecheck groups; pnpm deadcode:knip passed; Madge and runtime import checks both report 0 cycles.
  • Database worker ratchet passed against the pinned base: 846 → 846 T1 call sites. Shared-registry build-graph and all nine import-closure suites were explicitly exercised. Existing host-owned routing remains appropriate; this changes no worker transport.
  • Fresh Codex autoreview: P2 scoped-clean.
  • Published-driver update cell passed on Testbox: published 2026.9.8 → candidate 2026.9.8, readiness 200, running version verified, durable state preserved, and incognito lifecycle verified. Run; the lease is now stopped. The aggregate remote command failed its initial SDK-ref lookup because the transport uses a carrier commit; the update step exited 0, and the SDK diff subsequently completed locally against the actual commits.
Test cost and validation caveats

Measured command wall times include compilation and import costs on a heavily loaded host: initial focused group 378.6 s; expanded import/owner group 977.6 s; placement/ownership/ACP/exact-entry group 789.8 s; final Board/ACP/cron group 492.1 s; isolated archive import 158.6 s. Earlier fixture failures were repaired and their owning suites passed. The archive import suite hit its 180 s setup deadline in the expanded group and passed in isolation; no timeout was increased and no flake fix is claimed.

Final valid Vitest test-execution totals for materially changed files (excluding shared compile/import overhead):

File Seconds
session-meta-read.cache.test.ts 0.336
session-accessor.sqlite-exact-read.test.ts 45.933
session-entry-read.worker.test.ts 59.618
placement-move-schema.test.ts 3.635
placement-read-projection.worker.test.ts 84.947
placement-store.turn-claim-closure.test.ts 51.520
openclaw-state-db-injected-admission.test.ts 0.398
openclaw-state-ownership.test.ts 137.917

The longer existing suites exercise native worker admission, revocation, snapshots, and settlement; a mocked kernel would not prove those boundaries. Added cases reuse their existing fixtures and add no timers, polling, or per-test Gateway boots. Hosted CI seconds are pending the PR run.

The campaign remains above its <500/<200 targets. Schema/quarantine, transaction-envelope, participant/main-key, and transcript-watermark reductions remain separate work. Coordination/overlap: #166041, #165984 (placement test changes on newer main), #165680, #165552, #165885, #165895, #165890, #165901, #165859, #165894, #165904, #165921, and #162433. This PR is being landed through the native maintainer workflow under explicit maintainer direction.

Landing integration

Merged main 1e8b7a3623bca9dc8b83babbea1c3b001c1012d7, including sibling #166041, without conflicts in a57268275bc537a8befb048f46c4b9458754ea7a. The introduced scope remains 19 files. Fresh independent P2 autoreview and completed exact-head ClawSweeper review found no actionable defects. The measurements above remain evidence for the original measured head.

Post-integration proof passed: core production typechecking, all 27 core test-type groups, and Madge (zero cycles). The SDK API comparison completed with digest afaea76f: no entrypoint or direct export changes, 130 dependent closure changes, and the same two compatible additive declaration changes as the original report. The released-tag check preserves existing call shapes; the optional internal read argument adds no required capability or deprecation.

Focused validation covered 117 distinct cases. The eight-file run passed 60 cases and timed out one Doctor case at its existing 120-second deadline (991.13s command wall time); the remaining two session files passed 56 cases (241.54s). The unchanged selected Doctor replay passed in 115.855s against that 120s limit (397.61s including preparation). The unauthorized rejection completes before the broad authorized preflight; the delay is in unchanged Doctor/plugin migration discovery. Its exact import/worker/scheduling cost remains uncertain. No timeout, assertion, or source change was made, and the replay is not claimed as a flake fix.

Integrated CI 37447469826 repeats two independently proven main failures: 15 Windows path-emulation cases in src/state/openclaw-state-db.paths.windows.test.ts (job 112216278412), and 8 Windows inventory-migration cases in src/state/openclaw-state-db-schema-repair.windows.test.ts (job 112216278891). The same cases failed earlier in scheduled main run 37437741118, jobs 112183782598 and 112183782443. All 16 relevant test/owner/setup inputs are unchanged between the tested main parent and PR merge tree. Five isolated runs of each file on the approved head and merge base passed on Node 26/macOS with --maxWorkers=1 (230 cases); those passes do not establish a Linux CI fix.

The successful fail-fast monitor cancelled 60 sibling jobs; their coverage remains unrun. The native inherited-failure admin route is explicitly authorized for this landing. Its evidence binds the exact head, run/attempt, failed cases, baseline logs, all cancellations, and tested merge b42ccaa42ba4d94a514637618e2c27892c26aa91. Local git merge-tree exactly reproduces that merge's tree. The original-head run 37443691750 had the same two failures and a downstream monitor timeout; it is historical evidence only.

Collect placement facts in one statement per batch, carry Board presence in exact-entry reads, and reuse ACP rows under the admitted connection revision. Keep snapshot consistency, foreign-commit freshness, native integer range checks, and transaction-held ownership validation while removing repeated reads.
@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 gateway Gateway runtime size: XL 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, 6:38 AM ET / 10:38 UTC (Revision 4).

ClawSweeper review

What this changes

The PR reduces repeated SQLite reads by batching worker-placement facts, caching unchanged ACP session metadata, combining Board presence with session reads, and reusing supplied writer handles.

Merge readiness

✅ Ready for maintainer review

The optimization remains useful and distinct from merged sibling work. No actionable correctness or security defect was found in the introduced diff; the supplied runtime evidence supports the performance claim.

Priority: P2
Reviewed head: a57268275bc537a8befb048f46c4b9458754ea7a

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful measured optimization with substantial boundary validation and no actionable introduced defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied production Gateway campaign exercises the changed placement, ACP, Board, and shared-state readers and observes fewer native statements with completed turns and clean shutdown. Measurements remain scoped to 8ad5047; integrated-head boundary validation is separately recorded. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied production Gateway campaign exercises the changed placement, ACP, Board, and shared-state readers and observes fewer native statements with completed turns and clean shutdown. Measurements remain scoped to 8ad5047; integrated-head boundary validation is separately recorded. No stored-data contract changes.
Evidence reviewed 11 items Introduced scope: Inspected the pinned merge-base-to-head diff across all 19 introduced paths. The actual checkout and original PR head are a572682; endpoint comparison was not substituted for introduction evidence.
Snapshot and integer contracts: Placement projection combines independently selected placement, pending-result, journal, move, and environment rows per 250-session batch inside the existing deferred transaction. Existing domain decoders remain in use, and the JSON reviver rejects unsafe numeric values.
Cache lifecycle: ACP reuse is bounded to 128 rows and keyed by admitted schema, foreign-commit data version, and local mutation revision. The existing revision owner excludes transactions, pinned snapshots, authorizers, and active mutations; disposal removes retained rows. Entry-incarnation matching still happens when consuming the selected rows.
Findings None None.
Security None None.

How this fits together

OpenClaw reads shared control-plane and per-agent SQLite state while preparing chat turns and worker recovery. These readers supply session metadata, Board membership, and placement facts to existing runtime owners.

flowchart TD
  A[Chat turns and recovery] --> B[Existing database owners]
  B --> C[Admission and freshness checks]
  C --> D[Placement snapshot batches]
  C --> E[ACP metadata reuse]
  C --> F[Session and Board reads]
  D --> G[Current runtime facts]
  E --> G
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +354, Tests +243, Docs +15. Total +612 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 10 457 103 +354
Tests 8 355 112 +243
Docs 1 16 1 +15
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 828 216 +612

Review metrics

Metric Value Why it matters
Measured warmed SQL reduction 2740.8 → 2652.4 statements/turn; 3.2% reduction Three matched repetitions support reduced database work without claiming lower end-to-end latency.
Production versus test growth Production net +354; tests net +243 Production growth has a stated purpose: typed snapshot batching, bounded metadata reuse, and preservation of existing compatibility paths.

Technical review

Best possible solution:

Keep the optimization within the existing read, revision, and transaction owners while preserving snapshot consistency and final write-authority checks.

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

Not applicable as a bug reproduction: source confirms repeated reads on current main, and the supplied matched runtime campaign measures their reduction. No tests or target code were executed during this read-only review.

Is this the best way to solve the issue?

Yes. The patch reduces work through existing owners, preserves snapshot and invalidation contracts, and introduces no competing persistence or configuration surface.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a measured, bounded runtime performance improvement without evidence of an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster 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 production Gateway campaign exercises the changed placement, ACP, Board, and shared-state readers and observes fewer native statements with completed turns and clean shutdown. Measurements remain scoped to 8ad5047; integrated-head boundary validation is separately recorded. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied production Gateway campaign exercises the changed placement, ACP, Board, and shared-state readers and observes fewer native statements with completed turns and clean shutdown. Measurements remain scoped to 8ad5047; integrated-head boundary validation is separately recorded. No stored-data contract changes.

Evidence

What I checked:

  • Introduced scope: Inspected the pinned merge-base-to-head diff across all 19 introduced paths. The actual checkout and original PR head are a572682; endpoint comparison was not substituted for introduction evidence. (a57268275bc5)
  • Snapshot and integer contracts: Placement projection combines independently selected placement, pending-result, journal, move, and environment rows per 250-session batch inside the existing deferred transaction. Existing domain decoders remain in use, and the JSON reviver rejects unsafe numeric values. (src/gateway/worker-environments/placement-read-projection.ts:257, a57268275bc5)
  • Cache lifecycle: ACP reuse is bounded to 128 rows and keyed by admitted schema, foreign-commit data version, and local mutation revision. The existing revision owner excludes transactions, pinned snapshots, authorizers, and active mutations; disposal removes retained rows. Entry-incarnation matching still happens when consuming the selected rows. (src/acp/runtime/session-meta-keys.ts:60, a57268275bc5)
  • Board compatibility: The optional Board selection preserves the existing board_widgets absence discriminator and selects membership from board_tabs. Single-key acquisition after a cohort conversion error retains Board presence and canonical validation; existing callers may omit the new option. (src/config/sessions/session-accessor.sqlite-entry-read.ts:365, a57268275bc5)
  • Final write authority preserved: Supplied writers retain path-access admission and authoritative schema/ownership validation inside the managed transaction before the operation runs. The strengthened ownership regression injects a foreign owner immediately before BEGIN and asserts rejection before the write callback. (src/state/openclaw-state-db.ts:459, a57268275bc5)
  • Real runtime evidence: The captured PR body reports three fresh fixtures per revision on Node 26.10.0 / SQLite 3.53.4, comparing 2030657 with 8ad5047. Each fixture completed all 13 top-level turns, child execution, control-plane RPCs, cron, compaction, and shutdown. Warmed statement medians fell from 2740.8 to 2652.4; targeted placement, ACP, Board, and ownership statement classes correspond to the changed readers. These establish statement reduction, not latency improvement. (8ad5047fc043)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: 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 (3 earlier review cycles)
  • reviewed 2026-10-06T09:41:53.407Z sha 8ad5047 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T09:47:49.904Z sha 8ad5047 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T10:10:38.574Z sha a572682 :: 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 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 46ba1d1 into main Oct 6, 2026
118 of 183 checks passed
@steipete
steipete deleted the dbasync/sqlopt-misc branch October 6, 2026 10:45
@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
…6053)

Collect placement facts in one statement per batch, carry Board presence in exact-entry reads, and reuse ACP rows under the admitted connection revision. Keep snapshot consistency, foreign-commit freshness, native integer range checks, and transaction-held ownership validation while removing repeated reads.
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 gateway Gateway runtime 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: XL 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