Skip to content

perf(sqlite): checkpoint WAL from maintenance ticks instead of commits - #160818

Merged
steipete merged 10 commits into
mainfrom
steipete/perf-micro-long-write-lock-holds-worker-transactions-20260919
Sep 29, 2026
Merged

steipete merged 10 commits into
mainfrom
steipete/perf-micro-long-write-lock-holds-worker-transactions-20260919

Conversation

@steipete

@steipete steipete commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every WAL-mode store connection, including the Gateway main thread, ran with SQLite's default inline autocheckpoint (wal_autocheckpoint = 1000 pages). Once readers keep the log from resetting, every commit above ~4 MiB of WAL retries a PASSIVE checkpoint inside COMMIT and syncs the main database file on the committing thread. On team.openclaw.ai (32.5 GB agent store on btrfs, 3.3 M extents) that made commit steps take 1.5–13.5 s on the main thread and up to 41 s on workers, which showed up as 11–12 s chat.metadata/models.list responses, liveness heartbeats 13 s overdue and database is locked failures for cron maintenance.

Evidence

Journal since boot 20:48Z (57 min): 28 slow SQLite transaction step … step=commit lines, 15 of them isMainThread=true; connections already run synchronous = NORMAL, so the only sync a commit pays is the autocheckpoint; session history disk budget deferred until a completed WAL checkpoint is observed ×15 confirms checkpoints never complete under readers, so every commit re-attempts one.

