Skip to content

fix(update): back up every database before migrations and restore them on rollback - #158163

Merged
steipete merged 5 commits into
mainfrom
upd/premigration-sqlite-snapshot-rollback
Sep 26, 2026
Merged

steipete merged 5 commits into
mainfrom
upd/premigration-sqlite-snapshot-rollback

Conversation

@steipete

@steipete steipete commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes rollback leaving the previous OpenClaw build unable to open databases migrated by a failed update, and verified backups missing consistent snapshots of unregistered agents.

Closes #157846
Refs #145169 #156917 #157107 #157077

Thanks @blyszcz, @mmartoccia, and @joshbunker for the reports.

User Impact

The repaired updater retains pre-migration shared and agent SQLite snapshots. A settled candidate failure before Gateway activation can restore them before restarting the previous version, provided recorded database generations match. Changed or unverifiable state is preserved with recovery guidance. Snapshots captured without confirming the Gateway stopped remain for manual recovery, even if it later exits.

openclaw backup create --verify --no-include-workspace consistently captures registered, configured custom, discovered default, historical, and linked agent database locations. Committed WAL content is included; --no-include-workspace excludes workspace files only.

Older-driver limitation: installing this candidate cannot retrofit an already-running 2026.9.1/2026.9.5 updater. Database rollback applies from the repaired driver onward. A target without complete Doctor write receipts cannot authorize restoration of changed databases; only an unchanged last-verified generation permits fallback. The archive coverage fix is directly usable in this version. No new public configuration, environment variables, CLI options, schemas, dependencies, stores, or backup formats.

Why This Change Was Made

The transaction retained package/configuration recovery data, while disposable canary database copies were discarded. Live Doctor migrations therefore outlasted package rollback. Archive capture also relied on the durable agent registry, missing consistent snapshots for unregistered agents even when raw files appeared in the archive.

Existing discovery, snapshot worker, and SQLite backup owners capture every affected database into <package-backup>.databases, using the archive's source-path layout. Snapshot digests are verified before displacement. The retained ledger/report records the directory and an aggregate inventory count/hash covering every database; per-file details remain bounded diagnostics. Snapshots and displaced files follow existing manual-recovery retention: they survive success or failure until the operator removes them after verification; no automatic expiry is introduced.

Write evidence reuses sqlite-file-generation plus the stable 96-byte WAL-index header, producing 64-character hash tokens and rejecting torn observations. Doctor compares the captured generation on admission under its existing maintenance owner and records the generation after draining its stores. These reads run in the existing isolated snapshot worker: closing a raw descriptor in Doctor's own process could otherwise release its SQLite fcntl locks. Restore compares the last verified generation after draining handles and acquiring file exclusions. A mismatch remains disqualifying for the run; diagnostics correctly identify the writer as unknown rather than attributing every change to a Gateway.

The restore owner holds Gateway maintenance and database exclusions, preserves current SQLite/WAL/SHM/journal families as <database>.migrated-<runId>, then atomically publishes each verified snapshot. Candidate-created databases are displaced and left absent. Publication is atomic per file, not across the whole family. Partial restoration, or subsequent package/configuration rollback refusal, leaves the Gateway stopped and retains both database generations for recovery. Candidate activation attempts and uncertain child termination remain ineligible.

Disk preflight reserves 2 × total family bytes + 3 × largest family + 64 MiB on the snapshot volume, plus total + largest + 64 MiB on each separate restore volume. Confirmed shortages and unsafe hardlinks refuse before migration; unavailable space measurements warn and attempt capture.

Production growth

The original 60-line compression remains incorporated. Production grew from the accepted +834 net to +1,378 for generation evidence, integration, the final refusal/Doctor-entry guards, schema-compatible package rollback, and the line-cap extraction; there is no cross-Doctor custody redesign.

Block Net LOC Why retained
Archive coverage/shared discovery +71 Covers unregistered and moved agents through one inventory owner.
Snapshot worker, inventory, disk checks +395 Captures consistent files and source generations with capacity checks on both destination types.
Generation reader/Doctor receipts +208 Detects unaccounted writes without disturbing Doctor's SQLite locks.
Restore owner +182 Drains captured lexical paths, then checks generations and digests under exclusions before preserving and replacing files.
CLI capture/receipt/restore adapter +203 Carries eligibility, sticky refusals, evidence, and recovery diagnostics.
Transaction/finalization/native integration +305 Carries receipts through every Doctor path and settles activation/Windows custody safely.
Ledger/report retention +14 Preserves aggregate evidence and recovery locations through diagnostic compaction.

