Skip to content

perf(sqlite): reuse compiled plugin state point reads - #138758

Merged
steipete merged 1 commit into
mainfrom
codex/sqlite-goal-kv-prepared-reads
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/sqlite-goal-kv-prepared-reads

Conversation

@steipete

@steipete steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Plugin state point reads rebuild and compile the same Kysely query for every lookup. Reconstructing a large Reef audit chain or Buzz reconnect cursor set repeats that JavaScript work thousands of times even though the physical connection and query shape are unchanged.

Why This Change Was Made

Reuse the existing prepareSqliteQuerySync helper once per physical SQLite connection at the shared point-read owner. Every invocation still binds its current plugin, namespace, key, and expiry time and executes the same fresh read. Native statement invalidation remains owned by the existing helper, and the compiled runner has weak connection ownership.

This preserves exact point-read timing. Replacing these callers with namespace snapshots would change concurrent reconnect observations or expose unrelated malformed audit rows. No result rows, authorization decisions, or expiry facts are cached.

User Impact

Existing plugin-state consumers perform less repeated query-building work without changing their results or setup. Schema, stored rows, transactions, error handling, quotas, and public APIs are unchanged.

Evidence

  • The regression fails before the change with seven compilations instead of one. It passes across two independently opened native connections with different plugins, namespaces, keys, absent rows, and exact expiry boundaries.
  • All 190 tests in 12 owner/helper/Buzz/Reef files pass, as does the full changed-file gate. Fresh independent Codex review found no actionable P0–P2 findings.
  • Five native phases exercise the actual candidate source with synthetic state: a 30,000-entry committed Reef chain, 1,020 Buzz reconnect rooms, malformed uncommitted overflow, an interleaved reconnect update, and physical close/reopen. Complete result hashes and all persisted row bytes/timestamps match baseline. The committed chain still performs 30,001 fresh SELECTs but no per-read Kysely compilations after its prepared reader is initialized; Buzz retains 1,021 SELECTs and only its separate list-query compilation.
  • The retained public store reads correctly after its old physical handle closes and a new connection opens. The native proof verifies candidate source hashes before and after. These are structural compilation/query measurements, not a latency benchmark or external channel test.

Production delta is +16 lines for one connection-owned compiled reader; tests add 47. There is no new cache framework, dependency, configuration, or test-only production hook.

@clawsweeper

clawsweeper Bot commented Sep 5, 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 size: S maintainer Maintainer-authored PR labels Sep 5, 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 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 11:01 PM ET / September 5, 2026, 03:01 UTC.

ClawSweeper review

What this changes

Reuse a compiled SQLite query for plugin-state lookups while supplying fresh plugin, namespace, key, and expiry values on every read.

Merge readiness

⛔ Blocked before merge - 1 item remains

The optimization remains useful: current main still recompiles point reads. No introduced correctness or security defect was found, and the prior review contains no outstanding code findings.

Priority: P2
Reviewed head: 2a061895c93a4905f6672608dadf0fb9771e96b7

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization using the established helper, with meaningful regression coverage and no actionable patch findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied MEMBER association exempts this internal optimization from the external-contributor proof gate. Reported native Reef/Buzz runs exercise the changed store owner with matching results, fresh interleaved reads, and reopen recovery; no material authority change triggers additional proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied MEMBER association exempts this internal optimization from the external-contributor proof gate. Reported native Reef/Buzz runs exercise the changed store owner with matching results, fresh interleaved reads, and reopen recovery; no material authority change triggers additional proof.
Evidence reviewed 10 items Verified introduced scope: The pinned introduction changes only the point reader and its regression test. The test merge’s raw parents match the pinned base and head, and its production delta matches the introduced hunk.
Current main still performs repeated compilation: Current main constructs the point query on every call and passes it to the compile-and-execute helper. It does not contain this connection-owned compiled reader. The supplied latest-release source object was unavailable locally, so no release inclusion is claimed.
Existing execution boundary and dependency signals: The existing preparation helper compiles once, builds invocation-local parameters, and uses the normal synchronous executor. Its Kysely imports and node:sqlite execution establish the relevant dependency contracts; no Codex runtime or protocol contract is involved. The helper is unchanged relative to fetched main.
Findings None None.
Security None None.