Change

  • Writers whose WAL maintenance is delegated to a worker (the Gateway's published agent and shared-state handles, via registerSqliteWalWorkerMaintenance) set wal_autocheckpoint = 0 when they register the owner, so they never checkpoint inline; the threshold they had is restored if the owner is cancelled while the handle stays open.
  • Every other connection keeps an inline threshold at 16,384 pages (64 MiB, the existing journal_size_limit) instead of 1,000. It only bounds a writer nobody else checkpoints.
  • The existing 30-minute periodic timer is unchanged (split-brain inspection plus the bounded incremental-vacuum pass). A separate 10-second tick runs checkpoint-only passes (SqliteWalPeriodicRequest.maxPages = 0) and never the split-brain probe. A writer whose maintenance is delegated to a worker skips those ticks inside the scheduler (no worker round trip, which raced store replacement in tests); the worker connections to the same WAL tick inline on their own thread, so checkpoint I/O stays off the Gateway event loop.
  • Checkpoint-only ticks run quiet: a PASSIVE pass blocked by a reader still records health and notifies observers but does not raise onCheckpointError every 10 s; the reclaim pass keeps today's warnings.
  • createSqliteWalMaintenanceScheduler takes the page budget per run; reclaimSqliteWalFreePages treats a zero budget as checkpoint-only.
  • The memory plugin no longer carries wal_autocheckpoint in the publication connection policy it snapshots from the canonical connection and asserts on borrowed worker connections: the value now legitimately differs between a delegating main-thread handle and a worker connection, and checkpoint cadence belongs to each connection's WAL owner.

No config, schema or durability change: synchronous, journal mode, journal_size_limit, close/TRUNCATE behavior and the 30-minute reclaim cadence are unchanged. Update behavior: none beyond the new build; existing stores need no migration.

Revision notes: revision 1 ran the split-brain probe on every tick, which SIGKILLed CI test forks that replace store files; revision 2 addressed the ClawSweeper findings (positive threshold still checkpointing inline above 64 MiB under a pinned reader; wall-clock cadence); revisions 3–4 still ran the probe on the first 10 s fire and exported a constant that tripped the plugin-SDK runtime-API guardrail; revision 5 keeps the periodic timer exactly as before and arms the tick beside it; revision 6 drops the pragma from the memory publication policy after CI showed the borrowed-connection assertion tripping on it; revisions 7–9 fix the per-owner timer counts and stop delegated writers from round-tripping ticks through their worker (a Testbox repro showed SQLite transaction admission was refused in src/auto-reply/reply/session.test.ts; after the fix that file passes 222/222 twice).

Proof (validation)

  • New src/infra/sqlite-wal.checkpoint-tick.test.ts: threshold pragma; a worker-maintained writer disables inline checkpoints and restores the valve on cancel; tick cadence with a real store (first fire checkpoints and reclaims, in-interval ticks checkpoint only, next interval reclaims).
  • Updated fixtures that identified the WAL timer by its 30-minute delay (sqlite-wal.replacement.test-support.ts, sqlite-wal.agent-admission.test.ts, openclaw-state-db.wal.test.ts) and the shared-state pragma test (worker-maintained writer reads wal_autocheckpoint = 0).
  • Testbox (blacksmith-testbox; revision 9 on tbx_01m3nswtg57zz8sewesdys2m0q / tbx_01m3nwg0ffycy0emy5get5khjm): src/auto-reply/reply/session.test.ts 222/222 twice; focused sqlite-wal*, checkpoint-tick, agent-admission, reclamation, state-db.wal, state-db-open, state-db, memory-core publication, gateway memory-search and the plugin-SDK runtime-API guardrail: 359 passed; doctor-maintenance.settlement NOCOW test 30/30 after merging main; node scripts/check-changed.mjs --base origin/main: all lanes ok in 27 min; Codex autoreview (local mode vs origin/main, P0): scoped-clean on revision 9.
  • Docs: docs/reference/database-schemas/integrity-and-recovery.md maintenance paragraph.

Follow-ups (separate): NOCOW (chattr +C) for stores on btrfs (lane in flight), and the worker admission wait that holds the write lock across main-thread round trips.

Inline autocheckpoints ran on every committing connection, including the Gateway main thread, and while readers kept the log from resetting every commit above 4 MiB retried a PASSIVE checkpoint and synced the database file. Raise the inline threshold to the 64 MiB recycling limit as a stalled-owner valve, tick the WAL maintenance timer every 10 s with checkpoint-only passes off the writers, and keep the 30-minute bounded vacuum reclaim.
@clawsweeper

clawsweeper Bot commented Sep 29, 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 docs Improvements or additions to documentation size: S labels Sep 29, 2026
@steipete
steipete enabled auto-merge (squash) September 29, 2026 00:05
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 29, 2026, 2:21 AM ET / 06:21 UTC (Revision 8).

ClawSweeper review

What this changes

The branch moves frequent SQLite WAL checkpoints from published writers to worker connection timers, raises the fallback inline threshold, and updates memory publication policy, tests, and storage documentation.

Regression provenance

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

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this PR open. The latest revision resolves the previously reported duplicate checkpoint schedule, but published writers can now leave WAL backfill waiting while their maintenance worker is idle.

Priority: P1
Reviewed head: 8978cb1eece37558ccf8071a808dfe626ae575f1

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has useful focused validation, but the idle-worker checkpoint gap limits readiness.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The supplied Repository State identifies a MEMBER author, so the ordinary external-contributor proof gate does not apply. Reported Testbox runs exercise real SQLite timer and pragma behavior, but the published-writer/idle-worker case is not covered; no stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied Repository State identifies a MEMBER author, so the ordinary external-contributor proof gate does not apply. Reported Testbox runs exercise real SQLite timer and pragma behavior, but the published-writer/idle-worker case is not covered; no stored-data contract changes.
Evidence reviewed 8 items Current-main behavior: Current main still uses a 1,000-page inline autocheckpoint threshold, so the branch's central performance change is not implemented there.
Introduced checkpoint gap: Registration disables inline checkpoints on the published writer; the new scheduler guard skips its zero-budget ten-second pass.
Worker admission boundary: Agent worker maintenance waits for deferred admission, which is flushed around an admitted worker operation; an idle worker has no such flush.
Findings 1 actionable finding [P2] Keep checkpoints running while the maintenance worker is idle
Security None None.

How this fits together

OpenClaw writes agent and shared state to SQLite databases. WAL maintenance copies committed pages into those databases and reclaims free pages; its scheduling affects disk use and Gateway responsiveness.

flowchart LR
A[Gateway writes] --> B[Published SQLite writer]
B --> C{Worker admitted?}
C -->|Yes| D[Worker checkpoint tick]
C -->|No| E[Thirty-minute pass]
D --> F[WAL backfill]
E --> F
E --> G[Bounded vacuum]
Loading

Before merge

  • Keep checkpoints running while the maintenance worker is idle (P2) - A published agent writer now disables inline checkpoints, and this guard skips its ten-second pass. Its worker-local pass waits for deferred admission, which an idle worker receives only when another operation arrives. Main-thread commits can therefore leave the WAL uncheckpointed until the thirty-minute periodic pass; retain a worker-owned checkpoint path for that interval.
  • Resolve merge risk (P1) - During main-thread writes without an admitted worker operation, the disabled inline checkpoint and skipped ten-second pass can leave WAL pages waiting until the thirty-minute maintenance pass, increasing disk use under sustained writes.
  • Complete next step (P2) - Repair the idle-worker checkpoint gap and validate the published-writer path before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P2] Keep checkpoints running while the maintenance worker is idle — src/infra/sqlite-wal-write-admission.ts:76-79
