Skip to content

improve(audit): reduce database reads while recording events - #200523

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-state-db-audit-page-reads-20260919
Nov 17, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-state-db-audit-page-reads-20260919

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Recording audit events on a large state database repeatedly walks retained history just to find the rows beyond its cap. This consumes SQLite page reads and writer CPU, increasing contention for other state operations.

User Impact

User impact: audit recording does less database work while preserving the same retained events, expiry cutoffs, pruning budgets and FIFO ordering. No schema, index, configuration, collection default or migration changes are required.

Why This Change Was Made

Identity and decision retention step through 100,000/250,000 ordered entries to find an overflow boundary on each insert. Activity and delivery-progress overflow also walk retained rows. Count the existing compact indexes, then select only the oldest excess rows for deletion inside the same synchronous transaction. Progress reuses its existing count; activity retains its exact-count recovery behavior. Runtime changes total five net added lines across the existing owners.

Evidence

A synthetic 4.63 GB database holds 100k activity events, 100k identity contexts, 250k decision facts and 200k progress rows. Five serial A1/A2/B groups used fresh fixture copies for each arm and the real shared writer kernel. No production data or service access was used. Every arm preserved identical row digests and counts.

Measurement A1 A2 B
Main DB reads, 1,200 turns 5,227,050 5,227,053 2,322,272
Median writer CPU, 1,000 turns 10.69 s 11.75 s 5.39 s
Median writer elapsed, 1,000 turns 10.75 s 11.84 s 5.44 s
Median batch p50 41.2 ms 43.7 ms 21.0 ms
Median batch p99 75.8 ms 88.6 ms 42.0 ms
Median sampled JS allocation 845.27 MB 846.17 MB 846.94 MB

Main reads decrease 55.6%; CPU and latency beat both controls. Allocation differs by 0.09–0.20%, within the controls' observed range. Pager and allocation instrumentation were measured separately from timing. VFS reads measure SQLite file reads, not physical disk I/O; macOS/APFS with a warm OS cache does not reproduce filesystem stalls. Indexed INSERT probes were sub-millisecond: this change addresses measured retention waste without claiming to explain multi-second production INSERTs or all other shared-state readers.

The documented benchmark read budget fails on base (5,227,048 > 3,000,000) and passes on the fix (2,322,273), with matching row digests. Five cold SQLite-cache SQL probe groups also preserve deletion counts: activity misses 9,691 → 2,382; identity 1,254 → 1,124; decision 3,114 → 861. CPU profiles attribute the largest saving to decision retention.

All 86 focused tests pass across audit-events, execution-identity-context, execution-decision-facts, message-delivery-progress-store and audit-event-writer.worker. Existing ordering, budget, replay/rollback, lazy-store and count-drift expectations remain unchanged. Codex autoreview found no actionable P0–P2 findings. Both unused-file scans, targeted typecheck/lint/format, SQLite guards and docs link checks pass. No affected Control UI imports were found.

