Repository navigation
improve(sqlite): reuse synchronous prepared statements - #114777
Conversation
e13a222 to
5dcd179
Compare
|
Codex review: needs maintainer review before merge. Reviewed July 28, 2026, 1:23 AM ET / 05:23 UTC. ClawSweeper reviewWhat this changesThe PR caches repeated synchronous SQLite prepared statements for OpenClaw’s shared and file-backed agent databases, while updating query-count tests so they measure executions rather than preparation calls. Merge readinessThis PR remains necessary because the synchronous Kysely path on current main still prepares equivalent SQLite SQL on each call. The branch’s bounded, database-owned cache is a plausible and well-tested improvement, but it is availability-sensitive because cached native statements retain their Priority: P2 Review scores
Verification
How this fits togetherOpenClaw’s gateway, sessions, and agent state use shared and per-agent SQLite databases. Synchronous Kysely helpers compile query objects into SQLite statements; this PR retains a small set of repeated statements between executions and must clear them whenever a database owner closes, replaces, or repairs a handle. flowchart LR
A[Gateway and session operations] --> B[Shared and agent database owners]
B --> C[Compiled synchronous queries]
C --> D[Database-owned statement cache]
D --> E[node:sqlite statements]
E --> F[Rows and write results]
B --> G[Close repair and eviction paths]
G --> D
Decision needed
Why: The implementation has a deliberate lifecycle cost that is not resolved by ordinary unit success alone; accepting that ownership invariant is a maintainer risk decision. Before merge
Agent review detailsSecurityNone. PR surfaceSource +191, Tests +491, Other +3. Total +685 across 10 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Rebase or otherwise validate the clean merge result against current Do we have a high-confidence way to reproduce the issue? Not applicable: this PR improves a measured synchronous-query performance path rather than fixing a report with a user-facing failure reproduction. The PR does provide a concrete after-fix workload run and focused cache tests. Is this the best way to solve the issue? Yes, conditionally: a database-owned, bounded cache is a narrower fit than a global cache because it follows state-database ownership and excludes incognito handles. The remaining requirement is current-merge proof of the clear-before-close lifecycle contract. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against d894a235e88d. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (9 earlier review cycles; latest 8 shown)
|
98b37ff to
24448d1
Compare
f2060a1 to
fae111b
Compare
fae111b to
0bfd007
Compare
|
Maintainer update: rebased onto current
Review audit for the clear-before-close ownership obligation (requested by ClawSweeper): every enabled-handle disposal path on this head was verified to clear via Local proof: |
…allowlist raw test SQL
…repare-count tests
6e0e98e to
38e7ee9
Compare
… ripgrep pass the artifacts-init guard
|
Merged via squash.
|
* perf(sqlite): cache synchronous prepared statements * fix(sqlite): refresh cached statement metadata * fix(sqlite): bound cached statement retention * fix(sqlite): close statement cache lifecycle gaps * test: suppress SQLite warning in retention child * test(sqlite): make transcript-load counter statement-cache-aware and allowlist raw test SQL * test(sessions): type the wrapped iterate against its overloaded signature * test: share a statement-cache-aware SQLite execution counter across prepare-count tests * fix(pr): validate head SHA with bash regex so fork-CI runners without ripgrep pass the artifacts-init guard --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
Summary
High Level TLDR
Synchronous Kysely queries now reuse a bounded set of hot SQLite prepared statements instead of recompiling identical SQL on every call. The cache is database-owned, second-use admitted, LRU bounded, byte bounded, disabled under SQLite authorizers, and enabled only for the lifecycle-owned file-backed shared and agent state databases.
Root Cause
executeCompiledSqliteQuerySyncprepared every query and immediately discarded the native statement. A measured 64-write subagent registry burst executed 2,144 statements but used only 65 SQL strings. The upsert SQL alone ran 2,080 times, so 2,079 prepares repeated SQL already compiled moments earlier.The previous behavior spent 55.64 ms of a 168.93 ms workload in native prepare calls on Node 25.9. This synchronous CPU work blocked the gateway event loop.
What Changed
:memory:agent databases uncached. Those handles are excluded from the 64-handle file-backed LRU eviction path, and the measured workload did not justify expanding their process-wide retention surface.The
setAuthorizerandDatabaseSync.deserializewrappers are intentionally retained. A SQLite authorizer gates statement compilation. Reusing a statement that was compiled before an authorizer was installed would bypass that compilation-time check. The guard protects this property even though no in-tree production caller currently exercises it.This does not change the subagent registry full snapshot rewrite, database schema, DDL, serialized formats, or incognito database behavior.
Supported Node API compatibility
enableNodeSqliteKyselyStatementCachedoes not assume that optionalnode:sqliteAPIs exist.installStatementInvalidationindependently guardssetAuthorizeranddeserializewithtypeof owner.<method> === "function"atsrc/infra/kysely-sync.ts:61andsrc/infra/kysely-sync.ts:75. Those are the only runtime call sites. The references atsrc/infra/kysely-sync.ts:21andsrc/infra/kysely-sync.ts:80are type-only and are erased at runtime.The shared and agent state open paths call the enable function at
src/state/openclaw-state-db.ts:527andsrc/state/openclaw-agent-db.ts:312. On a runtime missing both optional methods,installStatementInvalidationexecutes the two guards and installs its marker withObject.definePropertyatsrc/infra/kysely-sync.ts:91; it does not call either missing method.This PR adds no new required
node:sqliteAPI. Currentorigin/mainalready callsprepare,columns, andruninsrc/infra/kysely-sync.ts:36-43, anditerateSqliteQuerySyncalready callsprepare,columns, andstatement.iterate()insrc/infra/kysely-sync.ts:71-76. The supported Node floor is unchanged.Direct probes of the three requested runtimes produced:
setAuthorizerdeserializeNode 24 exposes
setAuthorizerbut notdeserialize, so the methods must be guarded independently. The implementation already does that. Authorizer invalidation behavior is covered on CI because CI runs Node 24, wheresetAuthorizerexists. Node 22 skips those cases through the feature check.Real behavior proof
The same 64 sequential subagent registry snapshot writes were measured in a throwaway state directory:
Measured reductions were 97.0% in prepare calls, 97.7% in prepare time, and 24.7% in total workload time. A fresh rerun after the review fixes still produced 65 prepares versus the 2,144 baseline.
The peak of 2 is only a property of this workload. It is not a mechanism ceiling. Each enabled database can admit up to 32 entries. Second-use admission reduces one-shot variable-cardinality churn but does not exclude repeated variants. A workload that executes each
NOT IN (?, ...)shape twice can admit every shape, fill the LRU, and evict hotter statements.src/infra/kysely-sync.test.ts:109proves this behavior. The risk is performance degradation, not incorrect results, because the 32-entry bound still holds.The earlier 20,000-handle stress experiment proves only the clean lifecycle path. It warmed two statements per handle, explicitly cleared and closed each handle, then ran 30 major GCs separated by
setImmediatemacrotasks:The focused retention tests now encode both sides of the lifecycle contract on Node 25.9:
Drop without clear did not collect. The first-use temporary statement collected, but the cached statement and its database remained retained after 30 GCs separated by macrotask boundaries. This demonstrates that clear-before-drop is required. A cached native
StatementSyncstrongly retains itsDatabaseSync, so JavaScript finalization cannot repair a missed clear after the cycle is rooted.src/infra/kysely-sync.test.ts:366covers the clean path andsrc/infra/kysely-sync.test.ts:374covers the hazard.Lifecycle disposal audit
Cache transitions and execution errors:
src/infra/kysely-sync.ts:71deletes the cache after every successful install, replacement, or removal.src/infra/kysely-sync.ts:86deletes the cache infinally, including failed deserialization.src/infra/kysely-sync.ts:207returns the iterator to reset the statement, andsrc/infra/kysely-sync.ts:188releases the active guard. Recovery is tested atsrc/infra/kysely-sync.test.ts:350.src/infra/sqlite-transaction.ts:201clears before close.src/infra/sqlite-transaction.test.ts:195proves the original operation error remains the propagated error.Shared state database owner:
src/state/openclaw-state-db.ts:106src/state/openclaw-state-db.ts:505src/state/openclaw-state-db.ts:548src/state/openclaw-state-db.ts:612src/state/openclaw-state-db.ts:624src/state/openclaw-state-db.ts:639delegates to close all.src/state/openclaw-state-db.ts:285src/state/openclaw-state-db.ts:407src/state/openclaw-state-db.ts:430src/state/openclaw-state-db-readonly.ts:64Per-agent database owner:
src/state/openclaw-agent-db.ts:122delegates to close by path and the shared close helper atsrc/state/openclaw-agent-db.ts:490.src/state/openclaw-agent-db.ts:244andsrc/state/openclaw-agent-db.ts:293delegate to the clear atsrc/state/openclaw-agent-db.ts:490.src/state/openclaw-agent-db.ts:346src/state/openclaw-agent-db.ts:380delegates to the clear atsrc/state/openclaw-agent-db.ts:490.src/state/openclaw-agent-db.ts:606delegates to the clear atsrc/state/openclaw-agent-db.ts:490.src/state/openclaw-agent-db.ts:642delegates to close by path.src/state/openclaw-agent-db.ts:652delegates to the clear atsrc/state/openclaw-agent-db.ts:490.src/state/openclaw-agent-db.ts:660delegates to close all.src/state/openclaw-agent-db.ts:521delegates to the clear atsrc/state/openclaw-agent-db.ts:490.src/state/openclaw-agent-db-maintenance.ts:122src/state/openclaw-agent-db-readonly.ts:113The following short-lived handles deliberately never call
enableNodeSqliteKyselyStatementCacheand are outside the prepared-statement cache lifecycle: schema preflight atsrc/state/openclaw-database-preflight.ts:104andsrc/state/openclaw-database-preflight.ts:139, startup checkpoint atsrc/state/openclaw-state-db-startup-checkpoint.ts:65, verification worker atsrc/state/openclaw-database-verify.worker.ts:49, schema-repair detection atsrc/state/openclaw-state-db-schema-repair.ts:172, snapshot source and verification handles atsrc/infra/sqlite-snapshot.ts:661,src/infra/sqlite-snapshot.ts:685, andsrc/infra/sqlite-snapshot.ts:715, agent owner inspection atsrc/state/openclaw-agent-db.ts:196, and incognito agent databases atsrc/state/openclaw-agent-db.ts:250.Verification
The new retention tests are not tautological. Each observes independent
WeakRefliveness after macrotask-separated GC and fails if its covered retention shape changes. The rollback-failure test separately asserts that close occurred, that cached Kysely state was cleared before close, and that the original operation error remained the thrown error.What was not tested
:memory:agent databases remain intentionally uncached and therefore do not receive this performance improvement.What Problem This Solves
Resolves a problem where bursty synchronous state writes repeatedly compiled identical SQL on the gateway event loop, delaying unrelated queued work.
Why This Change Was Made
The hot workload has a small reusable SQL core and a variable one-shot tail. Second-use admission captures the measured hot core, while per-database entry and byte limits, lifecycle clearing, authorizer bypass, and iterator isolation contain correctness and retention risks. Repeated variable-cardinality SQL can still compete for the bounded LRU, which is disclosed as a performance risk above.
User Impact
File-backed gateway state bursts spend substantially less synchronous CPU time compiling repeated SQL. Query results, ordering, affected-row counts, insert IDs, errors, schemas, serialized state, and incognito database behavior remain unchanged.
Evidence
The before and after workload, clean-path retention stress, drop-without-clear hazard test, lifecycle enumeration, focused regressions, static gates, and final branch autoreview are recorded above.
Maintainer additions during landing
db.prepare()calls as query proxies; statement caching legitimately reuses statements, so they now count executions via the sharedtest/helpers/sqlite-statement-execution-counter.ts(cache-cleared at attach).scripts/pr-lib/review.shvalidated the head SHA by shelling out torg, which does not exist on GitHub-hosted fork-PR runners; the fix(pr): bind review artifacts to the PR being landed #114897 artifact-validation tests therefore failed deterministically on every fork PR. The guard now uses bash's native regex. Unrelated to the statement cache, folded in because it blocked this PR's merge gate.