Skip to content

improve(sqlite): reuse synchronous prepared statements - #114777

Merged
steipete merged 9 commits into
openclaw:mainfrom
VACInc:perf/cache-prepared-statements
Jul 28, 2026
Merged

steipete merged 9 commits into
openclaw:mainfrom
VACInc:perf/cache-prepared-statements

Conversation

@VACInc

@VACInc VACInc commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

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

executeCompiledSqliteQuerySync prepared 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

  • Added a database-owned prepared-statement cache for explicitly enabled shared and file-backed agent state databases.
  • Admit SQL only after its second use.
  • Bound each enabled database to 32 statements and 32 probationary SQL strings.
  • Reject cache admission when SQL plus variable-size string or blob bindings exceed 64 KiB. The approximate 2 MiB variable-content ceiling is per enabled database, not process-wide.
  • Bypass the cache whenever a SQLite authorizer is installed, including authorizers whose captured policy state changes without replacing the callback.
  • Clear statements on authorizer transitions, deserialization, close, stale reopen, test reset, repair, rollback-failure close, and database open failure paths.
  • Keep the public lazy iterator uncached. Cached eager reads fully consume a private iterator under an active-statement guard, refresh metadata after SQLite schema reprepare, and reset after step-time errors.
  • Keep incognito :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 setAuthorizer and DatabaseSync.deserialize wrappers 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

enableNodeSqliteKyselyStatementCache does not assume that optional node:sqlite APIs exist. installStatementInvalidation independently guards setAuthorizer and deserialize with typeof owner.<method> === "function" at src/infra/kysely-sync.ts:61 and src/infra/kysely-sync.ts:75. Those are the only runtime call sites. The references at src/infra/kysely-sync.ts:21 and src/infra/kysely-sync.ts:80 are 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:527 and src/state/openclaw-agent-db.ts:312. On a runtime missing both optional methods, installStatementInvalidation executes the two guards and installs its marker with Object.defineProperty at src/infra/kysely-sync.ts:91; it does not call either missing method.

This PR adds no new required node:sqlite API. Current origin/main already calls prepare, columns, and run in src/infra/kysely-sync.ts:36-43, and iterateSqliteQuerySync already calls prepare, columns, and statement.iterate() in src/infra/kysely-sync.ts:71-76. The supported Node floor is unchanged.

Direct probes of the three requested runtimes produced:

API Node 22.22.3 Node 24.15.0 Node 25.9.0
setAuthorizer absent present present
deserialize absent absent absent

Node 24 exposes setAuthorizer but not deserialize, so the methods must be guarded independently. The implementation already does that. Authorizer invalidation behavior is covered on CI because CI runs Node 24, where setAuthorizer exists. Node 22 skips those cases through the feature check.

PATH=/tmp/n22/bin:$PATH node scripts/run-vitest.mjs src/infra/kysely-sync.test.ts
 Test Files  1 passed (1)
      Tests  15 passed (15)
[test] passed 1 Vitest shard in 5.19s

PATH=/tmp/n24/bin:$PATH node scripts/run-vitest.mjs src/infra/kysely-sync.test.ts
 Test Files  1 passed (1)
      Tests  15 passed (15)
[test] passed 1 Vitest shard in 4.70s

node scripts/run-vitest.mjs src/infra/kysely-sync.test.ts
 Test Files  1 passed (1)
      Tests  15 passed (15)
[test] passed 1 Vitest shard in 4.59s

Real behavior proof

The same 64 sequential subagent registry snapshot writes were measured in a throwaway state directory:

                                before      after
statement executions             2144       2144
prepare calls                     2144         65
distinct SQL strings                65         65
cache hits                           0       2079
cache hit rate                    0.00%      96.97%
prepare time                     55.64 ms     1.29 ms
workload time                   168.93 ms   127.27 ms
prepare share                    32.93%       1.01%
peak cached statements
in this measured workload            0           2

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:109 proves 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 setImmediate macrotasks:

database handles collected: 20000 / 20000
statements collected:       40000 / 40000
heap before:                16191712
heap after create:          47225888
heap after GC:              17293152
heap growth after GC:        1101440

The focused retention tests now encode both sides of the lifecycle contract on Node 25.9:

