Skip to content

refactor(sqlite): centralize WAL checkpoint execution - #157263

Merged
steipete merged 3 commits into
mainfrom
hostneutral/storage-identity-0924
Sep 24, 2026
Merged

steipete merged 3 commits into
mainfrom
hostneutral/storage-identity-0924

Conversation

@steipete

@steipete steipete commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

WAL checkpoint execution is split between runtime maintenance and Doctor, and duplicate-agent recovery imports its engine operation from the command layer. This is the bounded checkpoint-ownership slice of the maintainer-requested storage cleanup.

User Impact

No user-visible behavior changes. Runtime checkpoints preserve partial completion, health observations, errors, reader diagnostics, and maintenance admission. Offline compaction and duplicate recovery still refuse a busy TRUNCATE checkpoint before proceeding.

Existing installations require no configuration changes, migration, schema bump, or operator action on update. Stored bytes, schemas, retention, durability, file identity, authority rechecks, FIFO ordering, uncertain-outcome handling, and MessagePort fences are unchanged. No plugin SDK or public API surface changes.

Why This Change Was Made

The existing sqlite-wal-checkpoint.ts owner now executes native checkpoints as well as interpreting their outcomes. Its retained runtime owner holds the supplied connection; Doctor and duplicate-agent recovery call its strict offline truncation operation. Callers retain connection lifetime, thread selection, maintenance custody, and transaction boundaries. This introduces no new main-thread database access or asynchronous transaction callback.

Deleted the command-owned checkpointDoctorSqliteFile export, the migration layer's reverse import from Doctor, caller-side runtime checkpoint execution/error handling, and redundant result assertions. The existing SQLite numeric module now owns the finite-number decoder shared by offline checkpoint and compaction reads. Runtime's stricter three-column decoder remains distinct. The version-gated NOOP freshness probe stays with the read cache; it does not perform checkpoint maintenance.

Production LOC: +49 / -51 / net -2. Tests: +0 / -0 / net 0. Docs: +7 / -0 / net +7. Assertion-safety baseline maintenance: +1 / -1 / net 0 (exact shrink from 3 to 1).

The broader identity cut was deliberately deferred: current physical identity coalesces aliases, binds first creation, detects replacement, and fences delayed receipts with an incarnation. Role plus agent ID alone cannot replace those relationships. Active broker/admission work also overlaps that cut. Current native backup, vector loading, and WAL policy already have specialized owners; a new aggregate facade would not remove competing ownership.

Evidence

