Repository navigation
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
This comment was marked as spam.
This comment was marked as spam.
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Codex review: blocked before merge. Reviewed September 3, 2026, 7:05 AM ET / 11:05 UTC. ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits together
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]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +165, Tests +252. Total +417 across 6 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
This comment was marked as spam.
|
🦞🧹 I asked ClawSweeper to review this item again. |
This comment was marked as spam.
This comment was marked as spam.
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
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 I reproduced the original failure with the unmodified published OpenClaw 2026.8.1 package (build commit The new failure occurs when Doctor runs between the two captures:
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 Standalone boundary reproduction for the current headIn an isolated checkout at the head above with its normal dependencies installed, add the following temporary test as node scripts/run-vitest.mjs src/infra/backup-create.legacy-audit-lease.test.tsThe 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. |
This comment was marked as spam.
This comment was marked as spam.
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
This comment was marked as spam.
This comment was marked as spam.
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Thanks @gaoanze888! Proof: The real
CI note: the sole failing child was unrelated to this backup diff. The exact failed: checks-node-compact-small-6 job=100623609682 conclusion=failure |
* 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
…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]>
Closes #130761
What Problem This Solves
openclaw backup createheld 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:
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
node:sqlite.backupentry exits with the reported lost-lease error.backup create --no-include-workspace --verify --jsoncommand exits 0 withverified: true.Change Size
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.