git diff origin/main...HEAD --numstat totals: production +1562/−184, net +1378; tests/support +1751/−59, net +1692; docs +99/−21, net +78.

Evidence

Rebase and line-cap follow-up — d569ba145e8baf2a2b2f5c29e711e7f7f6199ae7: Rebased linearly onto main 88d655629ca250275d91ac8b015fc5f6bd21b63f. The worker conflict preserves main's #158317 snapshot/inventory progress streaming together with the reviewed database-backup and database-generation modes. Main also owns the Doctor runtime-mock export fix through #157780, so the redundant branch hunk was dropped. Range-diff confirmed the other three reviewed commits replayed unchanged.

The combined sources exceeded the 700-line gate: update-command-execution.ts had 709 counted lines and update-candidate-state.ts had 712. Unchanged inspection cleanup moved to the existing process-settlement sibling; CLI candidate validation/progress moved to a dedicated sibling that preserves the existing import boundary, original promise, callback-time option reads, and post-await authority check. No runtime policy, test assertion, baseline, suppression, schema, or option changed. This required extraction adds production +76/−51, net +25; tests/support and docs 0/0. Fresh scoped Codex review was clean at P0–P2.

The final reviewed tree c1abf07ccaaa067c56244e36b2d57c39a1d134a7 passed the line-cap gate and both import-cycle checks (0 cycles). All 83 selected touched/importer files ran three times: 81 passed, two existing platform-only files skipped; 1,789 tests passed and 10 existing platform cases skipped each time, in 743.808 / 672.862 / 663.892 s. Full node scripts/check-changed.mjs passed in 1704.081 s, including all 25 core-test type graphs, core/test-root types, lint, dead exports, and repository guards. Final Testbox, lease tbx_01m3dkw8trzn37k3a3hht9z6g5, exit 0, stopped successfully. The known original-service suite used 146.861 s across its existing cases; its longest case was 7.686 s. No new tests or skips were added.

Before extraction, the mechanically rebased tree passed its 36 selected suites three times (850 passing tests, six platform skips, 490.403 / 390.530 / 366.648 s) before the line-cap failure stopped check-changed: rebase Testbox, lease tbx_01m3dhfnv9m0p42723bbs0r3r4. Two earlier proof-harness attempts stopped before tests because they compared Crabbox's transport commit with the source commit; the corrected harness verifies the source tree and changed-file digests. All owned leases stopped. Auto-merge remains off.

Post-core recovery CI follow-up — 5828ca4e613c944d0d1e631d00076d1981fa63bf: This was an owned regression. The unchanged src/cli/update-cli.post-core-recovery.test.ts passed all 11 cases on clean main 88e58c41dc657a7563fd10458b2d429ee80a6f50 (25.220 s), while head 03bbc34708c7c527ae93990821b7fb62ba5797f8 failed both Windows variants at line 181, expected 0 to be greater than 0 (28.154 s). The count is Gateway activation commands. Attribution Testbox, lease tbx_01m3d4sb9gsxkf4867ghgd77x3.

Finalization unnecessarily attempted database restoration during schema-neutral package rollback. The updater's own ledger writes invalidated the snapshot fingerprint, suppressing the previous Gateway's restart. The existing rollback owner now checks schema compatibility first and restores snapshots only when that compatibility check requires it; compatible databases remain untouched. Sticky outside-write refusals, candidate-start eligibility, generation checks, and partial-restore pending recovery remain intact. No assertion was changed. Follow-up git diff --numstat: production +36/−28, net +8; tests/support 0/0; docs 0/0. The added block places the restore decision beside the existing schema guard and preserves the single file-restore owner.

Both pnpm check:import-cycles and pnpm check:madge-import-cycles passed with 0 cycles. All 28 affected/direct/barrel importer files, 2,332 tests, passed three times in 679.909 / 581.857 / 613.896 s. Full node scripts/check-changed.mjs passed in 1920.588 s, including all 25 core-test type graphs, core/test-root types, lint, dead exports, and repository guards. Verification Testbox, lease tbx_01m3d5t64x4vk2rf2te2je7a8d, exit 0, stopped successfully. The provider reported a portal-sync timeout after successful completion and lease cleanup; the proof command succeeded. Fresh scoped Codex review was clean at P0–P2. Auto-merge remains off.

The post-core regression file used 10.834 s test time in the first remote pass. The already-documented original-service suite used 159.573 s across 67 cases, longest 7.627 s (split-root failure: package-root-missing); its existing process compositions remain unchanged.

