Skip to content

fix(state): serialize audit writes through shared owner - #125316

Closed
jesse-merhi wants to merge 2 commits into
mainfrom
jesse/sqlite-single-writer-audit
Closed

jesse-merhi wants to merge 2 commits into
mainfrom
jesse/sqlite-single-writer-audit

Conversation

@jesse-merhi

@jesse-merhi jesse-merhi commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

Summary

The Gateway audit worker opened a second writable connection to openclaw.sqlite. Under concurrent main-agent turns, that gave SQLite two independent WAL/checkpoint owners in one process—the remaining writer-ownership gap after #123674.

This change removes the worker and drains audit metadata through one bounded, process-owned queue backed by the process's cached shared-state connection.

flowchart LR
  A[Gateway and direct-local producers] --> Q[Bounded cloned FIFO]
  Q --> O[Process cached SQLite owner]
  O --> S[(openclaw.sqlite)]
  L[Write lock] --> R[Fail-fast async retry]
  R --> Q
Loading

What changed

  • remove the audit worker and its second writable SQLite connection;
  • preserve non-blocking queue admission, FIFO ordering, backpressure, bounded shutdown, identity/decision records, and outbound delivery progress;
  • make lock probes fail fast and retry asynchronously without blocking the Gateway event loop or consuming metadata-loss warnings;
  • batch retention work and drain audit work before the final shared-state close;
  • split cached-owner, read-only-open, timeout, and retention responsibilities so callers use the correct owner directly;
  • remove obsolete worker packaging, lint, release, and documentation entries.

There is no schema-version change.

Practical proof

An isolated real SQLite run opened the cached owner, queued one audit event, drained the writer, then queried the same owner:

{"dataVersionBefore":2,"dataVersionAfter":2,"rows":1,"quickCheck":"ok"}

data_version remaining unchanged proves the write committed through the existing cached connection rather than a second connection. The event persisted and SQLite's integrity check remained clean.

A second isolated run held a competing BEGIN IMMEDIATE lock while the real queue accepted an event, measured event-loop responsiveness, released the lock, drained shutdown, and inspected the database after closing the cached owner:

{"eventLoopTimerMs":50,"rows":1,"ownerOpenAfterShutdown":false,"quickCheck":"ok"}

This demonstrates the lifecycle Clawsweeper flagged for maintainer confirmation: lock contention did not block the event loop, the accepted event persisted after retry, shutdown left no cached owner open, and the database remained healthy.

Validation

  • fresh isolated cold review: 298 focused tests, format, focused Oxlint, dead exports, import cycles, and diff checks passed;
  • final affected regression suite: 76/76 passed;
  • pnpm tsgo:core;
  • pnpm tsgo:scripts;
  • pnpm docs:list;
  • release and lint-suppression suites: 65/65 passed;
  • native review: two consecutive clean passes;
  • final isolated cold review: clean.

Fixes #123327.

Related: #117262. Complements the external-writer fix in #123674 by removing the remaining in-process audit writer.

@jesse-merhi
jesse-merhi requested review from a team as code owners August 17, 2026 14:49
Copilot AI lite review requested due to automatic review settings August 17, 2026 14:49
@clawsweeper

clawsweeper Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Aug 17, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. 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 Aug 17, 2026
@clawsweeper

clawsweeper Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 20, 2026, 8:14 PM ET / August 21, 2026, 00:14 UTC.

ClawSweeper review

What this changes

The PR replaces the audit worker’s separate SQLite connection with a bounded in-process queue that writes through the shared state-database owner.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 6 items remain

Keep open for maintainer handling: the protected maintainer PR is conflict-dirty, its central shared-owner change is already on current main through #126154, and the prior P1 event-loop blocker remains unresolved.

Priority: P1
Reviewed head: 77a582c9189a68108cbe18118688f09d7847a56b
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The shared-owner direction is meaningful, but the remaining P1 means the current patch is not merge-ready.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR reports isolated real SQLite output, but the external-contributor proof gate does not apply; the remaining blocker is source-proven slow successful persistence.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR reports isolated real SQLite output, but the external-contributor proof gate does not apply; the remaining blocker is source-proven slow successful persistence.
Evidence reviewed 6 items Synchronous persistence remains on the event loop: The queued drain invokes all audit record stores synchronously; a successful transaction is not moved to another thread or process.
Callee uses an immediate synchronous SQLite transaction: The ordinary audit-event path calls runOpenClawStateWriteTransaction, whose implementation calls runSqliteImmediateTransactionSync.
Current test covers lock failure, not slow successful persistence: The event-loop assertion is exercised while a second connection holds BEGIN IMMEDIATE; it does not inject a slow successful audit write or checkpoint.
Findings 1 actionable finding [P1] Keep audit SQLite writes off the Gateway event loop
Security None None.

