Skip to content

fix(backup): preserve audit capture across slow snapshots - #130962

Merged
obviyus merged 6 commits into
openclaw:mainfrom
gaoanze888:gaoanze888/backup-legacy-audit-lease-scope
Sep 3, 2026
Merged

obviyus merged 6 commits into
openclaw:mainfrom
gaoanze888:gaoanze888/backup-legacy-audit-lease-scope

Conversation

@gaoanze888

@gaoanze888 gaoanze888 commented Aug 27, 2026 •

Copy link
Copy Markdown

Closes #130761

What Problem This Solves

openclaw backup create held the 60-second legacy-audit migration lease while it verified, copied, compacted, and published SQLite snapshots. A slow snapshot could outlive the lease and fail the backup even when the Gateway was stopped.

Releasing the lease without a consistency check created a second bug: Doctor could migrate a captured legacy file into SQLite between the file and database snapshots, so a restored backup imported the same audit record twice.

Why This Change Was Made

Backup now treats the legacy filesystem and SQLite rows as one optimistic capture interval:

  1. Capture sanitized legacy files and filesystem/database witnesses under the short migration lease.
  2. Release the lease before the potentially long SQLite snapshot.
  3. Verify the staged SQLite snapshot still matches the first database witness.
  4. Reacquire the lease and compare a second filesystem/database witness.
  5. Delete and retry the complete staged attempt on drift.
  6. Fail closed after three changing attempts without publishing an archive.

The normal no-legacy path keeps its fast snapshot flow. The lease duration, database schema, import keys, retention, and restore format do not change.

User Impact

Verified backups can complete after slow SQLite work without publishing a cross-store state that duplicates restored audit records.

Evidence

  • Current-main real CLI red: a proof-only 61.5-second stall at the real node:sqlite.backup entry exits with the reported lost-lease error.
  • Exact-head real CLI green: the same backup create --no-include-workspace --verify --json command exits 0 with verified: true.
  • Checked-in CLI red/green: the registered entry-point regression fails on current main with the exact error and passes on this head.
  • Restore green: the owner-boundary regression restores the archive, runs the audit importer twice, and retains exactly one audit record.
  • Focused exact-head tests: 144 passed, 2 skipped.
  • Focused format, lint, lease, storage, and schema guards pass.

Change Size

  • Production: +203/-38, net +165.
  • Tests: +259/-7, net +252.

The production growth records and verifies one cross-store consistency fact. It replaces the unsafe alternatives of holding the short lease across slow SQLite work or trusting restore-time deduplication across different legacy generations.

AI Assistance

AI-assisted repair and review. Maintainer proof used the real backup and restore command paths.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@gaoanze888

This comment was marked as spam.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 3, 2026, 7:05 AM ET / 11:05 UTC.

ClawSweeper review

What this changes

The PR captures legacy audit files and matching SQLite audit rows around a slow backup snapshot, retries on drift, and adds CLI and restore-boundary regressions.

Merge readiness

⛔ Blocked before merge - 3 items remain

This PR remains necessary: current main still holds the short audit-migration lease across SQLite snapshotting, while this head releases it and verifies a single consistent filesystem/SQLite capture. No blocking correctness or security finding was identified.

Priority: P1
Reviewed head: 793d3804cbc6535cf422965a20e1412d8cb97ea5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-supported repair with real CLI evidence and strong boundary regressions; its explicit retry semantics and added coordination surface are understood merge risks.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body records an exact-head real CLI backup create --no-include-workspace --verify --json result with verified: true; the added product-path test reaches the real Node SQLite backup entry and observes a nonempty archive, while the owner-boundary test restores and reimports the staged archive exactly once.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body records an exact-head real CLI backup create --no-include-workspace --verify --json result with verified: true; the added product-path test reaches the real Node SQLite backup entry and observes a nonempty archive, while the owner-boundary test restores and reimports the staged archive exactly once.
Evidence reviewed 6 items Current-main behavior: Current main still captures legacy files and runs the SQLite snapshot planner inside the 60-second migration-lease callback, which is the slow-snapshot failure boundary this PR addresses.
PR capture owner: The introduced coordinator captures under the lease, snapshots SQLite after release, then recaptures and compares filesystem/database witnesses before accepting the staged state.
SQLite snapshot boundary: The global SQLite snapshot checks the pre-snapshot audit witness before sanitizing the staged copy and rewriting backup checkpoints; wrapped state-change errors reach the coordinator for retry.
Findings None None.
Security None None.

How this fits together