Topology CI follow-up — 03bbc34708c7c527ae93990821b7fb62ba5797f8: Madge includes type imports, so package Doctor's import of receipt accounting from capture/restore orchestration closed the database-backup → execution.types → package cycle. The unchanged recorder now has one leaf owner, update-command-database-receipts.ts, using the existing receipt contract; both callers moved and the old export was removed. Net production change: +2 lines; no lazy import, suppression, dependency, schema, or behavior change.

The original source reproduced exactly 1 Madge cycle in 47.594 s. Both pnpm check:import-cycles and pnpm check:madge-import-cycles then reported 0 cycles. All 39 direct/barrel importer files, 781 tests, passed three times in 586.04 / 612.62 / 490.65 s on Testbox, lease tbx_01m3ch7xv7ny1wk4jzbt8kx7f9. Fresh scoped Codex review was clean at P0–P2. A session restart interrupted the following changed-file gate; only that incomplete gate was resumed. Full node scripts/check-changed.mjs passed in 1899.994 s, wrapper 2031.267 s, exit 0, on Testbox, lease tbx_01m3ctzrew6gsk03zmfxn3xg06. All 25 core-test type graphs, test-root/core types, lint, dead exports, and repository guards passed. Both proof runs used the exact committed source tree; the final lease stopped successfully.

Regression coverage exercises archive round-trips, mutable-update/package-swap owners, spawned Doctors, database restoration, write mismatches, missing receipts, and handle exclusions. The online-writer regression loses a post-capture row before repair and preserves it afterward. Windows interruption improved from a 120.038 s timeout to 3.195 s passing; negative controls fail immediately on leaked signal listeners.

The branch review also caught directory-linked handles surviving file replacement because discovery used canonical paths and caches used lexical paths. Its regression failed with the original handle still open (1.075 s); capture now retains those spellings and the single restore owner drains them. Real discovery→capture→restore passes both ordinary and linked-path cases.

The importer replay also exposed an incomplete shared Doctor runtime mock from an earlier change: 35 E2E cases stopped at a missing createNonExitingRuntime export. The fixture now preserves actual exports and overrides only defaultRuntime; its original assertions remain intact.

Removing only the three-line finalization refusal guard makes the schema-neutral-write regression fail in 3.763 s: active package 2.0.0 is incorrectly rolled back to 1.0.0 despite recorded database write refusal.

The real npm 2026.9.5 receipt-backed cell passed 17/21 → 19/23 → 17/21, preserving session facts; the unchanged old Gateway returned HTTP 200 on /healthz and /readyz. The actual built Doctor produced an unchanged: true receipt for both databases. The harness preserved it, forced exit 71, and the package-Doctor/guarded-restore path accepted it. Snapshot 5.707 s, Doctor 9.857 s, restore 76 ms; remote command 720.393 s, including successful build 605.695 s.

This uses native executor/delegated Doctor and capture/restore owners, not the complete updater/package swap or systemd. Config is separately restored; the Gateway runs foreground. The separate managed-flow regressions cover finalization refusal.

A successful package-retirement proof used the real capture, transaction completion, and ledger owners: package cleanup removed the old package, both SQLite snapshots retained their exact sizes/digests, and reopening history preserved succeeded plus the snapshot directory and digests. Proof 10.881 s, capture 4.502 s, cleanup 19 ms; wrapper 94.289 s, exit 0. This verifies successful cleanup and persistent receipts, not Gateway activation.

After the linked-path repair, the final production cohort passed 521 tests in 22 files three times, with runner walls 358.72 / 230.50 / 210.63 s on Testbox, lease tbx_01m3cd20b9a3ttfwzz1fxrrx79. This includes the existing package-lifecycle regression: a pre-Doctor shim failure now restores the old package through ordinary recovery without replacing databases.

The shared-fixture replay passed 116 tests three times across 13 files (12 passed, one existing platform skip), followed by its Doctor type graph (50.543 s). The actual Node-provisioning live test also passed (4.814 s test, 11.895 s phase), installing and reusing Node 24.19.0 under isolated state and releasing both leases. Testbox, lease tbx_01m3ca8n6g3pgjkqx5tfrzkdkf: wrapper 1546.871 s, exit 0.

  • Pre-topology node scripts/check-changed.mjs: exit 0, 2048.631 s, including all 25 core test type graphs, core/test-root types, lint, dead exports, and repository guards. The wrapper completed in 2992.786 s, exit 0, and stopped its lease. Its captured source tree exactly matched the pre-topology head a804f6bfdfbe1054646c41533b5e2b06001eb43e. The shared test fixture also has separate three-pass consumer proof.
  • Importer coverage: 413/413 files observed, 407 passed, five existing platform-skipped files, one known unrelated failure owned by fix(ci): run policy checks for affected source changes #157902. Original manifest order was retained across continuations; repaired failures were verified, not retried unchanged for green. Importer Testbox, lease tbx_01m3c3zg2ng1zcmancwta2x52m. Native Windows/macOS, case-insensitive-volume, and Bun guards account for the existing skipped cases; no skips were added.
  • Pre-topology full branch Codex --mode branch --base origin/main review: scoped-clean at P0–P2, four passes with no accepted/actionable findings, on a804f6bfdfbe1054646c41533b5e2b06001eb43e.