Live Verification

Command: pnpm test src/audit/audit-event-writer.test.ts

Result: PASS (completed)

pnpm test src/audit/audit-event-writer.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-125316-dE4pit/target$ pnpm test src/audit/audit-event-writer.test.ts
$ node --import tsx scripts/test-projects.mts src/audit/audit-event-writer.test.ts
pnpm test src/audit/audit-event-writer.test.ts
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-125316-dE4pit/target

 ✓  unit  src/audit/audit-event-writer.test.ts (13 tests) 3580ms
     ✓ keeps progress absent while disabled and routes enabled progress off audit_events  323ms
     ✓ keeps a cold owner open nonblocking under a held write lock  343ms
     ✓ keeps the shared queue nonblocking under a held write lock and flushes before stop  343ms
     ✓ preserves FIFO ordering for dependent identity and decision retries  305ms
     ✓ prunes expired identity contexts before preserving exact-envelope conflicts  327ms
     ✓ keeps schema and insert failures off the admission path  435ms
     ✓ keeps malformed, serialization, and key failures nonblocking and redaction-safe  321ms

 Test Files  1 passed (1)
      Tests  13 passed (13)
   Start at  00:15:49
   Duration  6.93s (transform 2.36s, setup 1.00s, import 1.98s, tests 3.58s, environment 0ms)

[test] passed 1 Vitest shard in 17.74s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-125316-dE4pit/target$ pnpm test src/audit/audit-event-writer.test.ts
$ node --import tsx scripts/test-projects.mts src/audit/audit-event-writer.test.ts


























Assertions:

  • PASS expect_output: Test Files

How this fits together

Gateway audit producers enqueue metadata without waiting; the queue later persists it through the process-owned shared SQLite connection. Gateway shutdown unsubscribes audit producers and drains the queue before closing shared state.

flowchart LR
A[Gateway audit producers] --> B[Bounded audit queue]
B --> C[Queue drain]
C --> D[Shared state database owner]
D --> E[SQLite audit records]
F[Gateway shutdown] --> B
F --> D
Loading

Decision needed

Question Recommendation
Should audit persistence be redesigned to keep successful SQLite work off the Gateway event loop before any follow-up is merged? Restore an off-loop audit boundary: Keep one authoritative writer while moving actual audit persistence off the Gateway event loop and add a slow-success regression.

Why: The current shared-owner design removes a duplicate connection but cannot make synchronous DatabaseSync commits nonblocking; choosing the durable owner boundary affects the canonical main implementation.

Before merge

  • Keep audit SQLite writes off the Gateway event loop (P1) - setImmediate only defers the work: this drain synchronously calls the record stores, which immediately enter runOpenClawStateWriteTransaction. A slow successful commit or checkpoint therefore blocks the Gateway loop even though a locked write fails fast; the existing contention test does not cover that case. This is the prior P1 blocker—restore an off-loop persistence boundary and add a slow-success regression.
  • Resolve merge risk (P1) - The queue defers admission but executes successful SQLite writes synchronously on the Gateway event loop, so slow commits or checkpoints can still stall active turns.
  • Resolve merge risk (P1) - GitHub reports the branch as dirty; reconciling its stale docs and state changes against current main requires a maintainer-owned rebase or retirement decision.
  • Resolve merge risk (P1) - The bug-fix branch is net-positive in production surface, so retaining it needs a clear owner-boundary justification beyond the already-merged canonical implementation.
  • Complete next step (P2) - Maintainers need to choose the canonical off-loop single-writer architecture; the current branch is conflict-dirty and its central change is already on main.

Findings

  • [P1] Keep audit SQLite writes off the Gateway event loop — src/audit/audit-event-writer.ts:152-166
Agent review details

Security

None.

PR surface

Source +106, Tests +426, Docs +6, Other -4. Total +534 across 64 files.

View PR surface stats
Area Files Added Removed Net
Source 22 710 604 +106
Tests 36 511 85 +426
Docs 2 23 17 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 4 0 4 -4
Total 64 1244 710 +534