Remote proof uses Blacksmith Testbox lease tbx_01m39ar17z70c3z6sbgf2n3gkm, run 35979386538. No tests, builds, typechecks, or Gateway processes ran on the local machine.

  • Focused storage, infrastructure, state preflight, and Doctor migration proof: pnpm test src/infra/sqlite-wal src/infra/sqlite-number src/infra/state-migrations.agent-owner-recovery.test.ts src/commands/doctor-sqlite-compact.test.ts src/commands/doctor-state-sqlite-compact.test.ts src/commands/doctor-database-preflight.test.ts src/commands/doctor-state-migrations.test.ts src/state/openclaw-database-preflight --maxWorkers=1 — four Vitest shards passed in 276.46 seconds. Dependencies were installed with pnpm install --frozen-lockfile first, and synchronized source hashes were verified.
  • No new or changed test files; existing entry-point coverage protects busy truncation, partial PASSIVE completion, reader retirement, cleanup, artifact preservation, and duplicate-owner recovery.
  • node scripts/check-changed.mjs --base d4748c6cc48f6c51ca391df123d1e5fb15418761 passed, including all 25 core-test typecheck groups, lint, dead-export and storage guards. pnpm docs:check-links checked 14,555 internal links with zero broken links. The runtime-tested checkpoint source, before the final guard annotation, has SHA-256 9f9849ca39475d6a5ff0a41e3964f9a26a0e54f2408eb2a7ce6858757199f193; the later rebase did not change any touched SQLite owner.
  • Both pnpm build runs passed on Node 24.19.0: baseline aeb32f35468d556c909fbacff3aca550cb01cdd9 in 19m 55.6s; candidate 00cdc251478b729f4e34bf27d188ab29024c0260 in 15m 34.4s. Both reported the same existing Control UI budget warnings (startup JS 363.0 KiB vs 362.6; isolated Mermaid 1555.8 KiB vs 960.0).
  • Live comparison passed through the real CLI and isolated Gateways: fresh candidate startup; a stopped origin/main seed copied to the same absolute state path; baseline and candidate restarts during 28 submitted agent/session/history RPCs; four acknowledged writes retained in both; 23 calls outstanding at shutdown and 20 expected interrupted reads in each. Global and agent SQLite backup/create, verify, restore, state/agent preflight, offline Doctor compaction, restored Gateway startup, session IDs, and transcript content all matched. Both preflights were exact; integrity was ok. No model inference or real user state was involved. The original lease completed during the baseline build, after the tests and changed-file gate had passed. Remaining build/live proof uses replacement Blacksmith lease tbx_01m39hvc7rmajd16tw9k3rsjmk, run 35991648641, with fresh exact checkouts.
  • Cross-tree references confirm the deleted export has no remaining callers. Node SQLite mutating wal_checkpoint execution is confined to the checkpoint owner; the read cache retains only its NOOP observation.
  • Deslop completed. Three completed Codex autoreviews are scoped-clean through P2, with no actionable findings (full refactor, erased this: void callback declarations, and the statement-scoped checkpoint-primitive annotation). OAuth attempts failed with refresh_token_reused; the requested configured direct-API route completed the review.

The first changed-file gate required shrinking the assertion-safety baseline after removing casts; that bookkeeping is included. The next gate found two unbound-method declarations; explicit this: void declarations fixed them, targeted lint passed, and the complete gate then passed. Raw Testbox sync retained stale Git metadata after local rebase, so final gates use exact baseline/candidate worktrees materialized from a Git bundle on the same lease. The local wrapper could not run against the available dependency installation. After a later Testbox bulk-sync timeout, commands used the same owned Testbox SSH route and verified task-only checkouts; neither source trust nor provider changed.

The first live probe reached successful baseline backup/restore, integrity, preflight, and restart readback, plus fresh and copied-state candidate boots. Its eight-call candidate burst completed before the shutdown-overlap assertion. All calls succeeded; the probe was corrected to maintain bounded queued load, with the original overlap and acknowledgement assertions retained, then both revisions were rerun.

The live entry points were pnpm openclaw gateway run --bind loopback --port <isolated-port> --auth token, gateway call for health, agents.list, sessions.create, sessions.patch, sessions.list, chat.inject, and chat.history, followed by backup sqlite create --global / --agent main --repository <private-repository> --json, backup sqlite verify <snapshot> --json, backup sqlite restore <snapshot> --target <fresh-file> --json, database preflight <restored-global> --json, database preflight-agent <restored-agent> --agent-id main --json, and doctor --state-sqlite compact --json. A task-owned process group joined every Gateway exit before copying or activating restored files. The same stored session ID and complete synthetic message objects were compared on every replay.

After the final rebase, the complete live comparison was repeated on the exact published head 15194f898f5853b67b899b017f8422cce9d2ed92 against its main baseline f60ad5926e2da357c942f64d4912e741b699c1b3. The supported pnpm openclaw --version wrapper built fresh CLI runtime artifacts in 1m 14.6s (baseline) and 1m 35.2s (candidate). Both fresh/copied-state boots, restart readbacks, global/agent snapshot round-trips, integrity checks, and exact preflights passed again. Each revision retained all four acknowledged writes with 23 outstanding calls at shutdown and 20 expected interrupted reads. This final proof includes the newly landed SQLite rollback change. Hosted CI is attached to head 15194f898f5853b67b899b017f8422cce9d2ed92 in run 36003761008, completed successfully: 163 jobs, no failures, and required openclaw/ci-gate checks are successful. GitHub initially created only a zero-job BuildFailed / startup_failure placeholder; one close/reopen after confirming mergeability regenerated attachment. The earlier attached run found that the relocated checkpoint statement needed its raw-SQLite primitive annotation. The annotation is bound to that exact call; no file-wide allowance or runtime behavior changed.

