From 2c623b37a75e34287a57f0c29e078cab49a35e16 Mon Sep 17 00:00:00 2001 From: Arjun Ganesh Date: Thu, 24 Sep 2026 21:05:28 +0200 Subject: [PATCH 1/2] fix(backup): remove strict snapshot when recovery capture fails A strict pre-upgrade backup publishes its snapshot before capturing the policy and MCP recovery handoffs. When either capture threw, the command exited nonzero but left the new timestamped snapshot behind, even though it lacks the handoffs needed to restore after the historical gateway is retired. The MCP observation added in v0.0.128 made this path reachable. Remove the snapshot through the same path-confined cleanup used for failed strict backups, and report a cleanup failure alongside the original error. Fixes #12277 Signed-off-by: Arjun Ganesh --- .../strict-pre-upgrade-recovery.test.ts | 45 +++++++++++++++++- .../snapshot/strict-pre-upgrade-recovery.ts | 47 +++++++++++++------ 2 files changed, 76 insertions(+), 16 deletions(-) diff --git a/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.test.ts b/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.test.ts index 9e4a822a250..782e47bd3d2 100644 --- a/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.test.ts +++ b/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.test.ts @@ -153,7 +153,7 @@ describe("strict pre-upgrade recovery retention", () => { expect(mocks.captureRecordedSandboxBasePolicy).not.toHaveBeenCalled(); }); - it("does not publish either handoff when MCP observation fails", async () => { + it("removes the snapshot without publishing either handoff when MCP observation fails", async () => { mocks.observeMcpStateForRebuild.mockRejectedValue(new Error("MCP observation unavailable")); const result = { success: true, @@ -169,5 +169,48 @@ describe("strict pre-upgrade recovery retention", () => { ).rejects.toThrow("MCP observation unavailable"); expect(mocks.writeRebuildPolicyHandoff).not.toHaveBeenCalled(); expect(mocks.writeRebuildMcpHandoff).not.toHaveBeenCalled(); + expect(mocks.removeSandboxStateBackup).toHaveBeenCalledWith( + "alpha", + "/backups/alpha/timestamp", + ); + }); + + it("removes the snapshot when policy capture fails", async () => { + mocks.captureRecordedSandboxBasePolicy.mockRejectedValue(new Error("policy unavailable")); + const result = { + success: true, + backedUpDirs: ["workspace"], + failedDirs: [], + backedUpFiles: [], + failedFiles: [], + manifest: { backupPath: "/backups/alpha/timestamp" }, + }; + + await expect( + retainStrictPreUpgradeRecoveryState(sandbox as never, result as never, runtimeSelection), + ).rejects.toThrow("policy unavailable"); + expect(mocks.removeSandboxStateBackup).toHaveBeenCalledWith( + "alpha", + "/backups/alpha/timestamp", + ); + }); + + it("reports cleanup failure without hiding the recovery-state failure", async () => { + mocks.observeMcpStateForRebuild.mockRejectedValue(new Error("MCP observation unavailable")); + mocks.removeSandboxStateBackup.mockReturnValue(false); + const result = { + success: true, + backedUpDirs: ["workspace"], + failedDirs: [], + backedUpFiles: [], + failedFiles: [], + manifest: { backupPath: "/backups/alpha/timestamp" }, + }; + + await expect( + retainStrictPreUpgradeRecoveryState(sandbox as never, result as never, runtimeSelection), + ).rejects.toThrow( + "MCP observation unavailable. Failed strict pre-upgrade backup at '/backups/alpha/timestamp' could not be removed", + ); }); }); diff --git a/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.ts b/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.ts index 41272bccdae..bf1835d55ee 100644 --- a/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.ts +++ b/src/lib/actions/sandbox/snapshot/strict-pre-upgrade-recovery.ts @@ -6,6 +6,13 @@ import type { SandboxEntry } from "../../../state/registry/types"; import * as sandboxState from "../../../state/sandbox"; import { observeMcpStateForRebuild } from "../rebuild-mcp-phase"; +/** Remove a strict snapshot that cannot serve as a recovery point. Returns the + * cleanup failure message, or null when the snapshot was removed. */ +function removeUnusableStrictBackup(sandboxName: string, backupPath: string): string | null { + if (sandboxState.removeSandboxStateBackup(sandboxName, backupPath)) return null; + return `Failed strict pre-upgrade backup at '${backupPath}' could not be removed`; +} + /** Complete a strict pre-upgrade snapshot with the recovery authority that * becomes unavailable when the historical gateway is retired. */ export async function retainStrictPreUpgradeRecoveryState( @@ -16,31 +23,41 @@ export async function retainStrictPreUpgradeRecoveryState( if (!result.success) { const backupPath = result.manifest?.backupPath; if (!backupPath) return result; - if (sandboxState.removeSandboxStateBackup(sandbox.name, backupPath)) { + const cleanupError = removeUnusableStrictBackup(sandbox.name, backupPath); + if (!cleanupError) { const { manifest: _removedManifest, ...withoutPartialBackup } = result; return withoutPartialBackup; } - const cleanupError = `Failed strict pre-upgrade backup at '${backupPath}' could not be removed`; return { ...result, error: result.error ? `${result.error}. ${cleanupError}` : cleanupError, }; } - if (!result.manifest) { + const manifest = result.manifest; + if (!manifest) { throw new Error( `Strict pre-upgrade backup for '${sandbox.name}' completed without a published manifest`, ); } - const policyDocument = await captureRecordedSandboxBasePolicy( - sandbox.name, - "capture the live policy for pre-upgrade recovery", - ); - const mcpObservation = await observeMcpStateForRebuild(sandbox, runtimeSelection, true); - result.manifest = sandboxState.writeRebuildPolicyHandoff(result.manifest, policyDocument); - result.manifest = sandboxState.writeRebuildMcpHandoff( - result.manifest, - mcpObservation.entries, - mcpObservation.runtimeSelection ?? runtimeSelection, - ); - return result; + try { + const policyDocument = await captureRecordedSandboxBasePolicy( + sandbox.name, + "capture the live policy for pre-upgrade recovery", + ); + const mcpObservation = await observeMcpStateForRebuild(sandbox, runtimeSelection, true); + const withPolicyHandoff = sandboxState.writeRebuildPolicyHandoff(manifest, policyDocument); + result.manifest = sandboxState.writeRebuildMcpHandoff( + withPolicyHandoff, + mcpObservation.entries, + mcpObservation.runtimeSelection ?? runtimeSelection, + ); + return result; + } catch (error) { + // The snapshot is already published, but without its recovery handoffs it + // cannot restore once the historical gateway is retired. + const cleanupError = removeUnusableStrictBackup(sandbox.name, manifest.backupPath); + if (!cleanupError) throw error; + const detail = error instanceof Error ? error.message : String(error); + throw new Error(`${detail}. ${cleanupError}`, { cause: error }); + } } From cd7ddde7fa254bc57ad4b79e787810d723036af4 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Mon, 12 Oct 2026 13:52:22 +0530 Subject: [PATCH 2/2] fix(backup): clean up snapshots when native capture throws Remove the directory created by a failed capture while preserving the original error and earlier valid backups. Create the timestamp directory exclusively so a concurrent backup is not adopted for cleanup. Respect the existing cleanup deadline and report the retained path when removal cannot complete. Cover temporary-directory failure, denied cleanup, deadline expiry, and a competing backup writer through the native backup path. Refs #12277 Signed-off-by: Hung Le --- src/lib/state/sandbox.ts | 32 +++- test/state/snapshot-backup-cleanup-fixture.ts | 20 ++ test/state/snapshot-backup-cleanup.test.ts | 176 ++++++++++++++++++ 3 files changed, 224 insertions(+), 4 deletions(-) create mode 100644 test/state/snapshot-backup-cleanup-fixture.ts create mode 100644 test/state/snapshot-backup-cleanup.test.ts diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 697c8b54aef..fa848bc337f 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -2158,7 +2158,11 @@ function withSshCleanupResult({ } /** Capture one opaque archive of the OpenShell-owned native home/workspace. */ -function backupNativeSandboxState(sandboxName: string, options: BackupOptions): BackupResult { +function backupNativeSandboxState( + sandboxName: string, + options: BackupOptions, + onDirectoryCreated: (backupPath: string) => void, +): BackupResult { if (backupDeadlineExpired(options.deadlineMs)) { return nativeStateFailure("Sandbox backup deadline expired before backup started", true); } @@ -2173,7 +2177,10 @@ function backupNativeSandboxState(sandboxName: string, options: BackupOptions): if (existsSync(backupPath)) return nativeStateFailure(`Snapshot path '${backupPath}' already exists; retry the backup.`); rejectSymlinksOnPath(backupPath); - mkdirSync(backupPath, { recursive: true, mode: 0o700 }); + mkdirSync(path.dirname(backupPath), { recursive: true, mode: 0o700 }); + // Claim only a new leaf so failure cleanup cannot remove a concurrent backup. + mkdirSync(backupPath, { mode: 0o700 }); + onDirectoryCreated(backupPath); rejectSymlinksOnPath(backupPath); let temporary: ReturnType | null = null; @@ -2482,7 +2489,24 @@ function backupNativeSandboxState(sandboxName: string, options: BackupOptions): } export function backupSandboxState(sandboxName: string, options: BackupOptions = {}): BackupResult { - return backupNativeSandboxState(sandboxName, options); + let createdBackupPath: string | undefined; + try { + return backupNativeSandboxState(sandboxName, options, (backupPath) => { + createdBackupPath = backupPath; + }); + } catch (error) { + if ( + createdBackupPath && + !removeSandboxStateBackup(sandboxName, createdBackupPath, options.deadlineMs) + ) { + const detail = error instanceof Error ? error.message : String(error); + throw new Error( + `${detail}. Incomplete backup at '${createdBackupPath}' could not be removed`, + { cause: error }, + ); + } + throw error; + } } // ── Restore ──────────────────────────────────────────────────────── @@ -3157,7 +3181,7 @@ export type RebuildRecoveryManifestValidation = | { ok: false; reason: string }; /** - * Remove one completed rebuild backup without allowing a caller-controlled + * Remove one rebuild backup without allowing a caller-controlled * path to escape the sandbox's timestamped backup directory. */ function removePathWithinDeadline(targetPath: string, deadlineMs?: number): boolean { diff --git a/test/state/snapshot-backup-cleanup-fixture.ts b/test/state/snapshot-backup-cleanup-fixture.ts new file mode 100644 index 00000000000..ed5185cb746 --- /dev/null +++ b/test/state/snapshot-backup-cleanup-fixture.ts @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import path from "node:path"; +import { vi } from "vitest"; + +export function beforeNextBackupDirectoryCreate(sandboxRoot: string, create: () => void): void { + const originalMkdirSync = fs.mkdirSync; + const mkdir = vi.spyOn(fs, "mkdirSync").mockImplementation((directory, options) => { + if (path.dirname(String(directory)) === sandboxRoot) { + mkdir.mockRestore(); + syncBuiltinESMExports(); + create(); + } + return Reflect.apply(originalMkdirSync, undefined, [directory, options]); + }); + syncBuiltinESMExports(); +} diff --git a/test/state/snapshot-backup-cleanup.test.ts b/test/state/snapshot-backup-cleanup.test.ts new file mode 100644 index 00000000000..b493a36642d --- /dev/null +++ b/test/state/snapshot-backup-cleanup.test.ts @@ -0,0 +1,176 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeNextBackupDirectoryCreate } from "./snapshot-backup-cleanup-fixture"; + +const ORIGINAL_HOME = process.env.HOME; +const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-backup-cleanup-")); +process.env.HOME = TMP_HOME; + +const sandboxState = (await import( + pathToFileURL(path.join(import.meta.dirname, "../..", "src", "lib", "state", "sandbox.ts")).href +)) as typeof import("../../src/lib/state/sandbox.js"); +const SANDBOX_BACKUPS = path.join(TMP_HOME, ".nemoclaw", "rebuild-backups", "alpha"); +const NATIVE_ROOT = path.join(TMP_HOME, "native-home"); +const INVALID_TMPDIR = path.join(TMP_HOME, "not-a-directory"); +const OPENSHELL = path.join(TMP_HOME, "openshell"); + +beforeEach(() => { + fs.rmSync(SANDBOX_BACKUPS, { recursive: true, force: true }); + fs.mkdirSync(path.join(TMP_HOME, ".nemoclaw"), { recursive: true }); + fs.writeFileSync( + path.join(TMP_HOME, ".nemoclaw", "sandboxes.json"), + JSON.stringify({ + defaultSandbox: "alpha", + sandboxes: { + alpha: { name: "alpha", model: "m", provider: "p", gpuEnabled: false, agent: null }, + }, + }), + ); + fs.mkdirSync(NATIVE_ROOT, { recursive: true }); + fs.writeFileSync(path.join(NATIVE_ROOT, "state.txt"), "preserved\n"); + fs.writeFileSync(INVALID_TMPDIR, "occupied\n"); + fs.writeFileSync( + OPENSHELL, + '#!/usr/bin/env node\nprocess.stdout.write("Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n");\n', + { mode: 0o755 }, + ); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", OPENSHELL); + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); +}); + +afterEach(() => { + vi.restoreAllMocks(); + syncBuiltinESMExports(); + vi.useRealTimers(); + vi.unstubAllEnvs(); +}); + +afterAll(() => { + ORIGINAL_HOME === undefined + ? Reflect.deleteProperty(process.env, "HOME") + : Reflect.set(process.env, "HOME", ORIGINAL_HOME); + fs.rmSync(TMP_HOME, { recursive: true, force: true }); +}); + +function captureNativeBackup() { + const result = sandboxState.backupSandboxState("alpha", { + nativeStateSource: { + root: "/sandbox", + directory: NATIVE_ROOT, + assertCurrent: () => undefined, + }, + }); + expect(result.success, result.error).toBe(true); + const manifest = result.manifest!; + const manifestPath = path.join(manifest.backupPath, "rebuild-manifest.json"); + const archivePath = path.join(manifest.backupPath, "native-home.tar"); + return { + timestamp: manifest.timestamp, + manifestPath, + manifestContents: fs.readFileSync(manifestPath), + archivePath, + archiveContents: fs.readFileSync(archivePath), + }; +} + +function prepareSshTempFailure() { + const previous = captureNativeBackup(); + vi.setSystemTime(Date.now() + 1_000); + const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); + vi.spyOn(os, "tmpdir").mockReturnValue(INVALID_TMPDIR); + return { previous, timestamp, backupPath: path.join(SANDBOX_BACKUPS, timestamp) }; +} + +describe("cleanup after native backup throws", () => { + it("removes its new directory when SSH temporary-directory creation fails (#12277)", () => { + const { previous } = prepareSshTempFailure(); + + let failure: unknown; + try { + sandboxState.backupSandboxState("alpha"); + } catch (error) { + failure = error; + } + + expect(failure).toMatchObject({ code: "ENOTDIR" }); + + expect(fs.readdirSync(SANDBOX_BACKUPS)).toEqual([previous.timestamp]); + expect(fs.readFileSync(previous.manifestPath)).toEqual(previous.manifestContents); + expect(fs.readFileSync(previous.archivePath)).toEqual(previous.archiveContents); + }); + + it("reports the retained path and original error when cleanup is denied (#12277)", () => { + const { previous, timestamp, backupPath } = prepareSshTempFailure(); + vi.spyOn(fs, "rmSync").mockImplementationOnce(() => { + throw Object.assign(new Error("EACCES: cleanup denied"), { code: "EACCES" }); + }); + syncBuiltinESMExports(); + + let failure: unknown; + try { + sandboxState.backupSandboxState("alpha"); + } catch (error) { + failure = error; + } + + expect(failure).toMatchObject({ + message: expect.stringContaining(`Incomplete backup at '${backupPath}' could not be removed`), + cause: expect.objectContaining({ code: "ENOTDIR" }), + }); + expect(fs.readdirSync(SANDBOX_BACKUPS).sort()).toEqual([previous.timestamp, timestamp]); + expect(fs.readdirSync(backupPath)).toEqual([]); + expect(fs.readFileSync(previous.manifestPath)).toEqual(previous.manifestContents); + expect(fs.readFileSync(previous.archivePath)).toEqual(previous.archiveContents); + }); + + it("preserves the deadline and reports incomplete cleanup after capture throws (#12277)", () => { + const { previous, timestamp, backupPath } = prepareSshTempFailure(); + const deadlineMs = Date.now() + 30_000; + const originalMkdtempSync = fs.mkdtempSync; + vi.spyOn(fs, "mkdtempSync").mockImplementationOnce((prefix, options) => { + vi.setSystemTime(deadlineMs); + return Reflect.apply(originalMkdtempSync, undefined, [prefix, options]); + }); + syncBuiltinESMExports(); + + let failure: unknown; + try { + sandboxState.backupSandboxState("alpha", { deadlineMs }); + } catch (error) { + failure = error; + } + + expect(failure).toMatchObject({ + message: expect.stringContaining(`Incomplete backup at '${backupPath}' could not be removed`), + cause: expect.objectContaining({ code: "ENOTDIR" }), + }); + expect(fs.readdirSync(SANDBOX_BACKUPS).sort()).toEqual([previous.timestamp, timestamp]); + expect(fs.readdirSync(backupPath)).toEqual([]); + expect(fs.readFileSync(previous.manifestPath)).toEqual(previous.manifestContents); + expect(fs.readFileSync(previous.archivePath)).toEqual(previous.archiveContents); + }); + + it("preserves a backup completed by another writer before directory creation (#12277)", () => { + fs.writeFileSync(OPENSHELL, "#!/usr/bin/env node\nprocess.exit(1);\n", { mode: 0o755 }); + let concurrent: ReturnType | undefined; + beforeNextBackupDirectoryCreate(SANDBOX_BACKUPS, () => { + concurrent = captureNativeBackup(); + }); + + expect(() => sandboxState.backupSandboxState("alpha")).toThrow(/EEXIST/); + + expect(concurrent).toBeDefined(); + expect(fs.readdirSync(SANDBOX_BACKUPS)).toEqual([concurrent!.timestamp]); + expect(fs.readFileSync(concurrent!.manifestPath)).toEqual(concurrent!.manifestContents); + expect(fs.readFileSync(concurrent!.archivePath)).toEqual(concurrent!.archiveContents); + }); +});