Review metrics

Metric Value Why it matters
Production versus test LOC total +1,244/-710; production net-positive with added focused tests and docs This is a bug-fix refactor with substantial new persistence-path code, so the retained owner boundary must justify the production growth.
State schema version 0 changed The PR changes shared-state write ownership without advancing the SQLite schema contract.

Stored data model

Persistent data-model change detected: database schema: src/audit/message-delivery-progress-store.test.ts, durable storage schema: src/gateway/worker-environments/store.test.ts, migration/backfill/repair: src/flows/doctor-health.ts, persistent cache schema: src/plugin-state/plugin-state-store.test.ts, persistent cache schema: src/state/openclaw-database-verify.impl.ts, persistent cache schema: src/state/openclaw-database-verify.test.ts, and 26 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Repair the canonical writer boundary (recommended)
    Move successful audit persistence off the Gateway event loop while preserving one shared-state owner, then add a slow-write responsiveness regression.
  2. Pause this superseded branch
    Use the merged canonical path as the starting point and retire this conflict-dirty branch after maintainers decide the event-loop architecture.

Technical review

Best possible solution:

Keep the single shared-state owner, but restore an off-loop persistence boundary for audit work and prove a deliberately slow successful write cannot delay the Gateway loop.

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

Yes, from source: enqueue an audit record and make its successful immediate transaction slow; the queue drain executes that transaction synchronously on the Gateway event loop. The existing test only verifies fast failure under a held lock.

Is this the best way to solve the issue?

No. A single shared connection addresses competing writers, but the current queue does not keep successful SQLite work off the Gateway loop; the persistence boundary needs an off-loop design and regression proof.

Full review comments:

  • [P1] Keep audit SQLite writes off the Gateway event loop — src/audit/audit-event-writer.ts:152-166
    setImmediate only defers the work: this drain synchronously calls the record stores, which immediately enter runOpenClawStateWriteTransaction. A slow successful commit or checkpoint therefore blocks the Gateway loop even though a locked write fails fast; the existing contention test does not cover that case. This is the prior P1 blocker—restore an off-loop persistence boundary and add a slow-success regression.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P1: Successful audit writes can still block active Gateway turns, affecting a core runtime path.
  • merge-risk: 🚨 availability: The changed persistence path can introduce Gateway event-loop stalls even when lock contention fails fast.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR reports isolated real SQLite output, but the external-contributor proof gate does not apply; the remaining blocker is source-proven slow successful persistence.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Commit 5564671 merged the equivalent shared-owner audit writer now present on current main. (role: merged canonical implementation author; confidence: high; commits: 5564671c4fe0; files: src/audit/audit-event-writer.ts, src/audit/audit-event-writer.test.ts)
  • Dallin Romney: Current-main blame for the queue implementation terminates at commit 8fdc6d7 in this checkout’s available history. (role: recent current-main contributor; confidence: medium; commits: 8fdc6d7c363d; files: src/audit/audit-event-writer.ts)

Rank-up moves

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

  • Move successful audit persistence off the Gateway event loop while retaining one authoritative state owner.
  • Add a regression that injects a slow successful audit write or checkpoint and observes timer responsiveness.
  • Rebase or retire the conflict-dirty branch against the canonical current-main implementation.

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 (4 earlier review cycles)
  • reviewed 2026-08-17T14:54:28.465Z sha 9531f4c :: needs maintainer review before merge. :: none
  • reviewed 2026-08-17T15:05:49.114Z sha 9531f4c :: found issues before merge. :: [P1] Keep SQLite persistence off the Gateway event loop
  • reviewed 2026-08-17T15:29:28.797Z sha 9531f4c :: found issues before merge. :: [P1] Keep audit SQLite writes off the Gateway event loop
  • reviewed 2026-08-20T23:32:20.208Z sha 77a582c :: found issues before merge. :: [P1] Keep audit SQLite writes off the Gateway event loop

@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. 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. labels Aug 17, 2026
@openclaw-barnacle openclaw-barnacle Bot added the r: skill Auto-close: skills should be published on ClawHub, not added to core. label Aug 20, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 21, 2026
@RomneyDa
RomneyDa deleted the jesse/sqlite-single-writer-audit branch October 22, 2026 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. r: skill Auto-close: skills should be published on ClawHub, not added to core. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Shared state WAL checkpoint copies index pages over SQLite page 1 on local ext4

2 participants