Skip to content

improve: reduce audit event persistence overhead - #150243

Merged
steipete merged 2 commits into
mainfrom
codex/audit-event-prepared-queries
Sep 17, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/audit-event-prepared-queries

Conversation

@steipete

@steipete steipete commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #150239

What Problem This Solves

The default audit ledger rebuilds the same INSERT and exact post-prune SELECT for every run or tool event, adding avoidable work to its writer queue.

User Impact

Reduces audit persistence overhead. The real tool-event writer improved 6.67% at the paired median in a fixed component experiment; message-event gains were smaller. No configuration, schema, durability, or retention change.

Why This Change Was Made

Retain the two compiled query shapes with each physical SQLite connection in an audit query sibling using the existing prepared-query helper. Every write still binds fresh fields and runs the same native operations, transaction, HMAC projection, pruning, sequence validation, and authoritative reread.

Validation also exposed a pre-existing Windows fixture cleanup error. The writer test now closes the shared database before removing its temporary directory in one teardown hook; assertions and deadlines are unchanged.

Evidence

  • Full-owner comparison on Node 26.8.2 / SQLite 3.53.4: identical outcomes and audit SQL/method/binding traces for run, tool, and message events; duplicates, expiry, rollback/reuse, integer overflow, sibling databases, close/reopen, and real FIFO drain.
  • Thirty warm events compile 90 queries before and 30 after, with the same 90 native calls. Cold compilation falls from 91 to 33, with 91 native calls in both versions.
  • Fixed timing: three warmup and seven measured alternating pairs per cell, 30 events per arm. All samples retained; 22/28 measured pairs faster.
Entry point Baseline median, ms / 30 events Candidate median, ms / 30 events Median paired reduction Faster pairs
Direct tool events 50.444 47.256 6.80% 6/7
Tool-event writer and drain 54.722 52.202 6.67% 6/7
Direct message events 46.755 45.633 2.96% 5/7
Message-event writer and drain 56.644 54.242 1.72% 5/7

These are modest component results on a shared Windows host, not whole-Gateway gains. Slower pairs are retained (worst 8.39% slower). Invalid initial harness runs are preserved separately: fixture rowid restoration and an unreferenced writer-readiness wait were corrected before the complete fixed cohort; production code was unchanged.
Focused Windows validation: 116 tests passed across the audit store (58), writer (12), and Gateway subscription (46) suites. The unchanged baseline reproduced the writer cleanup failure before the fixture repair. Formatting and diff whitespace checks passed.

Independent reviews passed through P2 with no actionable findings, including the follow-up sibling extraction. Targeted type-aware lint and formatting passed for the extracted owner and query module. The initial CI run caught a newly enforced 700-line cap; the extracted owner now has 699 nonblank lines, with no suppression or baseline change. Hosted CI passed on revised head 1f3c488, including the required openclaw/ci-gate, line-cap ratchet, types, lint, and selected runtime suites.

The 116 local test passes and benchmark cohort preceded the mechanical module extraction. The revised head has now passed hosted CI. No new local benchmark or local runtime pass is claimed after extraction. Native review, prepare, and merge completed on a fresh Blacksmith Testbox. Landed as 8c959de; main ancestry and exact landed source hashes were verified. Native recovery receipts were transferred and verified before the owned lease was stopped.

Data-model compatibility: the reviewed diff changes only the audit store, its new query sibling, and writer test teardown. It changes no schema, migration, generated database types, schema version, defaults, persisted fields, indexes, durability, or retention. The query sibling imports the existing generated table type and compiles the same INSERT/SELECT with all 30 fresh values; it executes no DDL. Existing database files require no migration and use the unchanged schema/bootstrap owners. The full-owner experiment checked identical SQL/method/bindings and close/reopen behavior; revised-head CI is green. The automated 'database schema: src/audit/audit-event-queries.ts' classification is a path-based false positive, so no migration-specific gate applies to this diff.

@clawsweeper

clawsweeper Bot commented Sep 16, 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.

@steipete
steipete marked this pull request as ready for review September 16, 2026 19:01
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 16, 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 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 16, 2026, 9:51 PM ET / September 17, 2026, 01:51 UTC (Revision 2).

ClawSweeper review

What this changes

The PR reuses compiled audit insert and reread queries per SQLite connection and closes the test database before removing temporary directories.

Merge readiness

⛔ Blocked before merge - 1 item remains

The optimization remains useful and has no actionable findings. The previous migration-proof blocker does not apply: the introduced changes preserve the existing stored format and persistence semantics.

Priority: P2
Reviewed head: 1f3c488487485ce8e13ad05a8a4f326094924577

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with relevant production-owner measurements, preserved storage semantics, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Reported Windows component results exercise the actual audit store and writer/drain against SQLite, showing equivalent outcomes and reduced compilation overhead. The measurements precede a verified mechanical extraction; exact-head hosted CI supplies supplemental validation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Reported Windows component results exercise the actual audit store and writer/drain against SQLite, showing equivalent outcomes and reduced compilation overhead. The measurements precede a verified mechanical extraction; exact-head hosted CI supplies supplemental validation.
Evidence reviewed 9 items Introduced scope and unchanged storage contract: The complete merge-base-to-head delta changes query compilation and test teardown only. All 30 inserted fields, source-id conflict handling, textual sequence return, pruning, range validation, and post-prune reread remain equivalent; there is no DDL, migration, persisted cache, or configuration change.
Existing executor retains native lifecycle ownership: Prepared query helpers bind invocation-local values and execute through the same synchronous executor. Native statement invalidation, authorizer transitions, reentry protection, and disposal remain with the existing cache owner; the new WeakMap retains compiled shapes rather than audit results or authorization decisions.
Current main still performs repeated compilation: At fetched main, recordAuditEvent still constructs and compiles its INSERT and exact SELECT on each call. The merged SQLite bulk-read improvement at #149769 changes result retrieval, not this compilation cost.
Findings None None.
Security None None.