clear before drop:
  databaseCollected: true
  statementsCollected: 2 / 2

drop without clear:
  databaseCollected: false
  statementsCollected: 1 / 2

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 StatementSync strongly retains its DatabaseSync, so JavaScript finalization cannot repair a missed clear after the cycle is rooted. src/infra/kysely-sync.test.ts:366 covers the clean path and src/infra/kysely-sync.test.ts:374 covers the hazard.

Lifecycle disposal audit

Cache transitions and execution errors:

Path Disposal or reset proof
Authorizer transition src/infra/kysely-sync.ts:71 deletes the cache after every successful install, replacement, or removal.
Deserialization src/infra/kysely-sync.ts:86 deletes the cache in finally, including failed deserialization.
Row execution error src/infra/kysely-sync.ts:207 returns the iterator to reset the statement, and src/infra/kysely-sync.ts:188 releases the active guard. Recovery is tested at src/infra/kysely-sync.test.ts:350.
Rollback failure forced close src/infra/sqlite-transaction.ts:201 clears before close. src/infra/sqlite-transaction.test.ts:195 proves the original operation error remains the propagated error.

Shared state database owner:

Disposal path Clear proof
Terminal latch close src/state/openclaw-state-db.ts:106
Stale-handle reopen src/state/openclaw-state-db.ts:505
Mid-open schema or pragma failure src/state/openclaw-state-db.ts:548
Close by path src/state/openclaw-state-db.ts:612
Close all src/state/openclaw-state-db.ts:624
Test reset src/state/openclaw-state-db.ts:639 delegates to close all.
Doctor repair src/state/openclaw-state-db.ts:285
Existing read-only verification failure src/state/openclaw-state-db.ts:407
Existing read-only owner close src/state/openclaw-state-db.ts:430
Fresh read-only helper close src/state/openclaw-state-db-readonly.ts:64

Per-agent database owner:

Disposal path Clear proof
Terminal latch close src/state/openclaw-agent-db.ts:122 delegates to close by path and the shared close helper at src/state/openclaw-agent-db.ts:490.
Stale incognito or file-backed handle reopen src/state/openclaw-agent-db.ts:244 and src/state/openclaw-agent-db.ts:293 delegate to the clear at src/state/openclaw-agent-db.ts:490.
Mid-open schema or pragma failure src/state/openclaw-agent-db.ts:346
Outer open-failure cleanup src/state/openclaw-agent-db.ts:380 delegates to the clear at src/state/openclaw-agent-db.ts:490.
Close by path src/state/openclaw-agent-db.ts:606 delegates to the clear at src/state/openclaw-agent-db.ts:490.
Transient dispose src/state/openclaw-agent-db.ts:642 delegates to close by path.
Close all src/state/openclaw-agent-db.ts:652 delegates to the clear at src/state/openclaw-agent-db.ts:490.
Test reset src/state/openclaw-agent-db.ts:660 delegates to close all.
LRU eviction src/state/openclaw-agent-db.ts:521 delegates to the clear at src/state/openclaw-agent-db.ts:490.
Maintenance repair src/state/openclaw-agent-db-maintenance.ts:122
Fresh read-only helper close src/state/openclaw-agent-db-readonly.ts:113

The following short-lived handles deliberately never call enableNodeSqliteKyselyStatementCache and are outside the prepared-statement cache lifecycle: schema preflight at src/state/openclaw-database-preflight.ts:104 and src/state/openclaw-database-preflight.ts:139, startup checkpoint at src/state/openclaw-state-db-startup-checkpoint.ts:65, verification worker at src/state/openclaw-database-verify.worker.ts:49, schema-repair detection at src/state/openclaw-state-db-schema-repair.ts:172, snapshot source and verification handles at src/infra/sqlite-snapshot.ts:661, src/infra/sqlite-snapshot.ts:685, and src/infra/sqlite-snapshot.ts:715, agent owner inspection at src/state/openclaw-agent-db.ts:196, and incognito agent databases at src/state/openclaw-agent-db.ts:250.

Verification

node scripts/run-vitest.mjs src/infra/kysely-sync.test.ts
  15 passed

node scripts/run-vitest.mjs src/state/openclaw-state-db.test.ts src/state/openclaw-agent-db.test.ts
  191 passed, 6 skipped