pnpm check:changed passes its other gates but reports an inherited main regression: unused exports resolveSessionTranscriptPath and resolveSessionTranscriptPathInDir. Both findings reproduce on exact base 96763b979fed377e61d44520294b9eb12a740ae0. Introducing commit 4c79d8f41631ede63a1de20546224ee4c8c37e50 (#200461) removed their last production callers from src/gateway/session-transcript-files.fs.ts while leaving the exports. These files are unchanged here; this is an identified main regression, not a passing check.

Count existing compact indexes and delete only the oldest excess rows inside the existing synchronous transactions. Preserve all retention bounds and FIFO ordering. Synthetic A/A/B proof cuts main-DB reads 55.6% and writer CPU about half, with identical retained rows.
@clawsweeper

clawsweeper Bot commented Nov 17, 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 scripts Repository scripts size: M labels Nov 17, 2026
@steipete
steipete marked this pull request as ready for review November 17, 2026 09:22
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T09:24:46.825319Z c1837aa Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces deep retention OFFSET scans with row counts and oldest-row selection inside the existing audit storage owners.

Example: Record 1,200 synthetic turns with 250,000 retained decision facts and the other audit tables at their caps.

  • Before: The reported baseline performs approximately 5.23 million main-database reads.
  • After: The reported candidate performs approximately 2.32 million reads while retaining identical row counts and digests.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, apparently correct optimization with useful production-kernel measurements; evidence remains scoped to the in-process workload.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored performance PR is outside the contributor proof gate; its supplied real-writer-kernel measurements cover retention cost and persisted-row equivalence, without establishing Gateway transport or physical-I/O performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large retained audit histories consume writer CPU and database reads that compete with other state operations.
Reason: The maintainer-authored direction has measured value, a small production change, and no new product setting or retention policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a focused, measured reduction in audit retention work that current main does not contain; no actionable correctness or security findings were identified.

Priority: P2
Reviewed head: c1837aa50afb2aa3a63b5acfc594b790aac880b2

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared-state audit writer receives queued activity, execution identity, decision, and delivery-progress records, persists them, and prunes retained history within existing transactions.

flowchart LR
  A[Audit producers] --> B[Audit FIFO]
  B --> C[Shared state writer]
  C --> D[Four retention owners]
  D --> E[State database]
  E --> F[Audit inspection]
Loading

Technical review

Best possible solution:

Retain the focused query replacements and rerunnable benchmark while preserving the existing storage owners and retention contracts.

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

The baseline queries visibly traverse deep retained-row offsets, and the supplied benchmark records the corresponding read-budget failure; this review did not execute the workload.

Is this the best way to solve the issue?

The change addresses measured work at the existing owners and preserves equivalent oldest-first selection, expiry budgets, transaction scope, and rollback invalidation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Identity and decision overflow pruning keeps the original intent (4061902: Replace materialized retained-ID sets with an indexed overflow boundary while preserving oldest-first deletion and the remaining expiry budget.)
  • Activity overflow pruning and count recovery keeps the original intent (3a2d76f: Embed the cutoff in deletion and repair cached count drift once; the new query shape retains the recovery behavior and explains the extra count through measured page-read savings.)
  • Delivery-progress overflow pruning keeps the original intent (b916ac7: Remove a separate cutoff probe while preserving sequence ordering, retained headroom, and affected-row count updates.)
  • Audit writer benchmark keeps the original intent (4f78407: Measure real writer batching costs and persisted outcomes; this PR extends that workload with large fixtures and separate pager instrumentation.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 6e4d1d5 adds src/audit/audit-event-store.ts:597 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6e4d1d5f2a75; files: src/audit/audit-event-store.ts)
  • Josh Avant: Raw commit 562391b adds src/audit/execution-decision-facts.ts:247 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 562391b9af3c; files: src/audit/execution-decision-facts.ts)

PR surface

Source +5, Docs +33, Other +129. Total +167 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 37 32 +5
Tests 0 0 0 0
Docs 1 33 0 +33
Config 0 0 0 0
Generated 0 0 0 0
Other 3 153 24 +129
Total 8 223 56 +167

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime production versus tests Production +37/-32 lines, net +5; test files unchanged. The small runtime increase replaces expensive retained-row traversal without introducing another owner or cache; benchmark code supplies the performance regression proof.

Labels

Label changes:

  • add P2: Measured audit-writer savings benefit large retained databases, with no evidence of an urgent availability regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Measured audit-writer savings benefit large retained databases, with no evidence of an urgent availability regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 17, 2026, 4:38 AM ET / 09:38 UTC.

@steipete
steipete merged commit e6c9481 into main Nov 17, 2026
212 of 214 checks passed
@steipete
steipete deleted the steipete/perf-micro-state-db-audit-page-reads-20260919 branch November 17, 2026 09:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

RomneyDa added a commit that referenced this pull request Nov 17, 2026
Release adaptation: backport only the Socket Mode reconnect waiter owner
and focused regression tests; omit the performance harness and main-only
transport documentation addition. Add listener-count assertions for timer
settlement and disconnect cancellation; adjust the test allocation to 41.

Companion dispositions: #198007 is specific to SDK 3.2 callback/abort
semantics and is not applicable to this line pinned to socket-mode 3.1.0.
#197657 retires main allocations; other audit hits (#200523, #197009,
#194964, #184507, #192197, #192051, #190003, #189850) only overlap the
excluded shared perf README. No later #188745 mention through bd692e9.

(cherry picked from commit a1d1da7)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…w#200523)

Count existing compact indexes and delete only the oldest excess rows inside the existing synchronous transactions. Preserve all retention bounds and FIFO ordering. Synthetic A/A/B proof cuts main-DB reads 55.6% and writer CPU about half, with identical retained rows.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M 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