openclaw backup create stages state files and SQLite snapshots before publishing a verified archive. Legacy audit logs are migrated by Doctor into SQLite, so backup must preserve one restorable point across the filesystem-to-database transition.

flowchart LR
  A[Legacy audit files] --> B[Short migration lease]
  B --> C[Staged file and database witnesses]
  C --> D[SQLite snapshot]
  D --> E{Witnesses still match?}
  E -->|yes| F[Verified backup archive]
  E -->|no, up to 3 times| B
  E -->|still changing| G[Safe retry error]
Loading

Before merge

  • Resolve merge risk (P1) - The new bounded fail-closed path intentionally makes a backup retry after three continuously changing legacy-audit captures; this protects restore consistency but can require an operator retry under sustained writes.
  • Resolve merge risk (P1) - Production code grows by 165 net lines for the cross-store witness protocol; the filesystem and SQLite owners have no shared atomic snapshot primitive, so the added coordinator and staged-copy check are presently justified.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +165, Tests +252. Total +417 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 203 38 +165
Tests 3 259 7 +252
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 462 45 +417

Review metrics

Metric Value Why it matters
Production versus regression coverage production +165 net; tests +252 net The added production surface implements one cross-store consistency protocol, while the tests cover slow snapshot, interleaved migration, restore deduplication, and CLI behavior.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/infra/state-migrations.audit-backup.ts, serialized state: src/infra/state-migrations.audit-backup.ts, unknown-data-model-change: src/infra/state-migrations.audit-backup.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #130761
Summary: This PR is the focused candidate repair for the linked slow-snapshot backup failure.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept the bounded safe retry (recommended)
    Keep the three-attempt failure behavior because publishing a cross-generation filesystem/SQLite backup would risk duplicate restored audit records.

Technical review

Best possible solution:

Land the witness-based coordinator with its archive/restore interleaving regression, preserving the short lease only for capture and the explicit safe retry when a consistent state cannot be obtained.

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

Yes. The linked report and PR evidence give a concrete slow-snapshot path, and the checked-in regressions exercise the real backup/restore boundary with controlled timing and migration interleavings.

Is this the best way to solve the issue?

Yes. Keeping the lease around the slow SQLite operation reproduces the failure, while release without witnesses permits cross-generation restore duplication; the backup coordinator is the boundary that can validate both stores together.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: The PR changes backup behavior for existing state directories by retrying rather than publishing when legacy audit state changes during capture.

Label justifications:

  • P1: The linked report shows built-in verified backups can fail even with the Gateway stopped.
  • merge-risk: 🚨 compatibility: The PR changes backup behavior for existing state directories by retrying rather than publishing when legacy audit state changes during capture.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body records an exact-head real CLI backup create --no-include-workspace --verify --json result with verified: true; the added product-path test reaches the real Node SQLite backup entry and observes a nonempty archive, while the owner-boundary test restores and reimports the staged archive exactly once.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body records an exact-head real CLI backup create --no-include-workspace --verify --json result with verified: true; the added product-path test reaches the real Node SQLite backup entry and observes a nonempty archive, while the owner-boundary test restores and reimports the staged archive exactly once.

Evidence

What I checked:

  • Current-main behavior: Current main still captures legacy files and runs the SQLite snapshot planner inside the 60-second migration-lease callback, which is the slow-snapshot failure boundary this PR addresses. (src/infra/backup-create.ts:409, c4fd629a6da9)
  • PR capture owner: The introduced coordinator captures under the lease, snapshots SQLite after release, then recaptures and compares filesystem/database witnesses before accepting the staged state. (src/infra/backup-create.ts:383, 793d3804cbc6)
  • SQLite snapshot boundary: The global SQLite snapshot checks the pre-snapshot audit witness before sanitizing the staged copy and rewriting backup checkpoints; wrapped state-change errors reach the coordinator for retry. (src/infra/backup-sqlite-snapshot.ts:347, 793d3804cbc6)
  • Migration sibling contract: Doctor uses the same migration lease while importing legacy audit sources, so the PR's before/after witness protocol covers the competing lifecycle owner rather than relying on restore-time deduplication. (src/infra/state-migrations.audit-logs.ts:633, 793d3804cbc6)
  • Order-sensitive regression: The added regression schedules both a lease-duration overrun and a concurrent Doctor migration at the real snapshot-planner boundary, restores the archive, reruns the importer, and asserts exactly one record remains. (src/infra/backup-create.legacy-audit-lease.test.ts:15, 793d3804cbc6)
  • Real CLI proof: The checked-in product-path regression starts the CLI, shifts time when the real Node SQLite backup entry is reached, and verifies successful archive creation. (src/cli/program/register.backup.product-path.test.ts:47, 793d3804cbc6)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (5 earlier review cycles)
  • reviewed 2026-08-27T14:06:45.841Z sha 3bd25ec :: needs real behavior proof before merge. :: [P2] Add a regression for the released lease boundary
  • reviewed 2026-08-27T14:50:47.308Z sha 3bd25ec :: needs real behavior proof before merge. :: [P2] Cover the lease-release boundary with a regression
  • reviewed 2026-08-27T16:07:29.329Z sha c67184a :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-28T02:03:28.912Z sha c67184a :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T04:51:46.532Z sha 1c0106c :: needs maintainer review before merge. :: none