Changed-test costs: one file, one worker

pnpm test <file> --maxWorkers=1, Linux Testbox, lease tbx_01m3c62f259q2fs9bw9kbdnkfr: all 21 original file runs passed, 606.075 s summed command wall including setup. The restore row shows its subsequent macOS remeasurement. Measured before the final three-line pre-Doctor gating change; the later linked-path restore variant is separately measured below.

Test file Wall seconds
update-cli.windows-recovery.test.ts 33.785
update-command-cleanup-recovery.test.ts 20.084
update-command-database-rollback.test.ts 47.461
update-command-migrated.test.ts 89.135
update-command-native-recovery.test.ts 16.200
update-command-pending-recovery.test.ts 38.570
update-command-post-update.test.ts 37.538
update-command-retained-restart.test.ts 21.477
update-command-service-command.test.ts 16.824
backup-verify-completeness.test.ts 26.852
doctor-maintenance.settlement.test.ts 18.276
doctor-update-schema-guard.test.ts 59.216
doctor-health.migration-refusal.test.ts 30.353
backup-create.test.ts 36.115
package-update-swap.bounds.test.ts 17.021
sqlite-readonly-worker.model-auth.test.ts 33.324
update-database-backup.test.ts 17.642
update-database-restore.test.ts 27.952 (updated locally)
update-doctor-result.test.ts 2.165
update-migrated-finalize.worker.test.ts 2.282
update-run-capture-receipts.test.ts 14.840

The linked-path restore regression subsequently passed all six cases through real capture/restore locally: 14.440 s summed test time, 34.77 s Vitest wall (including 17.612 s compiler preparation). The updated single-worker command pnpm test src/infra/update-database-restore.test.ts --maxWorkers=1 passed in 27.952 s wall on macOS (25.39 s Vitest wall); the final Testbox replay is recorded above.

Testbox Actions links can show cancellation after lease cleanup; the command exit codes above are the validation results.

Known gaps / waived test costs

Older drivers cannot be retrofitted. Continuous lifecycle custody across Doctor subprocesses remains deferred to Peter's decision in #156917; this change uses write receipts within existing custody intervals. Raw SQLite clients bypassing OpenClaw coordination are outside the guarantee during Doctor’s admitted interval; the existing maintenance owners exclude supported Gateway/store writers, while fingerprints detect writes between custody intervals. Fingerprints are conservative: later bookkeeping or checkpoint cleanup can also require manual recovery; automatic restoration never rebases over unaccounted changes.

  • ci-changed-node-test-plan.test.ts: 262.806 s (earlier waived 238.430 s), longest “keeps boundary coverage when only a deferred proof helper changes” 42.381 s (earlier 35.300 s); repeated repository graph/native-source and inventory planning.
  • package-acceptance-workflow.test.ts: 165.782 s (earlier waived 145.412 s), longest “bounds the complete CLI record for 256 real planner groups” 19.456 s (earlier 20.118 s); repeated Git/workflow admission and shell probes. Its unrelated exact-command assertion was fixed by fix(ci): run policy checks for affected source changes #157902 (98313da6cab4).
  • ci-node-test-plan.test.ts: 132.849 s/199 cases, longest “keeps precise RunsOn targets and their canonical child policies” 16.685 s; repeated full-universe hybrid/RunsOn planning before filtering two targets, a separate performance follow-up.

The existing service-custody.test.ts cooperative capability-probe case (startup=31000) passed in 31.313 s; its fixture deliberately waits 31 seconds before startup. It remains unchanged.

Additional pre-existing composition costs: doctor-config-flow.legacy-composition.test.ts, July fixture with local model disabled, 32.422 s (four sequential built CLI processes: validate, Doctor, validate, Doctor); doctor-config-preflight.refusal.process.test.ts, shipped 9.2 valid 36.981 s and managed-v1 37.086 s, and managed-pnpm 40.193 s (real private Doctor rehearsal/post-core processes, with compile caching disabled to match that driver). The new generation-capture factory returns immediately without input in these cases. Earlier measurements for those 9.2 cases were 28.041 / 23.627 / 22.931 s. The managed fixture also copies dist/extensions only to delete it immediately; skipping that copy and splitting the process contract are performance follow-ups.