How this fits together

Plugin-state storage holds persistent, plugin-scoped values in OpenClaw’s shared SQLite database. Synchronous and asynchronous store operations use its point reader, including Reef audit reconstruction and Buzz reconnect cursors.

flowchart TD
  A[Plugin store operations] --> B[Shared database owner]
  B --> C{Reader compiled for connection?}
  C -->|No| D[Compile fixed query]
  C -->|Yes| E[Bind current scope and expiry]
  D --> E
  E --> F[Execute fresh SQLite read]
  F --> G[Current value or missing result]
Loading

Before merge

  • Resolve merge risk (P1) - Reviewer limitation: installed Kysely and Node SQLite sources were unavailable, and upstream retrieval failed on DNS resolution; the author’s dated dependency inspection could not be independently repeated.
Agent review details

Security

None.

PR surface

Source +16, Tests +47. Total +63 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 27 11 +16
Tests 1 47 0 +47
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 74 11 +63

Review metrics

Metric Value Why it matters
Production versus test LOC Production net +16; tests net +47 Production growth supplies weak connection ownership and four fresh bindings while reusing the existing compiler/executor abstraction.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep one prepared reader per physical connection at the shared store owner, with fresh scope and expiry bindings through the existing executor.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep one prepared reader per physical connection at the shared store owner, with fresh scope and expiry bindings through the existing executor.

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

Not applicable to a functional bug: this is a performance optimization. Current-main source confirms repeated compilation, and the supplied regression report measures seven compilations becoming one; this review did not run a benchmark.

Is this the best way to solve the issue?

Yes. Reusing the existing preparation helper at the common reader removes repeated compilation without introducing consumer-specific snapshots or changing fresh-read semantics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c748cd5714b8.

Labels

Label justifications:

  • P2: This is a bounded optimization for repeated plugin-state reads, with no 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: The supplied MEMBER association exempts this internal optimization from the external-contributor proof gate. Reported native Reef/Buzz runs exercise the changed store owner with matching results, fresh interleaved reads, and reopen recovery; no material authority change triggers additional proof.

Evidence

What I checked:

  • Verified introduced scope: The pinned introduction changes only the point reader and its regression test. The test merge’s raw parents match the pinned base and head, and its production delta matches the introduced hunk. (src/plugin-state/plugin-state-store.sqlite.ts:219, 0731e3e03535)
  • Current main still performs repeated compilation: Current main constructs the point query on every call and passes it to the compile-and-execute helper. It does not contain this connection-owned compiled reader. The supplied latest-release source object was unavailable locally, so no release inclusion is claimed. (src/plugin-state/plugin-state-store.sqlite.ts:219, c748cd5714b8)
  • Existing execution boundary and dependency signals: The existing preparation helper compiles once, builds invocation-local parameters, and uses the normal synchronous executor. Its Kysely imports and node:sqlite execution establish the relevant dependency contracts; no Codex runtime or protocol contract is involved. The helper is unchanged relative to fetched main. (src/infra/kysely-sync.ts:293, 2a061895c93a)
  • Caller and lifecycle preservation: The full store facade and SQLite owner show that async methods delegate to synchronous operations, while lookup, consume, update, registration, and conditional deletion share the point reader. Existing read-only acquisition skips in-flight write transactions and closes temporary connections; the patch does not change that ownership. (src/state/openclaw-state-db-readonly.ts:52, 2a061895c93a)
  • Focused regression and helper coverage: The added test exercises seven reads across changing keys, plugins, namespaces, absence, and exact expiry on each of two physical connections. Existing store tests cover writes and retained-store reopen; helper tests cover changing bindings, synchronous re-entry, authorizer transitions, execution errors, and close cleanup. These tests were read, not executed by this review. (src/plugin-state/plugin-state-store.test.ts:115, 2a061895c93a)
  • Consumer semantics favor exact reads: Reef follows the committed head through exact entry lookups, while Buzz reads each room cursor after its namespace listing. Replacing these reads with snapshots would broaden Reef’s read scope or change Buzz’s observation timing; shared compilation reuse preserves both paths. (extensions/reef/src/audit-state.ts:369, 2a061895c93a)