That earlier CI run also reported an execution-budget timeout in run-attempt.computer-use.test.ts (completed case; 10.013s elapsed). The fixture's five-second budget starts before connection preparation. On Blacksmith lease tbx_01m39qp7djp8mbepf1za68zw1k (run 36002055640), the exact failing merge 382eb95516356de3189ebcd528d20092b23bef29 was replayed through node --import tsx scripts/ci-run-node-test-shard.mts, using the original ordered 12-file group, OPENCLAW_VITEST_MAX_WORKERS=2, and the same forks/isolation policy: 111/111 tests passed in 130.73s wall. The same file alone passed 2/2 tests in 43.21s wall. No assertions, deadlines, or fixtures were changed. pnpm check:architecture then passed on the pushed 15194f898f5853b67b899b017f8422cce9d2ed92 head, including the Kysely guard; hosted CI independently passed the same architecture job. These replays establish non-reproduction, not a fix; the original timeout's cause remains unproven. Correlation and terminal-notification shape were also checked against the sibling Codex source.

Follow-ups

  • Coordinate logical database identity with the broker and lifecycle owners, retaining physical alias/replacement evidence inside the engine and preserving incognito ownership and uncertain-outcome custody.
  • Consolidate snapshot source selection only after accounting for the distinct live-handle, isolated-process, artifact-preserving, and cleanup contracts.
  • Route the remaining memory-forget vector-load bypass through its existing extension owner when its SDK boundary is addressed.
  • Treat backend-neutral fence transport as a separate admission change with live-authority and settlement proof.

All three task-owned Blacksmith leases are confirmed completed/stopped. The branch is clean and pushed. Non-required PR-context/auto-response automation was still queued at closeout; no required checks are pending. This PR remains open and ready for coordinator review, with auto-merge disabled; it has not been merged.

@steipete steipete closed this Sep 24, 2026
@steipete steipete reopened this Sep 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations size: S labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 24, 2026, 10:08 AM ET / 14:08 UTC (Revision 4).

ClawSweeper review

What this changes

The branch routes runtime and offline SQLite WAL checkpoints through one owner, shares numeric result decoding, and documents that ownership boundary.

Merge readiness

⛔ Blocked before merge - 3 items remain

Current main and the latest release still split checkpoint execution, so this PR remains useful. The pinned patch has no identified correctness defect and fixes the prior SQLite guard finding. The published-updater compatibility proof requested in the prior review remains outstanding.

Priority: P3
Reviewed head: 1fce6ccf6b9f2ae8e9329c57a213acb6186cf07c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is focused and its runtime parity evidence is strong, with one specific upgrade-proof gate remaining.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR reports real CLI and isolated Gateway runs through the changed runtime checkpoint, Doctor compaction, backup, and preflight paths on fresh and copied state, with matching retained writes, transcript content, and exact preflights. The pinned final commit adds a guard comment only. The separate published-updater upgrade cell remains outstanding; no stored-data model changes were introduced.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR reports real CLI and isolated Gateway runs through the changed runtime checkpoint, Doctor compaction, backup, and preflight paths on fresh and copied state, with matching retained writes, transcript content, and exact preflights. The pinned final commit adds a guard comment only. The separate published-updater upgrade cell remains outstanding; no stored-data model changes were introduced.
Evidence reviewed 9 items Introduced checkpoint ownership: The pinned merge-base-to-head diff moves native checkpoint execution into the existing checkpoint owner and changes runtime, Doctor, and duplicate-recovery callers.
Offline refusal remains: Doctor still checkpoints before and after compaction, while duplicate recovery retains its ownership and integrity checks before truncation.
Current main has not absorbed the change: Current main still executes runtime checkpoint SQL in the WAL caller and invokes the command-owned Doctor checkpoint from duplicate recovery.
Findings None None.
Security None None.