In the broader importer run, summed serial testcase time was 212.204 s for doctor-config-preflight.refusal.process.test.ts (17 cases), 166.941 s for doctor-config-flow.legacy-composition.test.ts (26 cases), and 174.220 s for update-command-original-service.test.ts (67 cases). These are testcase sums, not file wall times; the existing repeated process/private-runtime compositions own those costs.

extensions/matrix/doctor-contract-api.account-state.test.ts passed its single repair case in 34.302 / 32.297 / 30.037 s: a cold source Doctor CLI with compile cache disabled and three real sync-store lifecycles/drains. Moving its source-specific loader contract to a shared built-runtime fixture is a performance follow-up.

@clawsweeper

clawsweeper Bot commented Sep 25, 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 gateway Gateway runtime cli CLI command changes commands Command implementations size: XL labels Sep 25, 2026
@steipete
steipete marked this pull request as ready for review September 25, 2026 14:38
@steipete
steipete enabled auto-merge (squash) September 25, 2026 14:45
@steipete
steipete disabled auto-merge September 25, 2026 14:45
@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 25, 2026, 10:22 PM ET / September 26, 2026, 02:22 UTC (Revision 5).

ClawSweeper review

What this changes

The branch adds retained SQLite snapshots and guarded restoration to package-update rollback, includes unregistered agent databases in verified backups, and documents recovery limits.

Regression provenance

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

Merge readiness

⛔ Blocked before merge - 7 items remain

Keep this PR open. Current main still lacks the requested rollback and archive coverage, but unconditional database capture can block an otherwise compatible package update. Snapshot retention and full upgrade compatibility also remain unresolved.

Priority: P0
Reviewed head: d569ba145e8baf2a2b2f5c29e711e7f7f6199ae7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The branch has substantial direct recovery proof and focused validation, while an introduced update-admission regression and unresolved storage compatibility keep it from merge readiness.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): A real npm 2026.9.5 state and agent database passed through the built candidate Doctor, an injected failure, guarded restore, and an old Gateway serving health endpoints with session facts retained. That terminal trace supports the changed recovery owner, but it omits complete package swap and managed-service activation; existing-state upgrade compatibility through the full published-driver path remains unverified.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): A real npm 2026.9.5 state and agent database passed through the built candidate Doctor, an injected failure, guarded restore, and an old Gateway serving health endpoints with session facts retained. That terminal trace supports the changed recovery owner, but it omits complete package swap and managed-service activation; existing-state upgrade compatibility through the full published-driver path remains unverified.
Evidence reviewed 9 items Unconditional capture: The introduced package-transaction callback captures databases whenever an original update run exists; it does not first establish that Doctor will migrate them.
Admission refusal: The new backup owner rejects measured snapshot-space shortages and hard-linked database files before capture, making the unconditional callback an update failure path.
Transaction ordering: Package swap awaits the callback after activation preparation and before package replacement and post-install Doctor, so capture refusal prevents that update from proceeding.
Findings 1 actionable finding [P1] Keep compatible updates runnable without full snapshot capacity
Security None None.

How this fits together

The installed updater stages a new OpenClaw package and runs Doctor, which can migrate shared and per-agent SQLite databases. If the update fails, recovery decides whether it can restore those databases and restart the previous Gateway; the backup CLI also archives them independently.

flowchart LR
 A[Package update] --> B[Installed updater]
 B --> C[Database inventory]
 C --> D[SQLite snapshots]
 B --> E[Candidate Doctor]
 E --> F[Write evidence]
 D --> G[Rollback decision]
 F --> G
 G --> H[Gateway restart]
Loading

Decision needed

Question Recommendation
After a package update succeeds and its Gateway is verified, should this PR retain full database snapshots indefinitely or retire them? Retire verified successes: Remove snapshots only after successful final verification while retaining failed and uncertain recovery artifacts.

Why: The PR changes the storage and recovery-retention contract, and its stated manual-retention choice has no separate recorded maintainer acceptance.