Likely related people:

  • Peter Steinberger: 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-09-05T01:30:59.549Z sha 9456ed0 :: blocked before merge. :: none

@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

I completed the direct dependency inspection requested by the latest ClawSweeper review. Installed Kysely 0.29.5 DefaultQueryCompiler.compileQuery returns the compiled SQL and compiler-ordered bound values; appendValue retains the original values. OpenClaw's existing preparation helper substitutes unique marker identities and builds a fresh parameter array per invocation. In Node v24.20.0 src/node_sqlite.cc, StatementSync::Iterate resets the statement and calls BindParams; BindParams clears prior bindings and binds each current argument. The normal executor, re-entry handling, authorizer invalidation and physical close owner remain unchanged. No Codex runtime/protocol contract is involved.

The actual native owner-path proof also passed: a 30,000-link Reef chain still performs 30,001 SELECTs with the same values while warm Kysely compilation falls to zero; Buzz still observes fresh interleaved writes, and uncommitted corrupt overflow records remain outside the read scope. Two physical connections bind independently, and fresh-process reopen preserves the stored rows. The 190 focused tests, full changed-file gate, and independent P0–P2 review passed. This resolves the reviewer's dependency-access limitation without changing the prepared head or adding a result cache.

@steipete
steipete force-pushed the codex/sqlite-goal-kv-prepared-reads branch from 9456ed0 to 2a06189 Compare September 5, 2026 02:53
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Refreshed proof on 2a061895c93a4905f6672608dadf0fb9771e96b7: all 190 tests, the full changed-file gate, five native Reef/Buzz/store phases, and transaction/consume/corrupt-value controls pass. The rebase combines the two required test imports; production behavior is unchanged. A fresh two-part independent Codex review found no actionable P0–P2 findings.

The latest ClawSweeper review reports only that its environment could not retrieve dependency sources. I directly inspected the installed Kysely 0.29.5 compiler and official Node 24.20.0 node_sqlite.cc: compilation retains parameter identity/order, and native calls reset/rebind before execution. The existing helper and native cache/close rules are unchanged. The earlier dependency proof remains applicable; the refreshed native tests verify exact rows, scope, expiry, write-owner behavior and physical reopen. No review finding or rank-up move is left unaddressed.

@steipete
steipete merged commit 2595432 into main Sep 5, 2026
174 checks passed
@steipete
steipete deleted the codex/sqlite-goal-kv-prepared-reads branch September 5, 2026 03:26
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
vincentkoc added a commit to LiuwqGit/openclaw that referenced this pull request Sep 5, 2026
* refs/remotes/origin/main: (602 commits)
  fix(plugins): trace trust refusals and repair legacy provenance (openclaw#138746)
  perf(sqlite): reuse compiled plugin state point reads (openclaw#138758)
  refactor: type chat prefetch dependencies and clean loading tests (openclaw#138793)
  ci: reduce Doctor test startup and core lint jobs (openclaw#138796)
  feat(update): retain run history and share outcome reports (openclaw#138690)
  chore(deps): update @openclaw/fs-safe to 0.8.1 (openclaw#138500)
  fix: preserve global board ownership from pinning to notifications (openclaw#138675)
  fix(gateway): deliver session catalog updates from slow hosts (openclaw#138674)
  perf(sessions): index pending conversation replies (openclaw#127182)
  perf(auth): reuse ordered provider alias entries (openclaw#138805)
  docs(diagnostics): clarify whole-process CPU metrics (openclaw#138804)
  perf(memory): narrow source reads and stream embedding cache rows (openclaw#138766)
  fix: allow older source on newer Testbox checkouts (openclaw#138782)
  fix(agents): preserve recovered task progress and lifecycle ownership (openclaw#138785)
  perf(codex): reduce rollout tail scan CPU (openclaw#138784)
  perf(gateway): stop projecting history deltas at the byte budget (openclaw#138655)
  fix(build): bound native declaration inputs to checkout (openclaw#138742)
  fix(cli): preserve foreground Gateway argument handling (openclaw#138765)
  fix(ui): align task toolbar with side-panel tabs (openclaw#138769)
  fix(logbook): drain accepted work before closing SQLite (openclaw#138754)
  ...

# Conflicts:
#	src/agents/embedded-agent-runner/compact.queued.ts
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. 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