node scripts/run-vitest.mjs src/infra/sqlite-transaction.test.ts
  10 passed

node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo
  passed

node scripts/run-oxlint.mjs src/infra/kysely-sync.ts src/infra/kysely-sync.test.ts src/infra/sqlite-transaction.ts
  passed

node scripts/run-oxlint.mjs src/infra/sqlite-transaction.test.ts
  passed

./node_modules/.bin/oxfmt --check src/infra/kysely-sync.ts src/infra/kysely-sync.test.ts src/infra/sqlite-transaction.ts src/infra/sqlite-transaction.test.ts
  passed

git diff --check
  passed

.agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main --stream-engine-output
  autoreview clean: no accepted/actionable findings reported
  overall: patch is correct (0.9)

The new retention tests are not tautological. Each observes independent WeakRef liveness 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

  • Incognito :memory: agent databases remain intentionally uncached and therefore do not receive this performance improvement.
  • No live gateway, service, container, or production state database was started, stopped, restarted, or touched.
  • No networked or cross-platform runtime proof was run.
  • Full repository test and build suites were not run.
  • The planned incremental subagent registry rewrite was intentionally not included or tested.

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

  • Test-only: the transcript-load and pairing-scan tests counted db.prepare() calls as query proxies; statement caching legitimately reuses statements, so they now count executions via the shared test/helpers/sqlite-statement-execution-counter.ts (cache-cleared at attach).
  • Folded main-side fork-CI fix: scripts/pr-lib/review.sh validated the head SHA by shelling out to rg, 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.

@VACInc
VACInc force-pushed the perf/cache-prepared-statements branch from e13a222 to 5dcd179 Compare July 27, 2026 22:28
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 28, 2026, 1:23 AM ET / 05:23 UTC.

ClawSweeper review

What this changes

The 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 readiness

⚠️ Ready for maintainer review - 3 items remain

This 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 DatabaseSync owner; merge should wait for proof on the current merge result and an owner-level lifecycle check.

Priority: P2
Reviewed head: 447704bf3968fd5bc80ffa6a2cfb13ded49322ba
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has strong real workload evidence and focused lifecycle coverage; its remaining uncertainty is the availability-sensitive ownership invariant on the current merge result.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body includes an after-fix real workload run in a throwaway state directory, with before/after prepare and elapsed-time measurements, plus focused runtime test transcripts. No private data is exposed in the supplied evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body includes an after-fix real workload run in a throwaway state directory, with before/after prepare and elapsed-time measurements, plus focused runtime test transcripts. No private data is exposed in the supplied evidence.
Evidence reviewed 6 items Current implementation gap: The PR body identifies the existing synchronous Kysely execution path as preparing and immediately discarding native SQLite statements; the proposed cache is enabled only from the shared-state and file-backed agent-state database open paths.
Lifecycle ownership coverage: The branch clears the cache in the shared and per-agent database open-failure paths and in the rollback-failure forced-close path, matching the stated invariant that every cache-enabled owner clears before close.
Execution-count regression coverage: The branch replaces tests that used prepare-call counts with a helper that counts matching statement iterations, so those tests continue to assert actual query execution after statement reuse is introduced.
Findings None None.
Security None None.

How this fits together

OpenClaw’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
Loading

Decision needed

Question Recommendation
Should this bounded performance cache be accepted after current-merge lifecycle proof, given that native cached statements make every future database-owner disposal path responsible for clear-before-close? Require current-merge lifecycle proof: Rebase or test the merge result and confirm the shared and agent database owners still clear cached statements before every close-like transition.

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

  • Resolve merge risk (P1) - Cached native StatementSync objects retain their DatabaseSync owner. The branch covers known close, repair, eviction, and rollback-failure paths, but this invariant must be rechecked against the exact current-main merge result before landing.
  • Resolve merge risk (P1) - The branch is behind main; its focused evidence is strong, but final availability and test proof should run on the actual merge result rather than the older base alone.
Agent review details

Security

None.

PR surface

Source +191, Tests +491, Other +3. Total +685 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 210 19 +191
Tests 5 513 22 +491
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 4 1 +3
Total 10 727 42 +685