Before merge

  • Keep compatible updates runnable without full snapshot capacity (P1) - This unconditional capture runs for every package transaction before Doctor. Capture then rejects measured disk shortages and hard-linked database files, so a package update with compatible databases fails before any migration even though the existing path could proceed. Gate mandatory capture on migration risk or preserve a verified compatible-update path, with an admission regression.
  • Resolve merge risk (P1) - Mandatory capture can stop a schema-compatible package update on measured disk shortage or a hard-linked database, even when no database migration is needed.
  • Resolve merge risk (P1) - Successful updates retain a full snapshot of every discovered database until manual removal; the resulting storage lifetime and cleanup responsibility have not received recorded acceptance.
  • Resolve merge risk (P1) - The real recovery cell exercises Doctor and guarded restore, but a complete published-updater-to-candidate package-swap and final managed-Gateway recovery cell is not shown.
  • Complete next step (P2) - Repair compatible-update capture admission, record the snapshot-retention decision, and prove the complete published-updater recovery path before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P1] Keep compatible updates runnable without full snapshot capacity — src/cli/update-cli/update-command-execution.ts:184-189
Agent review details

Security

None.

PR surface

Source +1378, Tests +1692, Docs +78. Total +3148 across 75 files.

View PR surface stats
Area Files Added Removed Net
Source 48 1562 184 +1378
Tests 24 1751 59 +1692
Docs 3 99 21 +78
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 75 3412 264 +3148

Review metrics

Metric Value Why it matters
Production versus test growth production +1,378 net LOC; tests/support +1,692 net LOC The PR body attributes production growth to generation evidence, restoration, and lifecycle integration; maintainers should weigh that cost against the recovery contract.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/cli/update-cli/update-command-database-receipts.ts, migration/backfill/repair: src/cli/update-cli/update-command-fresh-doctor.ts, migration/backfill/repair: src/commands/doctor-maintenance-types.ts, migration/backfill/repair: src/commands/doctor-maintenance.ts, migration/backfill/repair: src/flows/doctor-health.ts, migration/backfill/repair: src/infra/update-run-codec.ts, and 3 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #157846
Summary: This PR is the candidate fix for the linked upgrade rollback report; the merged concurrent-snapshot repair supplies an adjacent primitive but does not implement rollback restoration.

Members:

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

Merge-risk options

Maintainer options:

  1. Repair admission and settle retention (recommended)
    Preserve compatible updates when exhaustive capture cannot run, record the successful-snapshot retention choice, and verify a complete upgrade recovery path.
  2. Accept mandatory capture
    Explicitly accept update refusal on constrained installations and indefinite snapshot storage, with operator-facing capacity and cleanup guidance.
  3. Hold the rollout
    Pause this branch if the capture admission and recovery-retention tradeoffs cannot be resolved safely for existing installations.

Technical review

Best possible solution:

Keep pre-migration restoration for updates that can change database compatibility, preserve a runnable path for verified compatible updates on constrained disks, and give operators a visible Fix or Doctor recovery action when rollback is refused.

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

Yes for the admission regression: the introduced callback always reaches capture, and the new capacity and hard-link checks reject before Doctor. This review established that path from source and the focused tests, without executing the PR.

Is this the best way to solve the issue?

No, not yet. The restoration uses existing update and snapshot owners, but capture needs an admission rule that preserves verified compatible updates.

Full review comments:

  • [P1] Keep compatible updates runnable without full snapshot capacity — src/cli/update-cli/update-command-execution.ts:184-189
    This unconditional capture runs for every package transaction before Doctor. Capture then rejects measured disk shortages and hard-linked database files, so a package update with compatible databases fails before any migration even though the existing path could proceed. Gate mandatory capture on migration risk or preserve a verified compatible-update path, with an admission regression.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.89

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. A real npm 2026.9.5 state and agent database passed through the built candidate Doctor, an injected failure, guarded restore, and an old Gateway serving health endpoints with session facts retained. That terminal trace supports the changed recovery owner, but it omits complete package swap and managed-service activation; existing-state upgrade compatibility through the full published-driver path remains unverified.

Label justifications:

  • P0: Failed updates can strand an older Gateway on newer SQLite schemas, making the core runtime unusable until recovery.
  • merge-risk: 🚨 compatibility: The new mandatory capture gate can reject package updates that previously proceeded with compatible databases.
  • merge-risk: 🚨 session-state: The patch replaces persisted shared and per-agent SQLite files during rollback and retains migrated generations for recovery.
  • merge-risk: 🚨 availability: Snapshot refusal or uncertain restoration can leave a managed Gateway stopped even when the package update path would otherwise complete.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): A real npm 2026.9.5 state and agent database passed through the built candidate Doctor, an injected failure, guarded restore, and an old Gateway serving health endpoints with session facts retained. That terminal trace supports the changed recovery owner, but it omits complete package swap and managed-service activation; existing-state upgrade compatibility through the full published-driver path remains unverified.
  • proof: sufficient: Contributor real behavior proof is sufficient. A real npm 2026.9.5 state and agent database passed through the built candidate Doctor, an injected failure, guarded restore, and an old Gateway serving health endpoints with session facts retained. That terminal trace supports the changed recovery owner, but it omits complete package swap and managed-service activation; existing-state upgrade compatibility through the full published-driver path remains unverified.