@gaoanze888

This comment was marked as spam.

@gaoanze888

This comment was marked as spam.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

@gaoanze888

This comment was marked as spam.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 28, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thanks @gaoanze888 — the original lease-loss failure is real, but the narrowed boundary introduces a restore duplication regression. Please preserve a consistent legacy-file/SQLite capture point before merging. This finding applies to current head c67184aa22b0a9c991298fbc143066172c22c9b5, not to an alternative implementation.

I reproduced the original failure with the unmodified published OpenClaw 2026.8.1 package (build commit ea806575e6450e4d1efdfc72c19f04be982a1b9b), synthetic isolated state, and no Gateway: a debugger-injected 62-second suspension at SQLite snapshot-planner entry left one live audit lease at the pause; after resuming, backup create exited 1 with legacy audit migration lease migration.legacy-audit/filesystem-sqlite-boundary was lost, and no archive was published.

The new failure occurs when Doctor runs between the two captures:

  1. Backup captures an active logs/config-audit.jsonl containing one synthetic record.
  2. After file capture releases the lease, Doctor imports that source under the real migration lease, writes its SQLite record, and archives the source.
  3. Backup snapshots SQLite after that import, then creates the archive.
  4. Restore that real archive into a fresh staging directory and run the real audit importer twice.

Expected: one restored audit record. Observed: two identical records. The added boundary test uses the real lease, SQLite snapshot, archive, restore command, and importer; its spy only schedules the competing import at SQLite snapshot-planner entry. The lease-duration-overrun case passes with this PR, while the concurrent-import case fails. The recorded four-suite run ended with 120 passed, 1 failed, 2 skipped. The preserved reproduction's executable production code matches this head; the local production-file difference was comments only. No read-pin proposal was present in that run.

The cause is the import identity contract, not an assertion about callback order: audit keys include the state-relative numbered .migrated[.N].raw generation, record ordinal, and sanitized-content digest. Generation selection and source migration therefore distinguish the restored active filename from the generation that Doctor already imported. The existing sanitized archive forces the restored active source onto a later generation, so overlap is not deduplicated as the new comment in backup-create.ts assumes.

Standalone boundary reproduction for the current head

In an isolated checkout at the head above with its normal dependencies installed, add the following temporary test as src/infra/backup-create.legacy-audit-lease.test.ts, then run the repository test wrapper:

node scripts/run-vitest.mjs src/infra/backup-create.legacy-audit-lease.test.ts

The failing assertion is the final equality against the single input record. This is a test-only scheduling probe, not a production patch.

import fs from "node:fs/promises";
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import { describe, expect, it, vi } from "vitest";
import { backupRestoreCommand } from "../commands/backup-restore.js";
import { CONFIG_AUDIT_MAX_ENTRIES, CONFIG_AUDIT_SCOPE } from "../config/io.audit.js";
import type { RuntimeEnv } from "../runtime.js";
import { closeOpenClawStateDatabase } from "../state/openclaw-state-db.js";
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
import { createBackupArchive } from "./backup-create.js";
import * as backupSqliteSnapshot from "./backup-sqlite-snapshot.js";
import { createSqliteAuditRecordStore } from "./sqlite-audit-record-store.js";
import { detectLegacyAuditLogs, migrateLegacyAuditLogs } from "./state-migrations.audit-logs.js";