Agent review details

Security

None.

PR surface

Source +65, Tests +174, Docs 0. Total +239 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 6 85 20 +65
Tests 7 180 6 +174
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 266 27 +239

Review metrics

Metric Value Why it matters
Code growth production +65 net lines, tests +174 net lines The production growth supports the timer split, but the added scheduler state needs published-owner coverage.

Stored data model

Persistent data-model change detected: vector/embedding metadata: extensions/memory-core/src/memory/manager-database-context.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-shadow-task.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Keep worker backfill active (recommended)
    Repair the owner lifecycle so a published writer receives timely worker-side checkpoints even when no worker command arrives.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Cover a published writer making writes while its worker is idle, and preserve current-owner admission and store-replacement checks while restoring timely off-main WAL backfill.

Technical review

Best possible solution:

Keep an off-main checkpoint owner active whenever a published writer has inline checkpoints disabled, including idle-worker periods, while preserving replacement checks and the thirty-minute vacuum cadence.

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

Yes, as a source-level path: let a published writer commit while its worker has no admitted operation, then observe that neither inline nor ten-second checkpointing runs. This read-only review did not execute that scenario.

Is this the best way to solve the issue?

No. Moving checkpoint I/O off the Gateway thread fits the existing owner model, but the proposed scheduling does not cover idle-worker periods.

Full review comments:

  • [P2] Keep checkpoints running while the maintenance worker is idle — src/infra/sqlite-wal-write-admission.ts:76-79
    A published agent writer now disables inline checkpoints, and this guard skips its ten-second pass. Its worker-local pass waits for deferred admission, which an idle worker receives only when another operation arrives. Main-thread commits can therefore leave the WAL uncheckpointed until the thirty-minute periodic pass; retain a worker-owned checkpoint path for that interval.
    Confidence: 0.87

Overall correctness: patch is incorrect
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 2aed86671065.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The PR addresses reported multi-second Gateway stalls and liveness delays in an active database workflow.
  • merge-risk: 🚨 availability: The introduced idle-worker gap can delay WAL backfill and increase disk pressure during sustained writes.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The supplied Repository State identifies a MEMBER author, so the ordinary external-contributor proof gate does not apply. Reported Testbox runs exercise real SQLite timer and pragma behavior, but the published-writer/idle-worker case is not covered; no stored-data contract changes.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/infra/sqlite-wal.checkpoint-tick.test.ts.
  • [P1] node scripts/run-vitest.mjs src/infra/sqlite-wal.agent-admission.test.ts.
  • [P1] node scripts/run-vitest.mjs src/state/openclaw-state-db.wal.test.ts.
  • [P1] node scripts/check-changed.mjs --base origin/main.

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit cc75881 adds src/state/openclaw-agent-db.wal.ts:10 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cc75881752cf; files: src/state/openclaw-agent-db.wal.ts)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Show a real SQLite regression in which a published writer commits while its worker is idle and WAL backfill completes on the intended cadence.
  • Record worker commit latency with a reader pinning WAL above the 64 MiB fallback threshold.

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 (7 earlier review cycles)
  • reviewed 2026-09-29T00:11:50.545Z sha 902c35a :: blocked before merge. :: [P1] Keep pinned-WAL checkpoints off the committing thread | [P2] Use monotonic elapsed time for vacuum cadence
  • reviewed 2026-09-29T00:25:27.439Z sha 902c35a :: blocked before merge. :: [P1] Keep pinned-WAL checkpoints off the committing thread | [P2] Use monotonic elapsed time for vacuum cadence
  • reviewed 2026-09-29T00:36:44.142Z sha 18665a6 :: blocked before merge. :: [P1] Keep pinned-WAL checkpoints off the committing thread | [P2] Use monotonic elapsed time for vacuum cadence
  • reviewed 2026-09-29T01:29:34.557Z sha 01076e7 :: blocked before merge. :: [P2] Keep the worker from scheduling a second ten-second checkpoint
  • reviewed 2026-09-29T02:26:22.651Z sha ad445ca :: blocked before merge. :: [P2] Keep the worker from scheduling a second ten-second checkpoint
  • reviewed 2026-09-29T03:20:46.687Z sha 482452d :: blocked before merge. :: [P2] Avoid a second checkpoint tick on worker connections
  • reviewed 2026-09-29T03:33:55.954Z sha e9e2fae :: blocked before merge. :: [P2] Suppress duplicate worker-local checkpoint ticks

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 29, 2026
Writers whose WAL maintenance is delegated to a worker disable SQLite's automatic checkpoint when they register the owner and restore the 64 MiB valve on cancel. The maintenance timer counts fires: the first fire and every reclaim interval run the split-brain inspection and the bounded vacuum pass, all other ticks are checkpoint-only, so test forks that replace store files no longer trip the fatal containment every 10 s.
@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 Sep 29, 2026
Keep the 30-minute periodic timer as the only owner of the split-brain inspection and the bounded vacuum pass, and arm a separate 10-second checkpoint-only tick beside it, so test forks that replace store files never meet the fatal containment on a tick. Worker-maintained writers remember the inline threshold they had and restore it when their owner is cancelled instead of exporting a shared constant.
…on policy