Review metrics

Metric Value Why it matters
Per-database cache budget 32 retained statements, 32 admission candidates, 64 KiB per admission The bounded cache limits retention, but its native statement ownership makes lifecycle handling more important than an unbounded process-wide optimization.

Stored data model

Persistent data-model change detected: database schema: src/infra/kysely-sync.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh proof on the merge result (recommended)
    Validate the exact current-main merge result with the cache lifecycle tests and relevant state-owner tests before merging this handle-retention-sensitive optimization.
  2. Accept the retention invariant
    Maintainers may merge based on the documented owner audit if they explicitly accept that future cache-enabled owners must preserve clear-before-close.

Technical review

Best possible solution:

Rebase or otherwise validate the clean merge result against current main, then retain the bounded database-owned cache only if every cache-enabled database owner still clears it before close, replacement, repair, and eviction.

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.

Labels

Label justifications:

  • P2: This is a bounded internal performance improvement with no evidence of a current user-facing outage or data-integrity regression.
  • merge-risk: 🚨 availability: A missed clear-before-close path can retain database handles through cached native statements and affect long-running process resource availability.
  • 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 (terminal): The PR body includes an after-fix real workload run in a throwaway state directory, with before/after prepare and elapsed-time measurements, plus focused runtime test transcripts. No private data is exposed in the supplied evidence.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes an after-fix real workload run in a throwaway state directory, with before/after prepare and elapsed-time measurements, plus focused runtime test transcripts. No private data is exposed in the supplied evidence.

Evidence

What I checked:

  • Current implementation gap: The PR body identifies the existing synchronous Kysely execution path as preparing and immediately discarding native SQLite statements; the proposed cache is enabled only from the shared-state and file-backed agent-state database open paths. (src/infra/kysely-sync.ts:1, 447704bf3968)
  • Lifecycle ownership coverage: The branch clears the cache in the shared and per-agent database open-failure paths and in the rollback-failure forced-close path, matching the stated invariant that every cache-enabled owner clears before close. (src/state/openclaw-state-db.ts:524, 447704bf3968)
  • Execution-count regression coverage: The branch replaces tests that used prepare-call counts with a helper that counts matching statement iterations, so those tests continue to assert actual query execution after statement reuse is introduced. (test/helpers/sqlite-statement-execution-counter.ts:1, 447704bf3968)
  • Feature provenance: The PR’s nine-commit history shows the cache introduced by VACInc and subsequent lifecycle, test-counter, and fork-CI follow-ups by steipete; this is still an unmerged branch rather than behavior already present on current main. (src/infra/kysely-sync.ts:1, 447704bf3968)
  • Real behavior proof: The PR body records an after-fix throwaway-state-directory run of 64 sequential registry snapshot writes: 2,144 executions remained constant while prepares fell from 2,144 to 65 and workload time fell from 168.93 ms to 127.27 ms. (src/infra/kysely-sync.test.ts:61, 447704bf3968)
  • Related automation fix is separate: The small shell change in this PR is adjacent to the merged review-artifact integrity work in fix(pr): bind review artifacts to the PR being landed #114897, but it fixes fork-runner availability of rg rather than the SQLite cache’s root problem. (scripts/pr-lib/review.sh:160, 447704bf3968)