describe("backup legacy audit capture boundary", () => {
  it.each(["lease-duration overrun", "concurrent audit migration"] as const)(
    "restores audit records exactly once after %s during the SQLite snapshot",
    async (scenario) => {
      await withOpenClawTestState(
        { layout: "state-only", prefix: "backup-audit-boundary-", scenario: "minimal" },
        async (state) => {
          const record = {
            ts: "2026-07-01T00:00:00.000Z",
            source: "config-io",
            event: "config.write",
            argv: ["openclaw", "config", "set", "safe", "preserved-audit-record"],
            execArgv: [],
          };
          await state.writeText("logs/config-audit.jsonl", `${JSON.stringify(record)}\n`);
          const originalSnapshot = backupSqliteSnapshot.createBackupSqliteSnapshotPlan;
          const realNow = Date.now.bind(Date);
          const clock = vi.spyOn(Date, "now");
          let snapshotReached = false;
          const snapshot = vi
            .spyOn(backupSqliteSnapshot, "createBackupSqliteSnapshotPlan")
            .mockImplementationOnce(async (params) => {
              snapshotReached = true;
              if (scenario === "lease-duration overrun") {
                // Model a synchronous snapshot outliving the lease while heartbeat timers cannot run.
                clock.mockImplementation(() => realNow() + 61_000);
              } else {
                const migrated = await migrateLegacyAuditLogs({
                  detected: detectLegacyAuditLogs({
                    stateDir: state.stateDir,
                    doctorOnlyStateMigrations: true,
                  }),
                  stateDir: state.stateDir,
                });
                expect(migrated.warnings).toEqual([]);
              }
              return await originalSnapshot(params);
            });
          try {
            const archive = await createBackupArchive({
              output: state.path("backup.tar.gz"),
              includeWorkspace: false,
            });
            expect(snapshotReached).toBe(true);
            clock.mockRestore();
            snapshot.mockRestore();
            const runtime: RuntimeEnv = { log: vi.fn(), error: vi.fn(), exit: vi.fn() };
            const restored = await backupRestoreCommand(runtime, {
              archive: archive.archivePath,
              target: state.path("restored"),
            });
            const manifest = JSON.parse(
              await fs.readFile(
                path.join(restored.targetPath, archive.archiveRoot, "manifest.json"),
                "utf8",
              ),
            ) as { assets: Array<{ kind: string; archivePath: string }> };
            const stateAsset = expectDefined(
              manifest.assets.find((asset) => asset.kind === "state"),
              "restored state asset",
            );
            const restoredStateDir = path.join(restored.targetPath, stateAsset.archivePath);
            for (let attempt = 0; attempt < 2; attempt += 1) {
              const migrated = await migrateLegacyAuditLogs({
                detected: detectLegacyAuditLogs({
                  stateDir: restoredStateDir,
                  doctorOnlyStateMigrations: true,
                }),
                stateDir: restoredStateDir,
              });
              expect(migrated.warnings).toEqual([]);
            }
            const records = createSqliteAuditRecordStore({
              scope: CONFIG_AUDIT_SCOPE,
              maxEntries: CONFIG_AUDIT_MAX_ENTRIES,
              env: { ...state.env, OPENCLAW_STATE_DIR: restoredStateDir },
            }).entries();
            expect(records.map((entry) => entry.value)).toEqual([record]);
          } finally {
            clock.mockRestore();
            snapshot.mockRestore();
            closeOpenClawStateDatabase();
          }
        },
      );
    },
  );
});

The repair needs one coherent file/database capture point without extending the timeout or weakening lease ownership. Separately, an unpublished read-snapshot-pin proposal was explored and rejected as incomplete: supported rollback-journal operation can block lease deletion behind the pinned reader, and the read-only recovery helper can prepare a private database copy before a later capture callback. Those are gaps in that alternative, not additional behavior attributed to this PR and not a recommended replacement.

This comment supplies a material regression finding; it does not close this PR or #130761 (the original backup lease-loss report). Both the original failure and this restored-record invariant should be regression gates for the eventual repair. Changes to import keys, retention, schema, or coordination storage need a separate maintainer decision.

@gaoanze888

This comment was marked as spam.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@gaoanze888

This comment was marked as spam.

@obviyus obviyus changed the title fix(backup): release audit lease before sqlite snapshot fix(backup): preserve audit capture across slow snapshots Sep 3, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 3, 2026
@obviyus

obviyus commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@obviyus
obviyus merged commit 0d17751 into openclaw:main Sep 3, 2026
215 of 218 checks passed
@obviyus

obviyus commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Thanks @gaoanze888!

Proof: The real backup create --no-include-workspace --verify --json command failed on current main after a 61.5-second stall at the real node:sqlite.backup entry. The exact landed source completed the same command with verified: true. The restore regression imports the archive twice and retains exactly one audit record.

  • Bug: Backup held a 60-second audit migration lease across potentially long SQLite work, while simply releasing it allowed a concurrent Doctor migration to duplicate restored audit history.
  • Fix: Backup now captures filesystem and database witnesses under short leases, snapshots SQLite outside the lease, validates both stores, and retries or fails closed on drift.