How this fits together

OpenClaw uses SQLite write-ahead logs for state databases. Runtime maintenance and offline Doctor or recovery operations checkpoint those logs, then use the result for health reporting or to decide whether offline work may proceed.

flowchart LR
  A[SQLite state database] --> B[Runtime maintenance]
  A --> C[Doctor and recovery]
  B --> D[WAL checkpoint owner]
  C --> D
  D --> E{Checkpoint result}
  E --> F[Health status]
  E --> G[Proceed or refuse offline work]
Loading

Before merge

  • Resolve merge risk (P1) - The published v2026.9.6 updater has not been shown activating this candidate on copied existing state; the installed updater runs before candidate-side Doctor and duplicate-agent recovery code, so the reported main-versus-candidate comparison does not cover that upgrade boundary.
  • Complete next step (P2) - Record the published v2026.9.6 updater activating this candidate on copied existing state, including Doctor compaction and duplicate-agent recovery outcomes.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source -2, Docs +7, Other 0. Total +5 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 5 49 51 -2
Tests 0 0 0 0
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 7 57 52 +5

Review metrics

None.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-sqlite-compact.ts, unknown-data-model-change: src/commands/doctor-sqlite-compact.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove the shipped update path (recommended)
    Run the published v2026.9.6 updater against copied existing state with this candidate and record activation plus Doctor and recovery outcomes.
  2. Pause for upgrade evidence
    Keep the PR open if the published updater and copied-state scenario cannot yet be exercised.

Technical review

Best possible solution:

Keep one SQLite checkpoint execution owner while demonstrating that a shipped updater can activate the candidate and preserve Doctor compaction and duplicate recovery on copied existing state.

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

Not applicable: this is an internal ownership refactor. The captured live comparison and existing SQLite entry-point tests address behavioral parity rather than a reported failing bug.

Is this the best way to solve the issue?

Yes: the existing WAL checkpoint owner is the narrowest home for native checkpoint execution, and the changed callers retain their admission and busy-refusal decisions. The shipped-updater upgrade boundary still needs proof.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 89f9250feaf7.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is a bounded internal ownership refactor with no claimed user-visible behavior change.
  • merge-risk: 🚨 compatibility: The PR touches Doctor and state recovery, but its otherwise strong proof does not exercise activation by the shipped updater.
  • 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 (live_output): The PR reports real CLI and isolated Gateway runs through the changed runtime checkpoint, Doctor compaction, backup, and preflight paths on fresh and copied state, with matching retained writes, transcript content, and exact preflights. The pinned final commit adds a guard comment only. The separate published-updater upgrade cell remains outstanding; no stored-data model changes were introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports real CLI and isolated Gateway runs through the changed runtime checkpoint, Doctor compaction, backup, and preflight paths on fresh and copied state, with matching retained writes, transcript content, and exact preflights. The pinned final commit adds a guard comment only. The separate published-updater upgrade cell remains outstanding; no stored-data model changes were introduced.

Evidence