Likely related people:

  • steipete: Posted the documented lifecycle audit and authored the four most recent branch commits that adapt tests, repair the fork-CI guard, and address cache-review follow-ups. (role: recent reviewer and follow-up contributor; confidence: medium; commits: ab1b840c91c7, 84a643baa9ea, 38e7ee97550b; files: src/infra/kysely-sync.test.ts, test/helpers/sqlite-statement-execution-counter.ts, scripts/pr-lib/review.sh)
  • VACInc: Authored the initial cache implementation plus the metadata, retention, and close-lifecycle follow-up commits on the proposed branch. (role: implementation contributor; confidence: medium; commits: 0b9151bb9b03, 7cf41e52d78c, 59ad2940d318; files: src/infra/kysely-sync.ts, src/state/openclaw-state-db.ts, src/state/openclaw-agent-db.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Rebase or validate the exact clean merge result against current main.
  • Run the focused cache, shared-state, agent-state, and rollback-failure tests on that merge result.

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 (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-27T23:33:27.734Z sha 98b37fff10ef6d009198c09492ce4bba9780a7f3 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-27T23:46:40.270Z sha 24448d1c5cfcdf27835be53c45ef6179a98a2abc :: needs changes before merge. :: [P1] Guard newer node:sqlite methods on supported Node releases
  • reviewed 2026-07-28T00:27:28.122Z sha f2060a141efefbbc5e48439b78f3e5105fe4c3f4 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-28T00:37:06.052Z sha fae111bd9110009386f6d9181cb1c06fada146c8 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-28T00:43:33.633Z sha fae111bd9110009386f6d9181cb1c06fada146c8 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-28T03:23:27.440Z sha 212ee2aa0ba113442c5ef87d7654886b69fb621a :: needs maintainer review before merge. :: none
  • reviewed 2026-07-28T03:34:51.113Z sha 0327b792179b283020d3f6dd2e6ca7090607e05e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-28T04:22:24.888Z sha 6e0e98e0240ef86b118ce2185a6cfd05afc23561 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jul 27, 2026
@VACInc
VACInc force-pushed the perf/cache-prepared-statements branch from 98b37ff to 24448d1 Compare July 27, 2026 23:37
@VACInc
VACInc marked this pull request as ready for review July 27, 2026 23:41
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed 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. P2 Normal backlog priority with limited blast radius. labels Jul 27, 2026
@VACInc
VACInc marked this pull request as draft July 28, 2026 00:22
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 28, 2026
@VACInc
VACInc force-pushed the perf/cache-prepared-statements branch from f2060a1 to fae111b Compare July 28, 2026 00:32
@VACInc
VACInc marked this pull request as ready for review July 28, 2026 00:38
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Jul 28, 2026
@steipete
steipete force-pushed the perf/cache-prepared-statements branch from fae111b to 0bfd007 Compare July 28, 2026 03:13
@steipete

Copy link
Copy Markdown
Contributor

Maintainer update: rebased onto current main and pushed two fixes so CI can evaluate the real merge result (head is now 0bfd0071).

  1. Kysely guardrail violations in src/infra/kysely-sync.test.ts: the four raw-SQL test sites (nested_value() UDF re-entry, length(?) parameter retention, oversized sql.raw admission, json(?) step-error) now carry /* kysely-allow-raw: ... */ comments explaining why each needs raw SQL — they exercise the statement cache itself with schema-free scalar queries, which is exactly the narrow boundary the guardrail allowlist exists for. node scripts/check-kysely-guardrails.mjs is green.

  2. session-accessor.sqlite-message-cut.test.ts rewind/switch/fork failures: these were not a product regression — the test counted db.prepare() calls as a proxy for full transcript loads, and statement caching legitimately reuses prepared statements, so the proxy undercounted while the actual reload (and the branch-listing correctness asserted right after) was intact. The counter now clears the statement cache at attach and counts iterate() executions of the transcript query instead, which measures the behavior the test actually cares about and is cache-agnostic. All 18 tests pass.

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 clearNodeSqliteKyselyCacheForDatabase before close — both owners funnel through single close helpers, mid-open failure and rollback-forced-close paths included; LRU eviction skips in-transaction and incognito handles. Driver-duplication check: live node:sqlite probes confirm no driver-level statement caching (distinct objects per prepare, 6x timing delta), and the repo's Kysely facade is compile-only, so this cache duplicates nothing.

Local proof: node scripts/run-vitest.mjs src/infra/kysely-sync.test.ts src/config/sessions/session-accessor.sqlite-message-cut.test.ts (20 tests green), node scripts/check-kysely-guardrails.mjs green, oxfmt clean, Codex autoreview clean.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jul 28, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes labels Jul 28, 2026
@steipete
steipete force-pushed the perf/cache-prepared-statements branch from 6e0e98e to 38e7ee9 Compare July 28, 2026 05:10
@openclaw-barnacle openclaw-barnacle Bot removed the cli CLI command changes label Jul 28, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Jul 28, 2026
@steipete
steipete merged commit accc6cc into openclaw:main Jul 28, 2026
191 of 197 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 29, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. scripts Repository scripts size: L 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.

2 participants