Before After
Slow snapshots lost the lease; an unlocked split could duplicate restored audit rows. Slow snapshots complete, and only one consistent filesystem/SQLite capture is published.
  • Landed: 0d17751
  • Source: 793d380
  • Tests: 144 passed, 2 skipped; exact-head Autoreview passed.

CI note: the sole failing child was unrelated to this backup diff. The exact src/commands/agent-exec.test.ts case fails with the same one-second fake-CLI PID timeout on both recorded current main and the PR head.

failed: checks-node-compact-small-6 job=100623609682 conclusion=failure

vincentkoc added a commit that referenced this pull request Sep 3, 2026
* commit '13b1f71c7010baaf2394555198e2fc04bef03586': (283 commits)
  fix(ui): retire stale MCP feedback across context changes (#128490)
  fix(agents): clarify set-identity workspace output (#126320)
  fix(auth): preserve OAuth metadata during session SDK refresh (#127988)
  fix(agents): recover catalog worker after generation mismatch (#127712)
  fix(memory-wiki): reject out-of-range claim confidence (#125656)
  ci: remove redundant contract runs and costly test work (#137220)
  fix(release): assert the Codex CLI pin the candidate declares (#137136)
  test(voice-call): reuse shared guards and deferred gates (#137262)
  fix(cron): isolate scheduler-disabled shared-store writes (#131733)
  fix(telegram): surface allowed custom reactions in react guidance (#129817)
  test(infra): reuse the shared npm call presence guard (#137254)
  fix: generated images disappear after failed tool calls (#131226)
  fix(docs): match source anchor checks to published sections (#137157)
  fix(backup): preserve audit capture across slow snapshots (#130962)
  fix(release): preserve legacy gh log reads (#137016)
  fix(memory-core): make forget rewrites atomic (#131383)
  fix(agents): write settings atomically (#131431)
  fix(plugins): keep the memory indexing runtime with the selected slot owner (#131779)
  fix(ci): pin iOS screenshot evidence to workflow revision (#136334)
  test(logging): remove redundant stderr spy casts (#137238)
  ...

# Conflicts:
#	scripts/e2e/lib/codex-release-package-assertions.mjs
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 4, 2026
…30962)

Closes openclaw#130761

## What Problem This Solves

`openclaw backup create` held the 60-second legacy-audit migration lease while it verified, copied, compacted, and published SQLite snapshots. A slow snapshot could outlive the lease and fail the backup even when the Gateway was stopped.

Releasing the lease without a consistency check created a second bug: Doctor could migrate a captured legacy file into SQLite between the file and database snapshots, so a restored backup imported the same audit record twice.

## Why This Change Was Made

Backup now treats the legacy filesystem and SQLite rows as one optimistic capture interval:

1. Capture sanitized legacy files and filesystem/database witnesses under the short migration lease.
2. Release the lease before the potentially long SQLite snapshot.
3. Verify the staged SQLite snapshot still matches the first database witness.
4. Reacquire the lease and compare a second filesystem/database witness.
5. Delete and retry the complete staged attempt on drift.
6. Fail closed after three changing attempts without publishing an archive.

The normal no-legacy path keeps its fast snapshot flow. The lease duration, database schema, import keys, retention, and restore format do not change.

## User Impact

Verified backups can complete after slow SQLite work without publishing a cross-store state that duplicates restored audit records.

## Evidence

- Current-main real CLI red: a proof-only 61.5-second stall at the real `node:sqlite.backup` entry exits with the reported lost-lease error.
- Exact-head real CLI green: the same `backup create --no-include-workspace --verify --json` command exits 0 with `verified: true`.
- Checked-in CLI red/green: the registered entry-point regression fails on current main with the exact error and passes on this head.
- Restore green: the owner-boundary regression restores the archive, runs the audit importer twice, and retains exactly one audit record.
- Focused exact-head tests: 144 passed, 2 skipped.
- Focused format, lint, lease, storage, and schema guards pass.

## Change Size

- Production: +203/-38, net +165.
- Tests: +259/-7, net +252.

The production growth records and verifies one cross-store consistency fact. It replaces the unsafe alternatives of holding the short lease across slow SQLite work or trusting restore-time deduplication across different legacy generations.

## AI Assistance

AI-assisted repair and review. Maintainer proof used the real backup and restore command paths.

Co-authored-by: gaoanze <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: backup create loses legacy audit migration lease on beta.3, even with Gateway stopped

3 participants