What I checked:

  • Introduced checkpoint ownership: The pinned merge-base-to-head diff moves native checkpoint execution into the existing checkpoint owner and changes runtime, Doctor, and duplicate-recovery callers. (src/infra/sqlite-wal-checkpoint.ts:131, 1fce6ccf6b9f)
  • Offline refusal remains: Doctor still checkpoints before and after compaction, while duplicate recovery retains its ownership and integrity checks before truncation. (src/infra/state-migrations.agent-owner-recovery.ts:106, 1fce6ccf6b9f)
  • Current main has not absorbed the change: Current main still executes runtime checkpoint SQL in the WAL caller and invokes the command-owned Doctor checkpoint from duplicate recovery. (src/infra/sqlite-wal.ts:534, 89f9250feaf7)
  • Latest release remains split: The latest stated release, v2026.9.6, retains the command-owned truncation operation. (src/commands/doctor-sqlite-compact.ts:107, eb377ac59e6c)
  • Prior finding fixed at pinned head: GitHub's patch for the final commit adds the statement-scoped raw-SQLite primitive annotation; the prior ClawSweeper finding concerned that missing guard annotation. (src/infra/sqlite-wal-checkpoint.ts:132, 1fce6ccf6b9f)
  • Real-path comparison: The captured PR body reports isolated Gateway and CLI runs on fresh and copied state, matching acknowledged writes, restored transcript content, Doctor compaction, and exact state and agent preflights. That comparison used branch revision 15194f898f5853b67b899b017f8422cce9d2ed92; the final pinned commit adds only the guard comment. (15194f898f58)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Galin Iliev: 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.

  • Record a published v2026.9.6 updater-to-candidate run on copied existing state covering Doctor and duplicate-agent recovery.

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 (3 earlier review cycles)
  • reviewed 2026-09-24T12:25:40.935Z sha b315890 :: blocked before merge. :: [P2] Register the moved checkpoint call with the SQLite guard
  • reviewed 2026-09-24T13:35:21.733Z sha 15194f898f5853b67b899b017f8422cce9d2ed92 :: blocked before merge. :: none
  • reviewed 2026-09-24T13:54:22.758Z sha 15194f898f5853b67b899b017f8422cce9d2ed92 :: blocked before merge. :: none

@steipete
steipete force-pushed the hostneutral/storage-identity-0924 branch from b315890 to 15194f8 Compare September 24, 2026 13:09
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Sep 24, 2026
@steipete
steipete force-pushed the hostneutral/storage-identity-0924 branch from 15194f8 to 1fce6cc Compare September 24, 2026 14:00
@steipete
steipete merged commit 49a3fd8 into main Sep 24, 2026
213 checks passed
@steipete
steipete deleted the hostneutral/storage-identity-0924 branch September 24, 2026 14:35
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 24, 2026
* commit '9ccfc7d1bea21e34da48edbd54afd2e1be57db40': (89 commits)
  fix(exec): avoid gateway stalls during background task writes (#157177)
  test(cli): isolate preaction title setter state
  fix(test): synchronize Git backoff cancellation readiness (#157315)
  fix: validate Codex model references in Docker (#157175)
  fix(state): tolerate brief WAL coordinator contention (#157121)
  fix: unblock conversations after recovery preparation fails (#157214)
  test(telegram): avoid wall-clock pacing in HTTP conformance (#157281)
  fix: keep independent database work responsive under load (#157230)
  refactor(sqlite): centralize WAL checkpoint execution (#157263)
  improve(android): show tool outcomes in collapsed work (#156950)
  fix: remove tracked release scratch blocking source capture (#157308)
  test(update): remove legacy probe stream ordering race
  fix: preserve steering across reconnects and show queued input (#157135)
  fix(ui): keep typing focus when the GitHub reader opens (#157202)
  fix(ios): keep screenshot logs outside capture evidence
  test(codex): await startup teardown in lifecycle fixtures
  chore(ui): refresh control ui locales (#157311)
  refactor(memory): deslop memory plugins (#156867)
  refactor(test): share CLI diagnostics fixture setup (#157201)
  fix(release): retry notarization submit/wait on transport failures and name the resume command (#157116)
  ...
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 25, 2026
WAL checkpoint execution was split between runtime maintenance and Doctor, and duplicate-agent recovery imported its engine operation from the command layer.

Centralize native checkpoint execution in the existing sqlite-wal-checkpoint owner. Runtime maintenance retains its admission, health observations, partial-checkpoint reporting, and reader diagnostics. Doctor compaction and duplicate-agent recovery retain strict busy-truncation refusal and their surrounding integrity and authority checks.

Remove the Doctor-owned checkpoint export, the recovery layer's reverse import, caller-side checkpoint execution, and the duplicate finite-number parser. The read cache keeps its separate version-gated NOOP freshness probe.

This is an internal ownership change. Stored formats, schemas, retention, durability, configuration, SDK contracts, and update behavior are unchanged; existing installations need no migration or operator action.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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.

1 participant