How this fits together

OpenClaw’s audit writer queues run, tool, and enabled message metadata for storage in the shared SQLite database. The audit store persists and prunes these records before returning them for operational inspection.

flowchart TD
  A[Run and tool events] --> C[Audit writer queue]
  B[Enabled message events] --> C
  C --> D[State write transaction]
  D --> E[Compiled queries with fresh values]
  E --> F[SQLite audit ledger]
  F --> G[Prune and reread]
  G --> H[Recorded audit event]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +66, Tests +1. Total +67 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 84 18 +66
Tests 1 3 2 +1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 87 20 +67

Review metrics

Metric Value Why it matters
Reported warm compilation cost 90 → 30 compilations per 30 events; native calls remain 90 The measured reduction isolates JavaScript query construction without skipping database work.
Production versus test growth Production net +66 lines; tests net +1 line Production growth explicitly binds 30 fields into reusable typed queries; test growth fixes cleanup ordering.

Stored data model

Persistent data-model change detected: database schema: src/audit/audit-event-queries.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #150239
Summary: This PR directly implements the linked audit compilation optimization; the earlier SQLite bulk-read change addresses a separate executor cost.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep compiled query reuse inside the audit store’s existing transaction and native execution lifecycle, preserving all persisted values and reread semantics.

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

Not applicable as a functional bug: this is a performance improvement, and current-main source confirms repeated compilation while the supplied experiment measures its cost.

Is this the best way to solve the issue?

Yes. Reusing the existing prepared-query helper removes repeated compilation without introducing a competing statement owner or changing database compatibility.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Reported Windows component results exercise the actual audit store and writer/drain against SQLite, showing equivalent outcomes and reduced compilation overhead. The measurements precede a verified mechanical extraction; exact-head hosted CI supplies supplemental validation.

Label justifications:

  • P2: This is a bounded audit persistence optimization with measured component gains and no urgent user-facing failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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): Reported Windows component results exercise the actual audit store and writer/drain against SQLite, showing equivalent outcomes and reduced compilation overhead. The measurements precede a verified mechanical extraction; exact-head hosted CI supplies supplemental validation.
  • proof: sufficient: Contributor real behavior proof is sufficient. Reported Windows component results exercise the actual audit store and writer/drain against SQLite, showing equivalent outcomes and reduced compilation overhead. The measurements precede a verified mechanical extraction; exact-head hosted CI supplies supplemental validation.

Evidence

What I checked:

  • Introduced scope and unchanged storage contract: The complete merge-base-to-head delta changes query compilation and test teardown only. All 30 inserted fields, source-id conflict handling, textual sequence return, pruning, range validation, and post-prune reread remain equivalent; there is no DDL, migration, persisted cache, or configuration change. (src/audit/audit-event-queries.ts:14, 1f3c48848748)
  • Existing executor retains native lifecycle ownership: Prepared query helpers bind invocation-local values and execute through the same synchronous executor. Native statement invalidation, authorizer transitions, reentry protection, and disposal remain with the existing cache owner; the new WeakMap retains compiled shapes rather than audit results or authorization decisions. (src/infra/kysely-sync-cache-state.ts:94, 1f3c48848748)
  • Current main still performs repeated compilation: At fetched main, recordAuditEvent still constructs and compiles its INSERT and exact SELECT on each call. The merged SQLite bulk-read improvement at improve: speed up SQLite reads on Node 24.20 #149769 changes result retrieval, not this compilation cost. (src/audit/audit-event-store.ts:628, 1fbb41545ec5)
  • Latest supplied release retains the original path: The v2026.9.4 source still builds both queries per event, so the requested optimization is neither already on fetched main nor present in the supplied latest release. (src/audit/audit-event-store.ts:628, 3a9d69db306c)
  • Previous compatibility concern resolved by source: The previous review requested migration or upgrade proof. The captured body now explains the unchanged persistent contract, and source inspection confirms that explanation. The storage policy distinguishes bounded query improvements from material changes to schemas, durability, retention, or permissions. Public docs: docs/reference/database-schemas/storage-changes.md. (docs/reference/database-schemas/storage-changes.md, 1f3c48848748)
  • Production-owner component evidence: The captured PR body reports a Windows Node 26.8.2 / SQLite 3.53.4 comparison through recordAuditEvent and the real writer/drain: matching SQL, bindings and outcomes across duplicates, expiry, rollback, overflow, separate databases and reopen. Thirty warm events reduced compilations from 90 to 30; the tool writer’s paired median improved 6.67%. These measurements precede the final module extraction and do not claim whole-Gateway gains. (5657549f190e)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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-16T19:16:03.001Z sha 1f3c488 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 17, 2026
@steipete
steipete merged commit 8c959de into main Sep 17, 2026
204 of 205 checks passed
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@steipete
steipete deleted the codex/audit-event-prepared-queries branch September 17, 2026 01:57
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 17, 2026
* improve: reduce audit event persistence overhead

* refactor: isolate prepared audit event queries
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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.

Audit writer repeatedly compiles fixed SQLite queries

1 participant