Evidence

What I checked:

  • Unconditional capture: The introduced package-transaction callback captures databases whenever an original update run exists; it does not first establish that Doctor will migrate them. (src/cli/update-cli/update-command-execution.ts:184, d569ba145e8b)
  • Admission refusal: The new backup owner rejects measured snapshot-space shortages and hard-linked database files before capture, making the unconditional callback an update failure path. (src/infra/update-database-backup.ts:95, d569ba145e8b)
  • Transaction ordering: Package swap awaits the callback after activation preparation and before package replacement and post-install Doctor, so capture refusal prevents that update from proceeding. (src/infra/package-update-swap.ts:394, d569ba145e8b)
  • Prior finding remains: The previous ClawSweeper review identified the compatible-update capacity regression. The pinned head still contains its unconditional trigger; the later rollback correction changes restoration, not capture admission. (src/cli/update-cli/update-command-execution.ts:185, d569ba145e8b)
  • Current-main necessity: Fetched main retains the pre-PR rollback refusal and has no update-database-backup owner. Its backup snapshot plan relies on registered agents, so the central requested work is not already on main. (src/cli/update-cli/update-command-rollback.ts:299, a410b4d0fb53)
  • Real recovery evidence and limit: The PR body matches the supplied SHA-256. It reports a real npm 2026.9.5 database/Doctor/restore cell that returned schemas 17/21 and an old Gateway serving health endpoints after forced failure. The author expressly limits that cell: it did not run the complete updater/package swap or systemd flow.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: 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.

  • Preserve schema-compatible package updates when full snapshot capture cannot run, with a focused admission regression.
  • Show a redacted published-updater-to-candidate failure and recovery run through package swap and final Gateway state.
  • Record the successful-update snapshot retention decision.

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-09-25T14:47:59.925Z sha a804f6b :: blocked before merge. :: [P1] Keep compatible package updates runnable without full snapshot capacity
  • reviewed 2026-09-25T18:34:49.011Z sha 03bbc34 :: blocked before merge. :: [P1] Keep compatible package updates runnable without full snapshot capacity
  • reviewed 2026-09-25T22:20:23.287Z sha 5828ca4 :: blocked before merge. :: [P1] Keep schema-compatible updates runnable without full snapshot capacity
  • reviewed 2026-09-26T01:37:51.458Z sha 5828ca4 :: blocked before merge. :: [P1] Keep compatible updates runnable without full snapshot capacity

@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 25, 2026
@steipete
steipete enabled auto-merge (squash) September 25, 2026 18:39
@steipete
steipete disabled auto-merge September 25, 2026 20:31
@steipete
steipete enabled auto-merge (squash) September 26, 2026 00:11
@steipete
steipete disabled auto-merge September 26, 2026 00:11
Include unregistered agent databases in consistent backups and retain database
snapshots with package recovery artifacts before Doctor migrations. Restore only
when recorded write fingerprints still match, preserving displaced migrated
files and refusing silent rollback over unaccounted writes.

Keep pre-Doctor install failures on the existing package recovery path.

Closes #157846
Refs #145169 #156917 #157107 #157077
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 26, 2026
roboclaw-bot added a commit that referenced this pull request Sep 27, 2026
Backport the coupled all-database snapshot and pre-start rollback repairs:
- #158317 / 979a8be
- #158163 / d780fdc
Source credit: Peter Steinberger (steipete).

Capture complete source-preserving online snapshots with continuous Gateway
exclusion for automatic restoration eligibility. Account for Doctor writes
through exact native transaction images, ordered worker/heartbeat receipts
and persistent metadata, including default_cache_size. Unknown observations
refuse restoration rather than adopt foreign generations.

Retain native source custody through displacement and separate published
postimage custody through settlement. Missing names use creator-owned locked
file capabilities and no-clobber publication. Published handles settle before
absence-last handback. Preserve foreign replacements/contents, cleanup errors,
WAL publication, live authority and the target restart attempted-start guard.

Review findings were reproduced at actual boundaries and corrected. The final
metadata proof passes 36 Doctor/image cases plus a real rollback positive;
prior 29 current-custody cases and earlier scoped evidence remain retained,
not relabeled as rerun. Production/focused types, lint, format and frozen
eb377ac ratchets pass. Final independent P0-P2 review passes both partitions
on exact tree a16411a.