The memory publication snapshots pragmas from the canonical agent connection and requires a borrowed worker connection to match them. wal_autocheckpoint now legitimately differs between a main-thread handle that delegates checkpoints to its maintenance worker and a worker connection that keeps the inline threshold, so the checkpoint cadence stays with each connection's WAL owner instead of the publication policy.
@openclaw-barnacle openclaw-barnacle Bot added the extensions: memory-core Extension: memory-core label Sep 29, 2026
A main-thread tick delegated every pass through the maintenance worker and raced store replacement; worker-thread connections to the same store now tick inline while a main-thread handle keeps only its periodic pass.
A delegated main-thread writer's tick round-tripped through its maintenance worker and raced store replacement; the scheduler now returns for a zero-budget pass when a worker owner is registered, and worker connections to the same WAL tick inline. Drops the thread-based default, which vitest's thread pool made unreliable.
…ong-write-lock-holds-worker-transactions-20260919
@steipete
steipete merged commit 492c49a into main Sep 29, 2026
241 of 243 checks passed
@steipete
steipete deleted the steipete/perf-micro-long-write-lock-holds-worker-transactions-20260919 branch September 29, 2026 06:26
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 30, 2026
openclaw#160818)

* perf(sqlite): checkpoint WAL from maintenance ticks instead of commits

Inline autocheckpoints ran on every committing connection, including the Gateway main thread, and while readers kept the log from resetting every commit above 4 MiB retried a PASSIVE checkpoint and synced the database file. Raise the inline threshold to the 64 MiB recycling limit as a stalled-owner valve, tick the WAL maintenance timer every 10 s with checkpoint-only passes off the writers, and keep the 30-minute bounded vacuum reclaim.

* perf(sqlite): keep worker-maintained writers off inline checkpoints

Writers whose WAL maintenance is delegated to a worker disable SQLite's automatic checkpoint when they register the owner and restore the 64 MiB valve on cancel. The maintenance timer counts fires: the first fire and every reclaim interval run the split-brain inspection and the bounded vacuum pass, all other ticks are checkpoint-only, so test forks that replace store files no longer trip the fatal containment every 10 s.

* perf(sqlite): run the checkpoint tick beside the periodic pass

Keep the 30-minute periodic timer as the only owner of the split-brain inspection and the bounded vacuum pass, and arm a separate 10-second checkpoint-only tick beside it, so test forks that replace store files never meet the fatal containment on a tick. Worker-maintained writers remember the inline threshold they had and restore it when their owner is cancelled instead of exporting a shared constant.

* perf(memory): keep checkpoint cadence out of the publication connection policy

The memory publication snapshots pragmas from the canonical agent connection and requires a borrowed worker connection to match them. wal_autocheckpoint now legitimately differs between a main-thread handle that delegates checkpoints to its maintenance worker and a worker connection that keeps the inline threshold, so the checkpoint cadence stays with each connection's WAL owner instead of the publication policy.

* test(sqlite): count both maintenance timers in the pragma acquisition test

* perf(sqlite): tick checkpoints from worker connections only

A main-thread tick delegated every pass through the maintenance worker and raced store replacement; worker-thread connections to the same store now tick inline while a main-thread handle keeps only its periodic pass.

* perf(sqlite): skip checkpoint-only ticks on worker-maintained writers

A delegated main-thread writer's tick round-tripped through its maintenance worker and raced store replacement; the scheduler now returns for a zero-budget pass when a worker owner is registered, and worker connections to the same WAL tick inline. Drops the thread-based default, which vitest's thread pool made unreliable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: memory-core Extension: memory-core merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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.

1 participant