Linux/Node source proof is not installed-driver or full platform qualification.
Windows/Bun restoration remains explicitly manual when native custody is not
supported. No schema/dependency/version changes or guard/budget waivers.
This component is committed locally only; parent composition and its bound
service-membership fixture patch are still pending. Public size-policy hold
remains active.

Implementation:
https://team.openclaw.ai/chat/roboclaw/dashboard/6dde6dee-8e3f-4d43-aada-2c1cf14afa4e
Persistent metadata correction:
https://team.openclaw.ai/chat/roboclaw/subagent/609bf089-d2c0-499e-8f9f-74c2615d43ac
Original discussion, handback correction and final review:
https://team.openclaw.ai/chat/roboclaw/dashboard/db4d78ac-b19b-4f64-adfb-0ca7973a62e4

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vyctorbrzezowski <[email protected]>
Co-authored-by: steipete <[email protected]>
Co-authored-by: jalehman <[email protected]>
roboclaw-bot added a commit that referenced this pull request Sep 27, 2026
Merge the reviewed coupled snapshot/rollback component into the prepared
release branch, preserving the existing service, Doctor, APFS, vendor and
already-landed canonical release repairs. Source credit remains Peter
Steinberger for #158317/#158163; all inherited contributor credits remain.

Apply the service-membership fixture only after matching its recorded exact
preimage and verify its postimage. Repair the extracted wrapper closure with
the three existing transaction/image/receipt modules required by the new
SQLite worker flow.

Bind maintenance exclusion to a private live owner: foreign late delegates
and unowned schema work refuse while valid same-owner delegates retain the
fence through release and cleanup. The quarantine inventory review concern
was refuted by its existing producer filter and real create/verify/restore
WAL coverage, with a discriminating filter-removal control. No redundant
backup production filter or schema change was added.

Composed interaction proof: 81 tests across nine files plus two extracted
wrapper checks pass. The final ownership repair passes 108 unique tests in
11 owner/sibling files, production/exact-owner types, lint, formatting and
all frozen eb377ac ratchets. Earlier independent source proof remains
retained rather than relabeled as rerun. Final independent P0-P2 review
completed all five partitions with zero findings on exact tree
d963fed; all 132 file bindings match.

This is local preparation, not canonical release publication or installed
platform qualification. Version remains 2026.9.6 and fs-safe remains0.18.1.
The separately accepted dependency PR and the public size-policy decision
remain external gates. No guard, assertion, lease, timeout or baseline waiver.

## Work sessions

- Original discussion, review and final integration:
  https://team.openclaw.ai/chat/roboclaw/dashboard/db4d78ac-b19b-4f64-adfb-0ca7973a62e4
- Final ownership correction and verification:
  https://team.openclaw.ai/chat/roboclaw/subagent/2a4b17b6-c5cf-4278-b582-debae9da3826
- Database implementation:
  https://team.openclaw.ai/chat/roboclaw/dashboard/6dde6dee-8e3f-4d43-aada-2c1cf14afa4e
- Persistent metadata correction:
  https://team.openclaw.ai/chat/roboclaw/subagent/609bf089-d2c0-499e-8f9f-74c2615d43ac

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vyctorbrzezowski <[email protected]>
Co-authored-by: steipete <[email protected]>
Co-authored-by: jalehman <[email protected]>
steipete added a commit that referenced this pull request Oct 1, 2026
The update database generation check compared physical fingerprints, so a SQLite checkpoint that merely folded already-captured WAL frames into the main file (on Windows, triggered by the exclusive removal probe) was treated as a later write and rollback was refused with "Databases changed after snapshot capture"; the Windows lifecycle test failed in isolation. The check now compares committed pages plus retained WAL commit evidence: checkpoint-only transitions and exact reversals that leave byte-identical content are admitted (identical content cannot lose data on restore; recorded at the comparer with a regression), while any newer data is still refused. The fixture's unsafe in-process snapshot mock is removed.

Refs #158163
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…162599)

The update database generation check compared physical fingerprints, so a SQLite checkpoint that merely folded already-captured WAL frames into the main file (on Windows, triggered by the exclusive removal probe) was treated as a later write and rollback was refused with "Databases changed after snapshot capture"; the Windows lifecycle test failed in isolation. The check now compares committed pages plus retained WAL commit evidence: checkpoint-only transitions and exact reversals that leave byte-identical content are admitted (identical content cannot lose data on restore; recorded at the comparer with a regression), while any newer data is still refused. The fixture's unsafe in-process snapshot mock is removed.

Refs openclaw#158163
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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]: Upgrade migrates state and agent databases irreversibly before the new build is verified, leaving no downgrade path

1 participant