From fde8d421bddf936186a4ba000620d0a0ba827fd1 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Thu, 8 Oct 2026 18:45:32 +0530 Subject: [PATCH 1/9] fix(sandbox): release verified absent recovery reservations Reconcile identity-free failed-create metadata only after proving gateway and runtime absence under the existing ownership locks. Preserve conflicting ownership and allow interrupted cleanup to retry. Fixes #12260 Signed-off-by: Hung Le --- src/lib/actions/sandbox/destroy-execution.ts | 17 + .../actions/sandbox/destroy-gateway.test.ts | 17 + src/lib/actions/sandbox/destroy-gateway.ts | 2 + src/lib/actions/sandbox/destroy-preflight.ts | 47 +- src/lib/actions/sandbox/destroy-presence.ts | 3 +- .../destroy-retained-recovery-flow.test.ts | 20 +- src/lib/actions/sandbox/destroy.ts | 24 +- .../lifecycle/retained-recovery.test.ts | 407 ++++++++++++++++++ .../sandbox/lifecycle/retained-recovery.ts | 213 +++++++++ src/lib/onboard/lifecycle-contracts.md | 7 + .../openshell-docker-sandbox-containers.ts | 15 +- src/lib/state/onboard-session.ts | 3 +- 12 files changed, 731 insertions(+), 44 deletions(-) create mode 100644 src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts create mode 100644 src/lib/actions/sandbox/lifecycle/retained-recovery.ts diff --git a/src/lib/actions/sandbox/destroy-execution.ts b/src/lib/actions/sandbox/destroy-execution.ts index 93edff1e48e..84ae7372c1d 100644 --- a/src/lib/actions/sandbox/destroy-execution.ts +++ b/src/lib/actions/sandbox/destroy-execution.ts @@ -67,6 +67,23 @@ export function redactDestroyError(error: unknown): string { return redactFull(error instanceof Error ? error.message : String(error)); } +export function stopSandboxInferenceResources( + sandboxName: string, + sandbox: SandboxEntry | null, +): void { + const nim = require("../../inference/nim") as { + stopNimContainer: (name: string, opts?: { silent?: boolean }) => void; + stopNimContainerByName: (name: string) => void; + }; + if (sandbox?.nimContainer) { + console.log(` Stopping NIM for '${sandboxName}'...`); + nim.stopNimContainerByName(sandbox.nimContainer); + } else { + // Older registry entries may not record the convention-named container. + nim.stopNimContainer(sandboxName, { silent: true }); + } +} + const SANDBOX_NATIVE_ROOT = "/sandbox"; const COMPLETE_NATIVE_HOME_AGENTS = new Set(["hermes", "langchain-deepagents-code", "openclaw"]); diff --git a/src/lib/actions/sandbox/destroy-gateway.test.ts b/src/lib/actions/sandbox/destroy-gateway.test.ts index b2caf65b7f9..7df8cf31354 100644 --- a/src/lib/actions/sandbox/destroy-gateway.test.ts +++ b/src/lib/actions/sandbox/destroy-gateway.test.ts @@ -109,6 +109,23 @@ describe("cleanupGatewayAfterLastSandbox", () => { }); }); + it("requires an owned runtime marker for identity-free recovery (#12260)", () => { + mocks.resolveOwnedHostGatewayRuntimeProviderId.mockReturnValue(null); + expect( + resolveGatewayCleanupRuntimeProviderId("nemoclaw-8081", "docker", { + configuredRuntimeProviderId: "docker", + requireOwnedRuntime: true, + }), + ).toBeNull(); + + mocks.resolveOwnedHostGatewayRuntimeProviderId.mockReturnValueOnce("docker"); + expect( + resolveGatewayCleanupRuntimeProviderId("nemoclaw-8081", undefined, { + requireOwnedRuntime: true, + }), + ).toBe("docker"); + }); + it("rejects disagreement between sandbox and gateway provider authority", () => { mocks.resolveOwnedHostGatewayRuntimeProviderId.mockReturnValueOnce("docker"); diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index 528ab78803e..04085eebfb1 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -58,6 +58,7 @@ interface ResolveGatewayCleanupRuntimeProviderDeps extends Pick< "resolveOwnedRuntimeProviderId" > { configuredRuntimeProviderId?: string | null; + requireOwnedRuntime?: boolean; } // Compute the Docker-driver gateway state directory that belongs to @@ -97,6 +98,7 @@ export function resolveGatewayCleanupRuntimeProviderId( stateDir: perGatewayState.stateDir, }, ); + if (deps.requireOwnedRuntime && !recorded) return null; if (registered && recorded && registered !== recorded) { throw new Error( `Refusing cleanup for gateway '${gatewayName}': registered runtime provider '${registered}' does not match recorded gateway runtime provider '${recorded}'.`, diff --git a/src/lib/actions/sandbox/destroy-preflight.ts b/src/lib/actions/sandbox/destroy-preflight.ts index ee02d15fdd6..4c1358d6ea9 100644 --- a/src/lib/actions/sandbox/destroy-preflight.ts +++ b/src/lib/actions/sandbox/destroy-preflight.ts @@ -55,6 +55,36 @@ import { } from "./gateway-target"; export { teardownSandboxDashboardForward } from "./forward-recovery"; +import { reconcileIdentityFreeRecovery as reconcileRetainedMetadata } from "./lifecycle/retained-recovery"; + +/** Probe only the recorded gateway before reconciling identity-free local metadata. */ +export function reconcileIdentityFreeRecovery( + sandboxName: string, + records: Parameters[1], + owningGatewayPort: number, + state: Omit[3], "observeSandbox" | "timeoutMs"> & { + captureOpenshell?: typeof import("../../adapters/openshell/runtime").captureOpenshell; + }, +): boolean { + const captureOpenshell = + state.captureOpenshell ?? + ( + require("../../adapters/openshell/runtime") as typeof import("../../adapters/openshell/runtime") + ).captureOpenshell; + return reconcileRetainedMetadata(sandboxName, records, owningGatewayPort, { + ...state, + timeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, + observeSandbox: (gatewayName) => + classifyDestroySandboxPresence( + sandboxName, + captureOpenshell(["sandbox", "list", "-g", gatewayName, "--output", "json"], { + ignoreError: true, + includeStreams: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }), + ), + }); +} export type SandboxDestroyPreflight = { cleanupGatewayName: string; @@ -128,23 +158,6 @@ export function resolveSandboxDestroyRuntimeSelection( return undefined; } -export function stopSandboxInferenceResources( - sandboxName: string, - sandbox: SandboxEntry | null, -): void { - const nim = require("../../inference/nim") as { - stopNimContainer: (name: string, opts?: { silent?: boolean }) => void; - stopNimContainerByName: (name: string) => void; - }; - if (sandbox?.nimContainer) { - console.log(` Stopping NIM for '${sandboxName}'...`); - nim.stopNimContainerByName(sandbox.nimContainer); - } else { - // Older registry entries may not record the convention-named container. - nim.stopNimContainer(sandboxName, { silent: true }); - } -} - function sandboxGatewayPort(entry: SandboxEntry): number { return registryEntryGatewayPort({ name: entry.name, diff --git a/src/lib/actions/sandbox/destroy-presence.ts b/src/lib/actions/sandbox/destroy-presence.ts index e8d3351c5b9..b58ddef511d 100644 --- a/src/lib/actions/sandbox/destroy-presence.ts +++ b/src/lib/actions/sandbox/destroy-presence.ts @@ -74,8 +74,9 @@ export type DestroyContainerIdentityProof = { /** Read the host observation consumed by the pure identity classifier. */ export function observeDestroyContainerIdentity( sandboxName: string, + inspect?: Parameters[1], ): DockerSandboxIdentityObservation { - return inspectDockerSandboxNameLabeledContainers(sandboxName); + return inspectDockerSandboxNameLabeledContainers(sandboxName, inspect); } /** diff --git a/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts b/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts index 212723a3693..e0df890386c 100644 --- a/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts @@ -58,16 +58,13 @@ function cancellationRecoveryFor( function prepublicationRecoveryHarness( options: { - identityFree?: boolean; partialLifecycleGeneration?: boolean; reservationSessionId?: string; sandboxPresent?: boolean; sessionRecoveryOverrides?: Partial; } = {}, ) { - const recovery = options.identityFree - ? retainedRecoveryRecordWithoutIdentity() - : retainedRecoveryRecord(); + const recovery = retainedRecoveryRecord(); const harness = createDestroyHarness({ sandboxPresent: options.sandboxPresent ?? false, dockerRunResult: { status: 0, stdout: "" }, @@ -267,21 +264,6 @@ describe("destroySandbox retained recovery flow", () => { }, ); - it( - "refuses identity-free recovery before pending identity publication (#11418)", - { timeout: 30_000 }, - async () => { - const { harness } = prepublicationRecoveryHarness({ identityFree: true }); - - await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow( - "process.exit(1)", - ); - - expect(harness.resolveRetainedSandboxRecoverySpy).not.toHaveBeenCalled(); - expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); - }, - ); - it( "removes every container after OpenShell confirms the retained sandbox absent (#10547)", { timeout: 30_000 }, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index ab80bcd202f..32dff7eb79f 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -62,6 +62,7 @@ import { preparePortableDemoSandboxDestroyAuthority, redactDestroyError, retirePortableLifecycleAuthority, + stopSandboxInferenceResources, } from "./destroy-execution"; import { cleanupGatewayAfterLastSandbox, @@ -82,6 +83,7 @@ import { import { withSandboxLifecycleLock } from "./lifecycle/lock"; import { prepareSandboxDestroy, + reconcileIdentityFreeRecovery, recordManagedVllmRetirementPending, reportManagedVllmDestroyOutcome, resolveSandboxDestroyRegistryAuthority, @@ -91,7 +93,6 @@ import { listInferenceRouteOwnersAcrossGatewayRoots, stopModelRouterForDestroyedSandbox, stopDestroyedSandboxProxy, - stopSandboxInferenceResources, teardownSandboxDashboardForward, } from "./destroy-preflight"; @@ -727,6 +728,27 @@ async function destroySandboxUnlocked( } const destroySession = onboardSession.loadSession(); const retainedRecoveryRecords = onboardSession.listRetainedSandboxRecoveryRecords(); + try { + if ( + reconcileIdentityFreeRecovery( + sandboxName, + retainedRecoveryRecords, + registryAuthority.gatewayPort, + { + session: onboardSession, + registry, + }, + ) + ) { + console.log( + ` Cleared retained recovery for '${sandboxName}'. No sandbox resources were removed.`, + ); + return; + } + } catch (error) { + console.error(` ${redactDestroyError(error)}`); + requestSandboxDestroyExit(1); + } const retainedRecoveryAuthority = selectRetainedSandboxRecoveryAuthority( sandboxName, registeredSandbox, diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts new file mode 100644 index 00000000000..6ffa396cd2b --- /dev/null +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -0,0 +1,407 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +let testHome: string; +const emptyDockerResult = { + status: 0, + stdout: "", + stderr: "", + pid: 0, + output: [null, "", ""], + signal: null, +}; + +beforeAll(async () => { + // Load the shared CLI graph before timing recovery operations in each isolated state root. + await import("../destroy-preflight"); +}); + +beforeEach(() => { + testHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-metadata-")); + vi.stubEnv("HOME", testHome); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(testHome, { recursive: true, force: true }); +}); + +async function setup(port = 19260) { + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", String(port)); + vi.resetModules(); + const session = await import("../../../state/onboard-session"); + const registry = await import("../../../state/registry"); + const docker = await import("../../../adapters/docker/run"); + const dockerTarget = await import("../../../adapters/docker/client-isolation"); + const presence = await import("../destroy-presence"); + const gateway = await import("../destroy-gateway"); + const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); + const gatewayName = port === 8080 ? "nemoclaw" : `nemoclaw-${port}`; + const route = { + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: null, + gatewayName, + reservationSessionId: "failed-create-session", + }; + session.saveSession( + session.createSession({ + sessionId: route.reservationSessionId, + sandboxName: "alpha", + agent: "openclaw", + provider: route.provider, + model: route.model, + }), + ); + registry.reserveSandboxInferenceRoute("alpha", route); + session.markRetainedSandboxRecovery("alpha", "identity lookup failed", undefined, { + gatewayName, + gatewayPort: port, + lifecycleGeneration: "failed-generation", + createAttemptNonce: "a".repeat(62), + }); + const record = session.listRetainedSandboxRecoveryRecords()[0]!; + const capture = vi + .fn() + .mockReturnValue({ + status: 0, + output: "[]", + stdout: "[]", + stderr: "", + }); + const containers = vi.spyOn(presence, "observeDestroyContainerIdentity").mockReturnValue({ + status: "observed", + rows: [], + malformedRows: 0, + }); + const volumes = vi.spyOn(docker, "dockerRun").mockReturnValue(emptyDockerResult); + const runtime = vi + .spyOn(gateway, "resolveGatewayCleanupRuntimeProviderId") + .mockReturnValue("docker"); + const defaultDaemon = vi + .spyOn(dockerTarget, "dockerContextIsDefaultFromBuild") + .mockReturnValue(true); + const files = [ + registry.REGISTRY_FILE, + session.SESSION_FILE, + session.RETAINED_SANDBOX_RECOVERY_FILE, + ]; + const snapshot = () => files.map((file) => fs.readFileSync(file, "utf8")); + const run = () => + reconcileIdentityFreeRecovery("alpha", session.listRetainedSandboxRecoveryRecords(), port, { + session, + registry, + captureOpenshell: capture, + }); + return { + session, + registry, + route, + record, + capture, + containers, + volumes, + runtime, + defaultDaemon, + snapshot, + run, + }; +} + +describe.skipIf(process.platform !== "linux")("identity-free retained recovery", () => { + it.each([8080, 19260])( + "releases the retained sandbox name after verified absence on gateway port %s (#12260)", + async (port) => { + const h = await setup(port); + expect(h.registry.getSandbox("alpha")?.gatewayPort).toBeUndefined(); + expect(h.record.sandboxIdentityFingerprint).toBeNull(); + + expect(h.run()).toBe(true); + + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.session.loadSession()).toMatchObject({ + status: "failed", + sandboxName: null, + cancellationRecovery: null, + }); + expect( + h.capture.mock.calls.every(([args]) => args[0] === "sandbox" && args[1] === "list"), + ).toBe(true); + expect(h.volumes.mock.calls.every(([args]) => args[2] === "volume" && args[3] === "ls")).toBe( + true, + ); + expect( + h.registry.reserveSandboxInferenceRoute("alpha", { + ...h.route, + reservationSessionId: "new-session", + }), + ).toBe(true); + }, + ); + + it.each([ + ["failed", { status: 1, output: "", stdout: "[]", stderr: "connection refused" }], + ["malformed", { status: 0, output: "invalid", stdout: "invalid", stderr: "" }], + ["diagnostic", { status: 0, output: "[]", stdout: "[]", stderr: "partial result" }], + [ + "present", + { + status: 0, + output: "", + stdout: JSON.stringify([ + { + id: "sandbox-alpha", + name: "alpha", + labels: {}, + phase: "Ready", + created_at: "2026-10-08", + resource_version: 1, + current_policy_version: 1, + }, + ]), + stderr: "", + }, + ], + ])("preserves state when the gateway observation is %s (#12260)", async (_label, observation) => { + const h = await setup(); + const before = h.snapshot(); + h.capture.mockReturnValue(observation); + + expect(h.run).toThrow(/presence as/u); + + expect(h.snapshot()).toEqual(before); + }); + + it.each(["residual", "failed", "malformed"])( + "preserves state for a %s container observation (#12260)", + async (kind) => { + const h = await setup(); + const before = h.snapshot(); + h.containers.mockReturnValue( + kind === "failed" + ? { status: "probe-failed", detail: "Docker unavailable" } + : { + status: "observed", + malformedRows: kind === "malformed" ? 1 : 0, + rows: + kind === "residual" + ? [ + { + id: "b".repeat(64), + managedBy: "openshell", + workspace: "default", + sandboxId: "sandbox-alpha", + }, + ] + : [], + }, + ); + + expect(h.run).toThrow(/container runtime/u); + + expect(h.snapshot()).toEqual(before); + }, + ); + + it.each(["nemoclaw-openclaw-state-v1-alpha", "nemoclaw-hermes-state-v1-alpha"])( + "preserves the recovery record when volume %s remains (#12260)", + async (volume) => { + const h = await setup(); + const before = h.snapshot(); + h.volumes.mockReturnValue({ ...emptyDockerResult, stdout: `${volume}\n` }); + + expect(h.run).toThrow(/volume absence/u); + + expect(h.snapshot()).toEqual(before); + }, + ); + + it("preserves state when volume inspection fails (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.volumes.mockReturnValue({ ...emptyDockerResult, status: 1, stderr: "unavailable" }); + expect(h.run).toThrow(/inspect retained volumes/u); + expect(h.snapshot()).toEqual(before); + }); + + it("pins container and volume observations to the default Docker daemon (#12260)", async () => { + const h = await setup(); + h.containers.mockRestore(); + + expect(h.run()).toBe(true); + + expect( + h.volumes.mock.calls.some( + ([args]) => args[0] === "--context" && args[1] === "default" && args[2] === "ps", + ), + ).toBe(true); + expect( + h.volumes.mock.calls.every( + ([args]) => + args[0] === "--context" && args[1] === "default" && ["ps", "volume"].includes(args[2]!), + ), + ).toBe(true); + }); + + it("preserves sandbox-scoped provider ownership after sandbox absence (#12260)", async () => { + const h = await setup(); + h.session.recordRetainedSandboxRecovery({ + ...h.record, + resources: { ...h.record.resources, sandboxScopedProviders: ["alpha-provider"] }, + }); + const before = h.snapshot(); + expect(h.run).toThrow(/sandbox-scoped resources/u); + expect(h.snapshot()).toEqual(before); + }); + + it.each([null, "podman"])( + "rejects unproven Docker absence for runtime %s (#12260)", + async (runtime) => { + const h = await setup(); + const before = h.snapshot(); + h.runtime.mockReturnValue(runtime); + expect(h.run).toThrow(/owning Docker runtime/u); + expect(h.snapshot()).toEqual(before); + }, + ); + + it("preserves records when more than one failed create uses the same name (#12260)", async () => { + const h = await setup(); + h.session.recordRetainedSandboxRecovery({ ...h.record, createAttemptNonce: "b".repeat(62) }); + const before = h.snapshot(); + expect(h.run).toThrow(/exactly one/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves a reservation owned by another session (#12260)", async () => { + const h = await setup(); + h.session.saveSession({ ...h.session.loadSession()!, sessionId: "replacement-session" }); + const before = h.snapshot(); + expect(h.run).toThrow(/conflicting ownership/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves identity-free recovery while the session is still in progress (#12260)", async () => { + const h = await setup(); + h.session.saveSession( + h.session.createSession({ + sessionId: h.route.reservationSessionId, + sandboxName: "alpha", + }), + ); + const before = h.snapshot(); + expect(h.run).toThrow(/conflicting ownership/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves metadata when Docker targets another daemon (#12260)", async () => { + const h = await setup(); + h.defaultDaemon.mockReturnValue(false); + const before = h.snapshot(); + expect(h.run).toThrow(/default daemon/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves recovery when its gateway differs from the owning registry root (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); + expect(() => + reconcileIdentityFreeRecovery("alpha", [h.record], 8080, { + session: h.session, + registry: h.registry, + captureOpenshell: h.capture, + }), + ).toThrow(/recovery gateway/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves a changed recovery record after successful absence probes (#12260)", async () => { + const h = await setup(); + h.capture.mockImplementationOnce(() => { + h.session.recordRetainedSandboxRecovery({ + ...h.record, + resources: { + ...h.record.resources, + sandboxScopedProviders: ["alpha-provider"], + }, + }); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; + }); + expect(h.run).toThrow(/recovery record changed/u); + expect(h.registry.getSandbox("alpha")).not.toBeNull(); + expect( + h.session.listRetainedSandboxRecoveryRecords()[0]?.resources.sandboxScopedProviders, + ).toEqual(["alpha-provider"]); + }); + + it("preserves a replacement session after registry retirement (#12260)", async () => { + const h = await setup(); + h.registry.removeSandboxRouteReservationIfCurrent(h.registry.getSandbox("alpha")!); + h.session.saveSession( + h.session.createSession({ + sessionId: "replacement-session", + sandboxName: "other-sandbox", + }), + ); + const replacement = fs.readFileSync(h.session.SESSION_FILE, "utf8"); + expect(h.run()).toBe(true); + expect(fs.readFileSync(h.session.SESSION_FILE, "utf8")).toBe(replacement); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + }); + + it("preserves a registry replacement that appears during absence verification (#12260)", async () => { + const h = await setup(); + h.capture.mockImplementationOnce(() => { + h.registry.removeSandboxRouteReservationIfCurrent(h.registry.getSandbox("alpha")!); + h.registry.reserveSandboxInferenceRoute("alpha", { + ...h.route, + model: "replacement", + reservationSessionId: "replacement-session", + }); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; + }); + expect(h.run).toThrow(/registry changed/u); + expect(h.registry.getSandbox("alpha")?.model).toBe("replacement"); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([h.record]); + }); + + it("preserves recovery when absence cannot be confirmed again before retirement (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.capture.mockReturnValueOnce({ status: 0, output: "[]", stdout: "[]", stderr: "" }); + h.capture.mockReturnValue({ status: 1, output: "", stdout: "", stderr: "gateway lost" }); + expect(h.run).toThrow(/presence as unknown/u); + expect(h.snapshot()).toEqual(before); + }); + + it("finishes on retry after recovery record retirement fails (#12260)", async () => { + const h = await setup(); + const rename = fs.renameSync; + const failure = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => + String(destination) === h.session.RETAINED_SANDBOX_RECOVERY_FILE + ? (() => { + throw new Error("recovery storage unavailable"); + })() + : rename(source, destination), + ); + expect(h.run).toThrow(/storage unavailable/u); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.loadSession()?.cancellationRecovery).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([h.record]); + failure.mockRestore(); + + expect(h.run()).toBe(true); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + }); +}); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts new file mode 100644 index 00000000000..daca63ba46a --- /dev/null +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isDeepStrictEqual } from "node:util"; + +import { dockerRun } from "../../../adapters/docker/run"; +import { dockerContextIsDefaultFromBuild } from "../../../adapters/docker/client-isolation"; +import { normalizeInferenceSelection } from "../../../inference/selection"; +import { MANAGED_IMAGE_AGENTS } from "../../../onboard/managed-image/agents"; +import { managedStartupStateRootOwnership } from "../../../onboard/managed-startup/state-roots"; +import { registryEntryGatewayPort } from "../../../state/gateway-registry"; +import type * as OnboardSession from "../../../state/onboard-session"; +import { resolveNemoclawStateGatewayPort } from "../../../state/paths"; +import type * as Registry from "../../../state/registry"; +import { + classifySandboxInferenceRouteReservation, + isPendingReservationForSession, + isRouteOnlySandboxReservation, +} from "../../../state/registry/route-reservation"; +import { resolveGatewayCleanupRuntimeProviderId } from "../destroy-gateway"; +import { + classifyDestroyContainerIdentity, + observeDestroyContainerIdentity, + type DestroySandboxPresence, +} from "../destroy-presence"; + +type Recovery = OnboardSession.RetainedSandboxRecoveryRecord; +type RecoveryState = { + observeSandbox(gatewayName: string): DestroySandboxPresence; + timeoutMs: number; + session: Pick< + typeof OnboardSession, + | "withOwnedOnboardLock" + | "loadSession" + | "listRetainedSandboxRecoveryRecords" + | "retainedSandboxRecoveryMatchesSession" + | "resolveRetainedSandboxRecovery" + >; + registry: Pick; +}; + +function unpublished(entry: Registry.SandboxEntry | null): boolean { + return ( + entry === null || + (isRouteOnlySandboxReservation(entry) && + entry.pendingCreateIdentity === undefined && + entry.lifecycleGeneration === undefined && + entry.lifecycleLiveIdentityFingerprint === undefined) + ); +} + +function refuse(name: string, reason: string): never { + throw new Error( + `Cannot reconcile retained sandbox '${name}': ${reason}. No sandbox resources were removed. ` + + "Recovery remains unresolved; correct the reported condition, then rerun destroy.", + ); +} + +function requireGatewayAbsence(record: Recovery, state: RecoveryState): void { + const { sandboxName, gatewayName } = record; + const presence = state.observeSandbox(gatewayName); + if (presence !== "absent") { + refuse(sandboxName, `the owning OpenShell gateway reports sandbox presence as ${presence}`); + } +} + +function requireAbsence(record: Recovery, state: RecoveryState): void { + const { sandboxName } = record; + requireGatewayAbsence(record, state); + const containers = classifyDestroyContainerIdentity( + sandboxName, + observeDestroyContainerIdentity(sandboxName, (args, options) => + dockerRun(["--context", "default", ...args], options), + ), + ); + if (containers.status !== "clear" || containers.identity !== null) { + refuse(sandboxName, "the container runtime did not confirm sandbox absence"); + } + const volumes = dockerRun(["--context", "default", "volume", "ls", "--format", "{{.Name}}"], { + ignoreError: true, + suppressOutput: true, + timeout: state.timeoutMs, + }); + if (volumes.status !== 0 || String(volumes.stderr ?? "").trim()) { + refuse(sandboxName, "the container runtime could not inspect retained volumes"); + } + const names = String(volumes.stdout ?? "") + .split(/\r?\n/u) + .filter(Boolean); + const reservedNames = MANAGED_IMAGE_AGENTS.flatMap((agent) => + managedStartupStateRootOwnership({ agent, sandboxName }).map((root) => root.resourceIdentity), + ); + if ( + names.some( + (name) => !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u.test(name) || reservedNames.includes(name), + ) + ) { + refuse(sandboxName, "retained volume absence is not established"); + } + requireGatewayAbsence(record, state); +} + +function requireReservationOwner( + record: Recovery, + entry: Registry.SandboxEntry, + session: OnboardSession.Session | null, + sessionState: RecoveryState["session"], +): void { + if ( + session?.status !== "recovery_required" || + session.sandboxName !== record.sandboxName || + session.cancellationRecovery?.reason !== record.reason || + !sessionState.retainedSandboxRecoveryMatchesSession(record, session) || + !isPendingReservationForSession(entry, session.sessionId) || + registryEntryGatewayPort({ + name: entry.name, + gatewayName: entry.gatewayName, + gatewayPort: entry.gatewayPort, + }) !== record.gatewayPort || + entry.gatewayName !== record.gatewayName || + entry.hostLocalInferenceReceipt != null || + entry.nativeNvidiaProviderAttachment !== undefined || + classifySandboxInferenceRouteReservation( + { + sandboxName: record.sandboxName, + gatewayName: record.gatewayName, + sessionId: session.sessionId, + selection: normalizeInferenceSelection(entry), + }, + entry, + ).kind !== "owned" + ) { + refuse( + record.sandboxName, + "the unpublished reservation has conflicting ownership or retained resources", + ); + } +} + +/** Retire only local recovery metadata; a missing identity never authorizes resource deletion. */ +export function reconcileIdentityFreeRecovery( + sandboxName: string, + observedRecords: readonly Recovery[], + owningGatewayPort: number, + state: RecoveryState, +): boolean { + const { session: sessionState, registry } = state; + if (process.platform !== "linux") return false; + const candidates = observedRecords.filter((record) => record.sandboxName === sandboxName); + if (!candidates.some((record) => record.sandboxIdentityFingerprint === null)) return false; + const observedEntry = registry.getSandbox(sandboxName); + if (!unpublished(observedEntry)) return false; + + return sessionState.withOwnedOnboardLock("nemoclaw retained recovery reconciliation", () => { + const record = candidates[0]; + if (!record || candidates.length !== 1 || record.sandboxIdentityFingerprint !== null) { + refuse(sandboxName, "exactly one identity-free recovery record is required"); + } + if ( + record.gatewayPort !== owningGatewayPort || + record.gatewayPort !== resolveNemoclawStateGatewayPort() || + registryEntryGatewayPort({ name: sandboxName, gatewayName: record.gatewayName }) !== + record.gatewayPort || + record.resources.sandboxScopedProviders.length > 0 + ) { + refuse( + sandboxName, + "the recovery gateway or sandbox-scoped resources could not be qualified", + ); + } + const entry = registry.getSandbox(sandboxName); + if (!isDeepStrictEqual(entry, observedEntry) || !unpublished(entry)) { + refuse(sandboxName, "the registry changed before reconciliation"); + } + if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), sessionState); + if ( + resolveGatewayCleanupRuntimeProviderId(record.gatewayName, entry?.openshellDriver, { + requireOwnedRuntime: true, + }) !== "docker" + ) { + refuse(sandboxName, "the owning Docker runtime could not be established"); + } + // Native Linux Docker gateways use the local default daemon. An ambient override is not absence proof. + if (!dockerContextIsDefaultFromBuild(process.env)) { + refuse( + sandboxName, + "the Docker observation target is not the native gateway's default daemon", + ); + } + requireAbsence(record, state); + // The onboarding lock prevents a new create while CAS protects the observed reservation. + const currentRecords = sessionState + .listRetainedSandboxRecoveryRecords() + .filter((current) => current.sandboxName === sandboxName); + if (!isDeepStrictEqual(currentRecords, candidates)) { + refuse(sandboxName, "the recovery record changed during absence verification"); + } + if (entry) { + requireReservationOwner(record, entry, sessionState.loadSession(), sessionState); + if (!registry.removeSandboxRouteReservationIfCurrent(entry)) { + refuse(sandboxName, "the registry changed during absence verification"); + } + } + if (registry.getSandbox(sandboxName) !== null) { + refuse(sandboxName, "a registry entry appeared during reconciliation"); + } + // Keep the independent record until both earlier local writes succeed so a retry can finish. + if (!sessionState.resolveRetainedSandboxRecovery(record)) { + refuse(sandboxName, "the recovery record could not be retired"); + } + return true; + }); +} diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 049ae3b3bd9..1763a815bed 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -136,6 +136,13 @@ runtime mutation | **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts`; `rotateSandboxToken` in `src/lib/sandbox/config-rotate-token.ts` | A named sandbox registry route selects the provider and credential binding whenever that registry row exists; an incomplete route fails closed. Only a sandbox with no registry row falls back to the onboard session, which must name exactly the requested sandbox; a different or null `sandboxName` is rejected before any credential side effect. An endpoint-backed fallback session without a concrete provider type is also rejected before prompting. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | OpenShell provider update runs first, with provider create as a fallback using the provider type owned by onboarding metadata and the registered gateway-reachable endpoint; an endpoint-backed provider without that metadata fails closed instead of being recreated incompletely. After provider rotation succeeds, `saveCredential` stages the value in the current process and audit runs last. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | No rollback follows a successful provider update; a later credential-staging or audit failure can report failure after the credential is already active. Covered by `test/security/config-rotate-token.test.ts` and the rotate-token case in `test/security/config-set-nested-ssrf.test.ts`. | | **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers launch OpenShell service forwarding only on free host ports. OpenShell ends each forward when its sandbox or gateway becomes unavailable. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, and gateway provider state. An interrupted onboarding session records the selected resource values or an explicit OpenShell-default choice; the resolved create intent remains process-local. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution effect transaction/checkpoint. | +For an unpublished recovery record without a sandbox identity, native Linux Docker can retire only local metadata after verified absence. +The owning gateway must report sandbox absence, and the default Docker daemon must report no matching containers or managed state volumes. +An existing reservation must match its recovery-only session; a retry after reservation removal preserves unrelated sessions. +This path requires an owned gateway runtime marker and preserves runtime resources. +Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keeps recovery blocked. +`actions/sandbox/lifecycle/retained-recovery.test.ts` covers these transitions, including interrupted metadata retirement. + ## Durable resumed recreate journal A resumed same-name replacement writes a secret-free journal before the lower create path can delete the source sandbox. diff --git a/src/lib/onboard/openshell-docker-sandbox-containers.ts b/src/lib/onboard/openshell-docker-sandbox-containers.ts index e6e0d4a699a..f2ed3de5242 100644 --- a/src/lib/onboard/openshell-docker-sandbox-containers.ts +++ b/src/lib/onboard/openshell-docker-sandbox-containers.ts @@ -223,12 +223,17 @@ type ExactDockerContainerCleanupDeps = { export function inspectDockerSandboxNameLabeledContainers( sandboxName: string, + inspect?: Parameters[2], ): DockerSandboxIdentityObservation { - return inspectDockerSandboxIdentities(`${OPENSHELL_SANDBOX_NAME_LABEL}=${sandboxName}`, { - managedBy: OPENSHELL_MANAGED_BY_LABEL, - workspace: OPENSHELL_SANDBOX_WORKSPACE_LABEL, - sandboxId: OPENSHELL_SANDBOX_ID_LABEL, - }); + return inspectDockerSandboxIdentities( + `${OPENSHELL_SANDBOX_NAME_LABEL}=${sandboxName}`, + { + managedBy: OPENSHELL_MANAGED_BY_LABEL, + workspace: OPENSHELL_SANDBOX_WORKSPACE_LABEL, + sandboxId: OPENSHELL_SANDBOX_ID_LABEL, + }, + inspect, + ); } function exactCleanupContainerIds( diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 0e6b24ff261..4c9f3d05dc9 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -1568,7 +1568,8 @@ function onboardLockContentionGuidance( return [lead, ...holderDetails, remediation].join(" "); } -function withOwnedOnboardLock(command: string, operation: () => T): T { +/** Hold the onboarding writer lock through one synchronous state transition. */ +export function withOwnedOnboardLock(command: string, operation: () => T): T { const managesOnboardLock = heldLockHandle === null; if (managesOnboardLock) { const lock = acquireOnboardLock(command); From 5eb77e8366a3fb8d0fd3b6f88fb6a663badb30b1 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Thu, 8 Oct 2026 20:27:01 +0530 Subject: [PATCH 2/9] fix(sandbox): reuse gateway resolver in recovery Pass the existing preflight resolver into retained recovery so the gateway registry stays within its dependency budget after main merges. Preserve rejection of conflicting gateway names and ports. Refs #12260 Signed-off-by: Hung Le --- src/lib/actions/sandbox/destroy-preflight.ts | 6 +++++- .../sandbox/lifecycle/retained-recovery.test.ts | 12 ++++++++++++ .../sandbox/lifecycle/retained-recovery.ts | 15 ++++++++------- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-preflight.ts b/src/lib/actions/sandbox/destroy-preflight.ts index 4c1358d6ea9..91617282cce 100644 --- a/src/lib/actions/sandbox/destroy-preflight.ts +++ b/src/lib/actions/sandbox/destroy-preflight.ts @@ -62,7 +62,10 @@ export function reconcileIdentityFreeRecovery( sandboxName: string, records: Parameters[1], owningGatewayPort: number, - state: Omit[3], "observeSandbox" | "timeoutMs"> & { + state: Omit< + Parameters[3], + "observeSandbox" | "timeoutMs" | "registryEntryGatewayPort" + > & { captureOpenshell?: typeof import("../../adapters/openshell/runtime").captureOpenshell; }, ): boolean { @@ -73,6 +76,7 @@ export function reconcileIdentityFreeRecovery( ).captureOpenshell; return reconcileRetainedMetadata(sandboxName, records, owningGatewayPort, { ...state, + registryEntryGatewayPort, timeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, observeSandbox: (gatewayName) => classifyDestroySandboxPresence( diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index 6ffa396cd2b..d02ac0ec1b5 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -345,6 +345,18 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", ).toEqual(["alpha-provider"]); }); + it("preserves metadata when the reservation gateway name and port conflict (#12260)", async () => { + const h = await setup(); + expect(h.registry.updateSandbox("alpha", { gatewayPort: 8080 })).toBe(true); + const before = h.snapshot(); + + expect(h.run).toThrow(/conflicting gateway identity/u); + + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + expect(h.volumes).not.toHaveBeenCalled(); + }); + it("preserves a replacement session after registry retirement (#12260)", async () => { const h = await setup(); h.registry.removeSandboxRouteReservationIfCurrent(h.registry.getSandbox("alpha")!); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts index daca63ba46a..debfdf7142b 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -8,7 +8,7 @@ import { dockerContextIsDefaultFromBuild } from "../../../adapters/docker/client import { normalizeInferenceSelection } from "../../../inference/selection"; import { MANAGED_IMAGE_AGENTS } from "../../../onboard/managed-image/agents"; import { managedStartupStateRootOwnership } from "../../../onboard/managed-startup/state-roots"; -import { registryEntryGatewayPort } from "../../../state/gateway-registry"; +import type { registryEntryGatewayPort } from "../../../state/gateway-registry"; import type * as OnboardSession from "../../../state/onboard-session"; import { resolveNemoclawStateGatewayPort } from "../../../state/paths"; import type * as Registry from "../../../state/registry"; @@ -27,6 +27,7 @@ import { type Recovery = OnboardSession.RetainedSandboxRecoveryRecord; type RecoveryState = { observeSandbox(gatewayName: string): DestroySandboxPresence; + registryEntryGatewayPort: typeof registryEntryGatewayPort; timeoutMs: number; session: Pick< typeof OnboardSession, @@ -104,15 +105,15 @@ function requireReservationOwner( record: Recovery, entry: Registry.SandboxEntry, session: OnboardSession.Session | null, - sessionState: RecoveryState["session"], + state: RecoveryState, ): void { if ( session?.status !== "recovery_required" || session.sandboxName !== record.sandboxName || session.cancellationRecovery?.reason !== record.reason || - !sessionState.retainedSandboxRecoveryMatchesSession(record, session) || + !state.session.retainedSandboxRecoveryMatchesSession(record, session) || !isPendingReservationForSession(entry, session.sessionId) || - registryEntryGatewayPort({ + state.registryEntryGatewayPort({ name: entry.name, gatewayName: entry.gatewayName, gatewayPort: entry.gatewayPort, @@ -159,7 +160,7 @@ export function reconcileIdentityFreeRecovery( if ( record.gatewayPort !== owningGatewayPort || record.gatewayPort !== resolveNemoclawStateGatewayPort() || - registryEntryGatewayPort({ name: sandboxName, gatewayName: record.gatewayName }) !== + state.registryEntryGatewayPort({ name: sandboxName, gatewayName: record.gatewayName }) !== record.gatewayPort || record.resources.sandboxScopedProviders.length > 0 ) { @@ -172,7 +173,7 @@ export function reconcileIdentityFreeRecovery( if (!isDeepStrictEqual(entry, observedEntry) || !unpublished(entry)) { refuse(sandboxName, "the registry changed before reconciliation"); } - if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), sessionState); + if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); if ( resolveGatewayCleanupRuntimeProviderId(record.gatewayName, entry?.openshellDriver, { requireOwnedRuntime: true, @@ -196,7 +197,7 @@ export function reconcileIdentityFreeRecovery( refuse(sandboxName, "the recovery record changed during absence verification"); } if (entry) { - requireReservationOwner(record, entry, sessionState.loadSession(), sessionState); + requireReservationOwner(record, entry, sessionState.loadSession(), state); if (!registry.removeSandboxRouteReservationIfCurrent(entry)) { refuse(sandboxName, "the registry changed during absence verification"); } From f7fd9d07e3f46c6cbebc7796212ef7878d2edca2 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Thu, 8 Oct 2026 23:51:30 +0530 Subject: [PATCH 3/9] fix(sandbox): finish identity-free recovery cleanup Retire legacy Shields state before releasing recovery authority so failed retirement remains retryable. Exercise the destroy command with real recovery metadata and document the native Docker limits. Refs #12260 Signed-off-by: Hung Le --- docs/reference/commands.mdx | 18 ++- src/lib/actions/sandbox/destroy.ts | 7 ++ .../lifecycle/retained-recovery.test.ts | 116 +++++++++++++++++- .../sandbox/lifecycle/retained-recovery.ts | 5 +- src/lib/onboard/lifecycle-contracts.md | 2 + 5 files changed, 144 insertions(+), 4 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index a77b702cd92..32a4beca645 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -531,13 +531,27 @@ Use the result from `destroy` to choose the next action: - If OpenShell reports the sandbox present, `destroy` preserves the record and removes no resources. OpenShell exposes no atomic delete-by-identity primitive. Neither NemoClaw nor manual inspection can bind a later mutable-name delete to the durable identity fingerprint. You can inspect the owning gateway for diagnosis, but do not delete the sandbox by mutable name. Live retained-sandbox removal is not supported yet. Use a different explicit sandbox name while this record remains blocked. - If OpenShell cannot determine whether the sandbox is present, `destroy` reports unknown presence, removes no resources, and preserves the recovery record. Correct the OpenShell gateway or list failure, then rerun `destroy`. -- If OpenShell confirms the sandbox is absent, `destroy` selects one retained record from its registry generation, gateway, create-attempt evidence, and available identity fingerprint. +- For the existing residual-cleanup path, `destroy` selects one retained record from its registry generation, gateway, create-attempt evidence, and available identity fingerprint. + Cleanup requires the owning OpenShell gateway to confirm sandbox absence. Before pending identity publication, it can instead select one record with a durable identity fingerprint when the pending reservation belongs to the recorded onboarding session, the saved session recovery evidence matches the record, and the registry has no lifecycle identity evidence. Provider and Docker cleanup then apply their own immutable identity checks. `destroy` removes only qualified residual resources and clears the matching recovery record only after verified cleanup. - If the recovery record is ambiguous or immutable runtime-identity verification fails, cleanup stops and the record remains. For Docker-backed sandboxes, a foreign container, changed Docker identity, or failed Docker probe has the same fail-closed result. -If OpenShell did not return a durable identity fingerprint, `destroy` cannot authorize deletion of a live sandbox. It can still select one recovery record that matches the immutable registry generation, gateway, and create-attempt evidence. It clears that record only after the owning gateway reports absence and verified residual cleanup succeeds. If the sandbox is present or presence is unknown, preserve the record and do not delete by mutable name. If NemoClaw could not save recovery evidence, preserve the registry entry and terminal output. +If OpenShell did not return a durable identity fingerprint, `destroy` cannot authorize deletion of a live sandbox. + +For an unpublished reservation without lifecycle identity evidence, `destroy` can clear local recovery metadata on native Linux with the default Docker daemon. +This path requires exactly one retained recovery record and a recorded gateway runtime marker that establishes Docker ownership. +The record must match the owning gateway. +That gateway must confirm sandbox absence, and Docker must confirm that no matching containers or managed state volumes remain. +An existing reservation must belong to the matching recovery-only onboarding session. +Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keep recovery blocked. +On success, `destroy` clears the matching local recovery metadata and releases the sandbox name without removing runtime resources. + +A record that matches immutable registry generation, gateway, and create-attempt evidence can instead use the existing residual-cleanup path. +That path clears the record only after the owning gateway reports absence and verified residual cleanup succeeds. +If the sandbox is present or presence is unknown, preserve the record and do not delete by mutable name. +If NemoClaw could not save recovery evidence, preserve the registry entry and terminal output. This fail-closed record keeps only the affected sandbox name unavailable. This command does not accept externally supplied identity authority. To onboard another sandbox while the record remains unresolved, supply a different explicit name: diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 32dff7eb79f..3b6794b7249 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -737,6 +737,13 @@ async function destroySandboxUnlocked( { session: onboardSession, registry, + ...(retireRemovedImmutabilityState + ? { + retireRemovedImmutabilityState: () => { + retireRemovedImmutabilityStateRecord(sandboxName, "sandbox-destroyed"); + }, + } + : {}), }, ) ) { diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index d02ac0ec1b5..e5a9f852fd3 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -19,7 +19,7 @@ const emptyDockerResult = { beforeAll(async () => { // Load the shared CLI graph before timing recovery operations in each isolated state root. - await import("../destroy-preflight"); + await import("../destroy"); }); beforeEach(() => { @@ -117,7 +117,121 @@ async function setup(port = 19260) { }; } +async function setupDestroy() { + const h = await setup(); + const preflight = await import("../destroy-preflight"); + const reconcile = preflight.reconcileIdentityFreeRecovery; + vi.spyOn(preflight, "reconcileIdentityFreeRecovery").mockImplementation( + (name, records, port, state) => + reconcile(name, records, port, { ...state, captureOpenshell: h.capture }), + ); + const ordinaryDestroy = vi + .spyOn(preflight, "prepareSandboxDestroy") + .mockRejectedValue(new Error("Unexpected resource cleanup during metadata recovery")); + const confirmation = await import("../destroy-confirmation"); + vi.spyOn(confirmation, "confirmSandboxDestroy").mockResolvedValue(true); + const exit = vi.spyOn(process, "exit").mockImplementation(((code: number) => { + throw new Error(`process.exit(${code})`); + }) as never); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "error").mockImplementation(() => undefined); + const { destroySandbox } = await import("../destroy"); + const { resolveNemoclawStateDir } = await import("../../../state/paths"); + const { enforceRemovedImmutabilityMigrationBoundary } = + await import("../../../state/migrations/removed-immutability"); + const stateDir = resolveNemoclawStateDir(); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + return { + ...h, + destroy: () => destroySandbox("alpha", { yes: true }), + ordinaryDestroy, + exit, + log, + legacyState: path.join(stateDir, "shields-alpha.json"), + assertMigrationClear: () => enforceRemovedImmutabilityMigrationBoundary("alpha"), + }; +} + describe.skipIf(process.platform !== "linux")("identity-free retained recovery", () => { + it("releases the retained name through destroy without entering resource cleanup (#12260)", async () => { + const h = await setupDestroy(); + + await expect(h.destroy()).resolves.toBeUndefined(); + + expect(h.capture).toHaveBeenCalledWith( + ["sandbox", "list", "-g", h.record.gatewayName, "--output", "json"], + expect.objectContaining({ ignoreError: true, includeStreams: true }), + ); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.session.loadSession()?.cancellationRecovery).toBeNull(); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.exit).not.toHaveBeenCalled(); + expect(h.log).toHaveBeenCalledWith( + " Cleared retained recovery for 'alpha'. No sandbox resources were removed.", + ); + }); + + it("retires removed Shields state when destroy clears identity-free recovery (#12260)", async () => { + const h = await setupDestroy(); + fs.writeFileSync(h.legacyState, "{}\n", { mode: 0o600 }); + expect(h.assertMigrationClear).toThrow(/state record from the removed Shields feature/u); + + await expect(h.destroy()).resolves.toBeUndefined(); + + expect(fs.existsSync(h.legacyState)).toBe(false); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.exit).not.toHaveBeenCalled(); + expect(h.assertMigrationClear).not.toThrow(); + }); + + it("preserves recovery for retry when removed Shields state retirement fails (#12260)", async () => { + const h = await setupDestroy(); + fs.writeFileSync(h.legacyState, "{}\n", { mode: 0o600 }); + expect(h.assertMigrationClear).toThrow(/state record from the removed Shields feature/u); + const before = h.snapshot(); + const rename = fs.renameSync; + const failure = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => + String(source) === h.legacyState + ? (() => { + throw new Error("legacy state retirement unavailable"); + })() + : rename(source, destination), + ); + + await expect(h.destroy()).rejects.toThrow("process.exit(1)"); + + expect(h.snapshot()).toEqual(before); + expect(fs.existsSync(h.legacyState)).toBe(true); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.log).not.toHaveBeenCalledWith(expect.stringContaining("Cleared retained recovery")); + failure.mockRestore(); + + await expect(h.destroy()).resolves.toBeUndefined(); + + expect(fs.existsSync(h.legacyState)).toBe(false); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + }); + + it("preserves legacy state and recovery when destroy cannot verify gateway absence (#12260)", async () => { + const h = await setupDestroy(); + fs.writeFileSync(h.legacyState, "{}\n", { mode: 0o600 }); + expect(h.assertMigrationClear).toThrow(/state record from the removed Shields feature/u); + const before = h.snapshot(); + h.capture.mockReturnValue({ status: 1, output: "", stdout: "", stderr: "gateway unavailable" }); + + await expect(h.destroy()).rejects.toThrow("process.exit(1)"); + + expect(fs.existsSync(h.legacyState)).toBe(true); + expect(h.snapshot()).toEqual(before); + expect(h.volumes).not.toHaveBeenCalled(); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + }); + it.each([8080, 19260])( "releases the retained sandbox name after verified absence on gateway port %s (#12260)", async (port) => { diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts index debfdf7142b..61fd2603dd7 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -28,6 +28,7 @@ type Recovery = OnboardSession.RetainedSandboxRecoveryRecord; type RecoveryState = { observeSandbox(gatewayName: string): DestroySandboxPresence; registryEntryGatewayPort: typeof registryEntryGatewayPort; + retireRemovedImmutabilityState?: () => void; timeoutMs: number; session: Pick< typeof OnboardSession, @@ -196,8 +197,10 @@ export function reconcileIdentityFreeRecovery( if (!isDeepStrictEqual(currentRecords, candidates)) { refuse(sandboxName, "the recovery record changed during absence verification"); } + if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); + // Legacy state retirement must succeed while the recovery authority is still available for retry. + state.retireRemovedImmutabilityState?.(); if (entry) { - requireReservationOwner(record, entry, sessionState.loadSession(), state); if (!registry.removeSandboxRouteReservationIfCurrent(entry)) { refuse(sandboxName, "the registry changed during absence verification"); } diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 1763a815bed..5731fb0091b 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -140,6 +140,8 @@ For an unpublished recovery record without a sandbox identity, native Linux Dock The owning gateway must report sandbox absence, and the default Docker daemon must report no matching containers or managed state volumes. An existing reservation must match its recovery-only session; a retry after reservation removal preserves unrelated sessions. This path requires an owned gateway runtime marker and preserves runtime resources. +When legacy Shields state exists, its retirement must succeed before registry and recovery metadata are removed. +A retirement failure keeps recovery metadata available for retry. Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keeps recovery blocked. `actions/sandbox/lifecycle/retained-recovery.test.ts` covers these transitions, including interrupted metadata retirement. From 2b385932045f4aa3af34bd841a94a0f1a1ba5e69 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Fri, 9 Oct 2026 10:00:55 +0530 Subject: [PATCH 4/9] fix(cli): admit retained recovery retries without registry rows Route destroy from the selected root's identity-free recovery record after reservation retirement. Keep ownership and absence validation in the lifecycle owner and document the owning-port recovery command. Add regressions for retry admission and isolation from other roots. Refs #12260 Signed-off-by: Hung Le --- docs/reference/commands.mdx | 11 +++++ .../lifecycle/retained-recovery.test.ts | 14 +++++++ src/lib/cli/public-dispatch.ts | 10 ++++- src/lib/onboard/lifecycle-contracts.md | 2 + src/lib/registry-recovery-action.ts | 9 ++++ test/cli/dispatch-recovery-routing.test.ts | 42 +++++++++++++++++++ test/support/public-dispatch-test-harness.ts | 10 ++++- 7 files changed, 95 insertions(+), 3 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 32a4beca645..9a39f32a7e8 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -546,7 +546,18 @@ The record must match the owning gateway. That gateway must confirm sandbox absence, and Docker must confirm that no matching containers or managed state volumes remain. An existing reservation must belong to the matching recovery-only onboarding session. Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keep recovery blocked. + +Run this recovery command with the gateway port used by the failed onboarding attempt. +For example, if onboarding used port `19260`: + +```bash +NEMOCLAW_GATEWAY_PORT=19260 $$nemoclaw destroy --yes +``` + +This selects the existing state root for that gateway. On success, `destroy` clears the matching local recovery metadata and releases the sandbox name without removing runtime resources. +If a local metadata write fails, resolve the reported write error. +Then rerun the same command with that port, even if the reservation was removed. A record that matches immutable registry generation, gateway, and create-attempt evidence can instead use the existing residual-cleanup path. That path clears the record only after the owning gateway reports absence and verified residual cleanup succeeds. diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index e5a9f852fd3..a881821450f 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -513,6 +513,7 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", it("finishes on retry after recovery record retirement fails (#12260)", async () => { const h = await setup(); + const { hasIdentityFreeRetainedRecovery } = await import("../../../registry-recovery-action"); const rename = fs.renameSync; const failure = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => String(destination) === h.session.RETAINED_SANDBOX_RECOVERY_FILE @@ -525,9 +526,22 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.registry.getSandbox("alpha")).toBeNull(); expect(h.session.loadSession()?.cancellationRecovery).toBeNull(); expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([h.record]); + expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(true); failure.mockRestore(); expect(h.run()).toBe(true); expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(false); + }); + + it("does not admit destroy from recovery retained in another gateway root (#12260)", async () => { + const h = await setup(19260); + const before = h.snapshot(); + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "8080"); + vi.resetModules(); + const { hasIdentityFreeRetainedRecovery } = await import("../../../registry-recovery-action"); + + expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(false); + expect(h.snapshot()).toEqual(before); }); }); diff --git a/src/lib/cli/public-dispatch.ts b/src/lib/cli/public-dispatch.ts index 7b941d079b8..c5f0a685009 100644 --- a/src/lib/cli/public-dispatch.ts +++ b/src/lib/cli/public-dispatch.ts @@ -561,9 +561,15 @@ async function dispatchSandboxArgv( // sandbox missing. The printed guidance runs it after `destroy --yes` // removed the registry entry, so registry recovery here can only exit with // "does not exist" or start a gateway the retirement never needs. + // An identity-free destroy retry can also retain only its local recovery + // record after reservation retirement. Its lifecycle owner still checks + // ownership and absence; admission must not require recreating a registry row. if ( - isRebuildRecoveryRetirement(requestedSandboxAction, requestedSandboxActionArgs) && - !registry().getSandbox(cmd) + (isRebuildRecoveryRetirement(requestedSandboxAction, requestedSandboxActionArgs) && + !registry().getSandbox(cmd)) || + (requestedSandboxAction === "destroy" && + !findKnownSandboxEntry(cmd) && + registryRecovery().hasIdentityFreeRetainedRecovery(cmd)) ) { validateName(cmd, "sandbox name"); await runPublicTranslationResult( diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 5731fb0091b..31f15658e40 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -142,6 +142,8 @@ An existing reservation must match its recovery-only session; a retry after rese This path requires an owned gateway runtime marker and preserves runtime resources. When legacy Shields state exists, its retirement must succeed before registry and recovery metadata are removed. A retirement failure keeps recovery metadata available for retry. +The public CLI admits an identity-free destroy retry from the selected root's retained record even after reservation retirement. +The lifecycle owner still validates recovery authority and absence before any metadata retirement. Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keeps recovery blocked. `actions/sandbox/lifecycle/retained-recovery.test.ts` covers these transitions, including interrupted metadata retirement. diff --git a/src/lib/registry-recovery-action.ts b/src/lib/registry-recovery-action.ts index 3d243c0653a..c58f83f5f84 100644 --- a/src/lib/registry-recovery-action.ts +++ b/src/lib/registry-recovery-action.ts @@ -39,6 +39,15 @@ export type RecoveredSandboxEntry = SandboxEntry & { type Session = ReturnType; +/** Route a metadata-only destroy retry using recovery retained in the selected state root. */ +export function hasIdentityFreeRetainedRecovery(sandboxName: string): boolean { + return onboardSession + .listRetainedSandboxRecoveryRecords() + .some( + (record) => record.sandboxName === sandboxName && record.sandboxIdentityFingerprint === null, + ); +} + type RecoveredSandboxMetadata = Partial< Pick< SandboxEntry, diff --git a/test/cli/dispatch-recovery-routing.test.ts b/test/cli/dispatch-recovery-routing.test.ts index 3528dadd9b0..db013962bdf 100644 --- a/test/cli/dispatch-recovery-routing.test.ts +++ b/test/cli/dispatch-recovery-routing.test.ts @@ -14,6 +14,48 @@ afterEach(() => { }); describe("CLI recovery routing", () => { + it("routes destroy to retained recovery after its registry row is retired (#12260)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById, exitSpy }) => { + await dispatchCli(["alpha", "destroy", "--yes"]); + + expect(runOclifCommandById).toHaveBeenCalledWith( + "sandbox:destroy", + ["alpha", "--yes"], + expect.objectContaining({ publicSandboxName: "alpha" }), + ); + expect(recoverRegistryEntries).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }, + { retainedRecoverySandboxNames: ["alpha"] }, + ); + }); + + it("keeps missing-name checks for destroy without matching local recovery (#12260)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById, stderr }) => { + await expect(dispatchCli(["alpha", "destroy", "--yes"])).rejects.toThrow("process.exit:1"); + + expect(recoverRegistryEntries).toHaveBeenCalledWith({ requestedSandboxName: "alpha" }); + expect(runOclifCommandById).not.toHaveBeenCalled(); + expect(stderr.join("\n")).toContain("Sandbox 'alpha' does not exist."); + }, + { retainedRecoverySandboxNames: ["beta"] }, + ); + }); + + it("does not admit other sandbox actions from a retained recovery record (#12260)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById }) => { + await expect(dispatchCli(["alpha", "status"])).rejects.toThrow("process.exit:1"); + + expect(recoverRegistryEntries).toHaveBeenCalledWith({ requestedSandboxName: "alpha" }); + expect(runOclifCommandById).not.toHaveBeenCalled(); + }, + { retainedRecoverySandboxNames: ["alpha"] }, + ); + }); + it.each([ { argv: ["term"], diff --git a/test/support/public-dispatch-test-harness.ts b/test/support/public-dispatch-test-harness.ts index f707bfa8018..3aabea0597c 100644 --- a/test/support/public-dispatch-test-harness.ts +++ b/test/support/public-dispatch-test-harness.ts @@ -24,6 +24,7 @@ export type DirectPublicDispatchHarness = { migrateLegacyPortState: ReturnType; printSandboxConnectHelp: ReturnType; recoverRegistryEntries: ReturnType; + hasIdentityFreeRetainedRecovery: ReturnType; resetObservedCalls: () => void; runOclifArgv: ReturnType; runOclifCommandById: ReturnType; @@ -40,6 +41,8 @@ type DirectPublicDispatchOptions = { defaultSandbox?: string | null; /** Registered route reservations that are not ready or default-eligible. */ pendingSandboxNames?: readonly string[]; + /** Identity-free recovery records in the selected gateway's state root. */ + retainedRecoverySandboxNames?: readonly string[]; /** Args the sandbox-connect stub treats as connect flags (default: none). */ connectFlags?: readonly string[]; /** Legacy sandbox rows that belong to the selected gateway but are not migrated yet. */ @@ -143,6 +146,9 @@ export async function withDirectPublicDispatch( recoveredFromSession: false, recoveredFromGateway: 0, })); + const hasIdentityFreeRetainedRecovery = vi.fn((name: string) => + (options.retainedRecoverySandboxNames ?? []).includes(name), + ); const migrateLegacyPortState = vi.fn(() => { if (options.migrationError) throw options.migrationError; return { migratedSandboxNames: [], migratedSession: false, warnings: [] }; @@ -169,6 +175,7 @@ export async function withDirectPublicDispatch( listSandboxes.mockClear(); migrateLegacyPortState.mockClear(); recoverRegistryEntries.mockClear(); + hasIdentityFreeRetainedRecovery.mockClear(); runOclifArgv.mockClear(); runOclifCommandById.mockClear(); }; @@ -193,7 +200,7 @@ export async function withDirectPublicDispatch( }); } cacheModule(legacyPortMigrationPath, { hasMigratableLegacySandbox, migrateLegacyPortState }); - cacheModule(registryRecoveryPath, { recoverRegistryEntries }); + cacheModule(registryRecoveryPath, { recoverRegistryEntries, hasIdentityFreeRetainedRecovery }); cacheModule(oclifRunnerPath, { runOclifArgv, runOclifCommandById }); const connectFlags = new Set(options.connectFlags ?? []); cacheModule(sandboxConnectPath, { @@ -219,6 +226,7 @@ export async function withDirectPublicDispatch( migrateLegacyPortState, printSandboxConnectHelp, recoverRegistryEntries, + hasIdentityFreeRetainedRecovery, resetObservedCalls, runOclifArgv, runOclifCommandById, From e29121ae53bff2ef0b15be713e0f5dbce8c4505c Mon Sep 17 00:00:00 2001 From: Hung Le Date: Fri, 9 Oct 2026 14:05:20 +0530 Subject: [PATCH 5/9] test(sandbox): consolidate retained recovery coverage Exercise metadata release through destroy at both gateway ports and retain Shields completion checks in the failure-and-retry case. Remove duplicate success cases without changing runtime behavior. Shorten recovery guidance while preserving ownership, absence and retry requirements. Refs #12260 Signed-off-by: Hung Le --- docs/reference/commands.mdx | 19 +--- .../lifecycle/retained-recovery.test.ts | 104 +++++++----------- src/lib/onboard/lifecycle-contracts.md | 16 +-- 3 files changed, 52 insertions(+), 87 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 9a39f32a7e8..9f128f15682 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -540,28 +540,21 @@ Use the result from `destroy` to choose the next action: If OpenShell did not return a durable identity fingerprint, `destroy` cannot authorize deletion of a live sandbox. -For an unpublished reservation without lifecycle identity evidence, `destroy` can clear local recovery metadata on native Linux with the default Docker daemon. -This path requires exactly one retained recovery record and a recorded gateway runtime marker that establishes Docker ownership. -The record must match the owning gateway. -That gateway must confirm sandbox absence, and Docker must confirm that no matching containers or managed state volumes remain. -An existing reservation must belong to the matching recovery-only onboarding session. -Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keep recovery blocked. +For an unpublished reservation without lifecycle identity, `destroy` can clear local recovery metadata on native Linux with the default Docker daemon. +It requires exactly one matching retained record, a recorded Docker ownership marker, and sandbox absence confirmed by the owning gateway. +Docker must report no matching containers or managed state volumes. +Any reservation must match its recovery-only onboarding session; conflicting state, recorded sandbox-scoped providers, or additional resource ownership block recovery. -Run this recovery command with the gateway port used by the failed onboarding attempt. -For example, if onboarding used port `19260`: +Use the failed onboarding attempt's gateway port to select its state root, for example: ```bash NEMOCLAW_GATEWAY_PORT=19260 $$nemoclaw destroy --yes ``` -This selects the existing state root for that gateway. -On success, `destroy` clears the matching local recovery metadata and releases the sandbox name without removing runtime resources. +Success clears the matching recovery metadata and releases the sandbox name without removing runtime resources. If a local metadata write fails, resolve the reported write error. Then rerun the same command with that port, even if the reservation was removed. -A record that matches immutable registry generation, gateway, and create-attempt evidence can instead use the existing residual-cleanup path. -That path clears the record only after the owning gateway reports absence and verified residual cleanup succeeds. -If the sandbox is present or presence is unknown, preserve the record and do not delete by mutable name. If NemoClaw could not save recovery evidence, preserve the registry entry and terminal output. This fail-closed record keeps only the affected sandbox name unavailable. This command does not accept externally supplied identity authority. diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index a881821450f..96d194412d2 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -117,8 +117,8 @@ async function setup(port = 19260) { }; } -async function setupDestroy() { - const h = await setup(); +async function setupDestroy(port = 19260) { + const h = await setup(port); const preflight = await import("../destroy-preflight"); const reconcile = preflight.reconcileIdentityFreeRecovery; vi.spyOn(preflight, "reconcileIdentityFreeRecovery").mockImplementation( @@ -153,39 +153,45 @@ async function setupDestroy() { } describe.skipIf(process.platform !== "linux")("identity-free retained recovery", () => { - it("releases the retained name through destroy without entering resource cleanup (#12260)", async () => { - const h = await setupDestroy(); - - await expect(h.destroy()).resolves.toBeUndefined(); - - expect(h.capture).toHaveBeenCalledWith( - ["sandbox", "list", "-g", h.record.gatewayName, "--output", "json"], - expect.objectContaining({ ignoreError: true, includeStreams: true }), - ); - expect(h.registry.getSandbox("alpha")).toBeNull(); - expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); - expect(h.session.loadSession()?.cancellationRecovery).toBeNull(); - expect(h.ordinaryDestroy).not.toHaveBeenCalled(); - expect(h.exit).not.toHaveBeenCalled(); - expect(h.log).toHaveBeenCalledWith( - " Cleared retained recovery for 'alpha'. No sandbox resources were removed.", - ); - }); - - it("retires removed Shields state when destroy clears identity-free recovery (#12260)", async () => { - const h = await setupDestroy(); - fs.writeFileSync(h.legacyState, "{}\n", { mode: 0o600 }); - expect(h.assertMigrationClear).toThrow(/state record from the removed Shields feature/u); + it.each([8080, 19260])( + "releases the retained name through destroy on gateway port %s without resource cleanup (#12260)", + async (port) => { + const h = await setupDestroy(port); + expect(h.registry.getSandbox("alpha")?.gatewayPort).toBeUndefined(); + expect(h.record.sandboxIdentityFingerprint).toBeNull(); - await expect(h.destroy()).resolves.toBeUndefined(); + await expect(h.destroy()).resolves.toBeUndefined(); - expect(fs.existsSync(h.legacyState)).toBe(false); - expect(h.registry.getSandbox("alpha")).toBeNull(); - expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); - expect(h.ordinaryDestroy).not.toHaveBeenCalled(); - expect(h.exit).not.toHaveBeenCalled(); - expect(h.assertMigrationClear).not.toThrow(); - }); + expect(h.capture).toHaveBeenCalledWith( + ["sandbox", "list", "-g", h.record.gatewayName, "--output", "json"], + expect.objectContaining({ ignoreError: true, includeStreams: true }), + ); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.session.loadSession()).toMatchObject({ + status: "failed", + sandboxName: null, + cancellationRecovery: null, + }); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.exit).not.toHaveBeenCalled(); + expect(h.log).toHaveBeenCalledWith( + " Cleared retained recovery for 'alpha'. No sandbox resources were removed.", + ); + expect( + h.capture.mock.calls.every(([args]) => args[0] === "sandbox" && args[1] === "list"), + ).toBe(true); + expect(h.volumes.mock.calls.every(([args]) => args[2] === "volume" && args[3] === "ls")).toBe( + true, + ); + expect( + h.registry.reserveSandboxInferenceRoute("alpha", { + ...h.route, + reservationSessionId: "new-session", + }), + ).toBe(true); + }, + ); it("preserves recovery for retry when removed Shields state retirement fails (#12260)", async () => { const h = await setupDestroy(); @@ -215,6 +221,7 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.registry.getSandbox("alpha")).toBeNull(); expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.assertMigrationClear).not.toThrow(); }); it("preserves legacy state and recovery when destroy cannot verify gateway absence (#12260)", async () => { @@ -232,37 +239,6 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.ordinaryDestroy).not.toHaveBeenCalled(); }); - it.each([8080, 19260])( - "releases the retained sandbox name after verified absence on gateway port %s (#12260)", - async (port) => { - const h = await setup(port); - expect(h.registry.getSandbox("alpha")?.gatewayPort).toBeUndefined(); - expect(h.record.sandboxIdentityFingerprint).toBeNull(); - - expect(h.run()).toBe(true); - - expect(h.registry.getSandbox("alpha")).toBeNull(); - expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); - expect(h.session.loadSession()).toMatchObject({ - status: "failed", - sandboxName: null, - cancellationRecovery: null, - }); - expect( - h.capture.mock.calls.every(([args]) => args[0] === "sandbox" && args[1] === "list"), - ).toBe(true); - expect(h.volumes.mock.calls.every(([args]) => args[2] === "volume" && args[3] === "ls")).toBe( - true, - ); - expect( - h.registry.reserveSandboxInferenceRoute("alpha", { - ...h.route, - reservationSessionId: "new-session", - }), - ).toBe(true); - }, - ); - it.each([ ["failed", { status: 1, output: "", stdout: "[]", stderr: "connection refused" }], ["malformed", { status: 0, output: "invalid", stdout: "invalid", stderr: "" }], diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 31f15658e40..14b980fc4aa 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -136,16 +136,12 @@ runtime mutation | **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts`; `rotateSandboxToken` in `src/lib/sandbox/config-rotate-token.ts` | A named sandbox registry route selects the provider and credential binding whenever that registry row exists; an incomplete route fails closed. Only a sandbox with no registry row falls back to the onboard session, which must name exactly the requested sandbox; a different or null `sandboxName` is rejected before any credential side effect. An endpoint-backed fallback session without a concrete provider type is also rejected before prompting. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | OpenShell provider update runs first, with provider create as a fallback using the provider type owned by onboarding metadata and the registered gateway-reachable endpoint; an endpoint-backed provider without that metadata fails closed instead of being recreated incompletely. After provider rotation succeeds, `saveCredential` stages the value in the current process and audit runs last. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | No rollback follows a successful provider update; a later credential-staging or audit failure can report failure after the credential is already active. Covered by `test/security/config-rotate-token.test.ts` and the rotate-token case in `test/security/config-set-nested-ssrf.test.ts`. | | **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers launch OpenShell service forwarding only on free host ports. OpenShell ends each forward when its sandbox or gateway becomes unavailable. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, and gateway provider state. An interrupted onboarding session records the selected resource values or an explicit OpenShell-default choice; the resolved create intent remains process-local. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution effect transaction/checkpoint. | -For an unpublished recovery record without a sandbox identity, native Linux Docker can retire only local metadata after verified absence. -The owning gateway must report sandbox absence, and the default Docker daemon must report no matching containers or managed state volumes. -An existing reservation must match its recovery-only session; a retry after reservation removal preserves unrelated sessions. -This path requires an owned gateway runtime marker and preserves runtime resources. -When legacy Shields state exists, its retirement must succeed before registry and recovery metadata are removed. -A retirement failure keeps recovery metadata available for retry. -The public CLI admits an identity-free destroy retry from the selected root's retained record even after reservation retirement. -The lifecycle owner still validates recovery authority and absence before any metadata retirement. -Conflicting state, recorded sandbox-scoped providers, or additional resource ownership in the reservation keeps recovery blocked. -`actions/sandbox/lifecycle/retained-recovery.test.ts` covers these transitions, including interrupted metadata retirement. +For identity-free recovery on native Linux, `actions/sandbox/lifecycle/retained-recovery.ts` owns local metadata retirement and preserves runtime resources. +It requires a recorded Docker runtime owner, owning-gateway absence, and no matching containers or managed state volumes on the default Docker daemon. +Any reservation must match its recovery-only session; conflicting state, recorded sandbox-scoped providers, or additional resource ownership block retirement. +Legacy Shields state retires before registry and recovery metadata; interrupted retirement retains recovery authority for retry. +The public CLI admits `destroy` from the selected root's retained record after reservation removal; the lifecycle owner revalidates authority and absence and preserves unrelated sessions. +`actions/sandbox/lifecycle/retained-recovery.test.ts` covers completion, refusal, and retry. ## Durable resumed recreate journal From ff1fbacdb47c6ba3155b8f9c67defc96ed777776 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Fri, 9 Oct 2026 15:03:29 +0530 Subject: [PATCH 6/9] docs(onboard): distinguish metadata-only retained recovery Limit the journey matrix identity checks to residual resource cleanup. Reference the existing ownership and absence contract for identity-free metadata retirement without runtime deletion. Refs #12260 Signed-off-by: Hung Le --- src/lib/onboard/lifecycle-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 14b980fc4aa..7c4d7fd0696 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -125,7 +125,7 @@ runtime mutation | Journey and entry | Desired state, planning, and assembly | Visible and destructive boundaries | Checkpoint and secret boundary | Compensation, coverage, and gaps | |---|---|---|---|---| -| **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, messaging selection and plan reconciliation complete before web-search or messaging provider registration. Each validated provider group is then created or updated and checkpointed before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of web-search and messaging providers registered for resume; real values remain process- or gateway-bound. | Readiness, post-create policy verification, dashboard forwarding, and cancellation failures preserve the live sandbox and an independent identity-bound recovery record. A later `destroy` refuses mutable-name deletion while that sandbox is live. Recovery remains blocked while the sandbox is present or its presence is unknown. After OpenShell authoritatively reports absence, destroy uses the record to qualify immutable runtime identity and, for Docker-backed sandboxes, exact container identities before residual cleanup and record retirement. A different explicit sandbox name starts a fresh session without changing the retained record. Exact provider-owned GPU cleanup can proceed through its owner receipt. NemoClaw attempts to remove temporary policy and build-context sources and reports cleanup failures with the onboarding error; post-create failures retain recovery state. Cancellation before sandbox creation can leave the session resumable. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, policy-authority, destroy, and retained-recovery tests. Gap: gateway upserts can outlive a failed or interrupted create. | +| **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, messaging selection and plan reconciliation complete before web-search or messaging provider registration. Each validated provider group is then created or updated and checkpointed before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of web-search and messaging providers registered for resume; real values remain process- or gateway-bound. | Readiness, post-create policy verification, dashboard forwarding, and cancellation failures preserve the live sandbox and an independent retained-recovery record. A later `destroy` refuses mutable-name deletion while that sandbox is live. Recovery remains blocked while the sandbox is present or its presence is unknown. After OpenShell confirms absence, residual cleanup and record retirement require immutable runtime identity and, for Docker-backed sandboxes, exact container identities. Eligible identity-free records instead follow the native Linux Docker ownership and absence contract below, retiring only local metadata without deleting runtime resources. A different explicit sandbox name starts a fresh session without changing the retained record. Exact provider-owned GPU cleanup can proceed through its owner receipt. NemoClaw attempts to remove temporary policy and build-context sources and reports cleanup failures with the onboarding error; post-create failures retain recovery state. Cancellation before sandbox creation can leave the session resumable. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, policy-authority, destroy, and retained-recovery tests. Gap: gateway upserts can outlive a failed or interrupted create. | | **`--fresh` onboard** — `resolveOnboardEntryOptions`, `prepareFreshSession`, `createBaseImageResolutionContext` | Current flags/environment/prompts replace resumable intent. `--fresh` disables auto-resume and forces base-image resolution; it does not prove that the selected sandbox name is unused. | The first destructive effect is local: the prior onboard session is cleared before a new session is saved. A matching live sandbox can later reuse or recreate through the normal sandbox decision; `--fresh` does not itself delete it. | The new session and machine snapshot replace the old resume checkpoint. Credential and effect boundaries then match new onboard or live recreate. | The discarded resume checkpoint is not restored on later failure. Covered by `entry-options.test.ts`, `session-bootstrap.test.ts`, and base-image resolution tests. | | **Resume, re-onboard, or recreate** — `onboard()`, `prepareOnboardSession`, `decideSandboxResume`, live-sandbox handling in `createSandbox` | For `--resume`, the recorded session is authoritative and conflicting current name/provider/model/image/tool-disclosure hints are rejected. A new re-onboard run takes current flags, environment, and prompts as intent while registry/gateway state provides drift evidence. The machine resolves a complete secret-free create intent, including policy, messaging/provider, GPU, resource, disabled-channel, and agent inputs, before repair/removal or live recreation. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, and image removal. The recreate journal preserves the source registry row after deletion. Replacement registration commits the new row after readiness and validation. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Resume registry removal and `repair-and-recreate` occur only after complete intent validation. Temporary policy/build artifacts remain materialization effects after the delete boundary. | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. OpenClaw records completed sandbox name, web search, messaging, and resource choices with explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values remain outside the session. A missing process value can be rebound only when the same OpenClaw session recorded successfully registering that provider and its live provider name, provider type, and credential key still match; otherwise interactive resume requests it again and non-interactive resume exits with environment-variable guidance. Credentials are checked before mutation and again immediately before materialization. | A failed replacement keeps the source registry row. Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Checkpoint replay reuses an exact live sandbox after an interrupted create and backfills missing create/register receipts. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces, create-intent characterization, checkpoint replay and resume guards, and sandbox-handler crash recovery. Gaps: early backup asymmetry and no rebuild-style cross-effect rollback. | | **Rebuild or installer-driven upgrade** — `rebuildSandbox` in `rebuild-pipeline.ts`; `upgradeSandboxes` | The registry remains authoritative only for non-MCP sandbox settings. Agent-native configuration and live OpenShell state are the MCP sources. A matching session may fill guarded legacy non-MCP gaps only when its selection agrees; an unrelated/global session is never used. Ambient provider/model selection is quarantined by `isolateAmbientRecreateEnv`, apart from narrowly scoped legacy recovery. Legacy and custom-image rebuilds retain and fingerprint a prepared build context. Managed-image rebuilds instead stage an immutable image and startup-profile handoff, skip Dockerfile image preflight, and revalidate provider-bound workload authority before each deletion boundary. | Consent persistence, target-gateway selection/recovery, and target-preflight registry updates can precede disposable image build/probes. Backup is the first durable recovery checkpoint when available. MCP detach/scrub uses a bounded source-derived handoff and NIM stop is a destructive in-place effect before the **sandbox delete** boundary. Legacy and custom-image paths recheck prepared context and mutation-edge conditions before delete. Managed-image paths revalidate the provider-bound handoff before delete. | Durable checkpoints are the backup/recovery manifest when one exists and the rewritten recreate session; stale recovery can reach deletion without a manifest, making that session its first new durable checkpoint. MCP handoff state and rollback receipts are process-local. Credential metadata comes from the target or guarded fallback; raw credentials/providers are checked against current process/gateway state, while prepared installer recovery may reconstruct a missing gateway provider from a validated host credential. | In-process rollback best-effort restores source-derived MCP state, but process death after non-MCP delete can still lose non-MCP registry metadata. The inner onboarding consumes the managed-workload handoff or selects the legacy resource profile after deletion. Covered by rebuild, managed-workload authority, image-preflight, DCode, and messaging tests. Gaps: health-before-delete and atomic swap. Closed issue #5801 records the original gap; #6835 fixed only the printed recovery path. | From 055660544fd5e0b4ff4d91d38e890dbd0ed3ba29 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Fri, 9 Oct 2026 17:54:30 +0530 Subject: [PATCH 7/9] fix(sandbox): accept the normalized default Docker endpoint Allow retained recovery after the runner resolves the default Docker context to its Unix endpoint. Keep alternate daemons blocked. Exercise runner initialization and the real guard in existing recovery tests without increasing the test count. Signed-off-by: Hung Le --- .../lifecycle/retained-recovery.test.ts | 22 ++++++++++++------- .../sandbox/lifecycle/retained-recovery.ts | 7 ++++-- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index 96d194412d2..27ca64d93bc 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -33,13 +33,19 @@ afterEach(() => { fs.rmSync(testHome, { recursive: true, force: true }); }); -async function setup(port = 19260) { +async function setup(port = 19260, dockerHost?: string) { vi.stubEnv("NEMOCLAW_GATEWAY_PORT", String(port)); + vi.stubEnv("DOCKER_HOST", dockerHost); + vi.stubEnv("DOCKER_CONTEXT", "default"); vi.resetModules(); + const dockerExec = await import("../../../adapters/docker/exec"); + vi.spyOn(dockerExec, "dockerSpawnSync").mockReturnValue({ + ...emptyDockerResult, + stdout: "unix:///var/run/docker.sock", + }); const session = await import("../../../state/onboard-session"); const registry = await import("../../../state/registry"); const docker = await import("../../../adapters/docker/run"); - const dockerTarget = await import("../../../adapters/docker/client-isolation"); const presence = await import("../destroy-presence"); const gateway = await import("../destroy-gateway"); const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); @@ -87,9 +93,6 @@ async function setup(port = 19260) { const runtime = vi .spyOn(gateway, "resolveGatewayCleanupRuntimeProviderId") .mockReturnValue("docker"); - const defaultDaemon = vi - .spyOn(dockerTarget, "dockerContextIsDefaultFromBuild") - .mockReturnValue(true); const files = [ registry.REGISTRY_FILE, session.SESSION_FILE, @@ -111,7 +114,6 @@ async function setup(port = 19260) { containers, volumes, runtime, - defaultDaemon, snapshot, run, }; @@ -327,6 +329,8 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", it("pins container and volume observations to the default Docker daemon (#12260)", async () => { const h = await setup(); h.containers.mockRestore(); + expect(process.env.DOCKER_HOST).toBe("unix:///var/run/docker.sock"); + expect(process.env.DOCKER_CONTEXT).toBeUndefined(); expect(h.run()).toBe(true); @@ -395,11 +399,13 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", }); it("preserves metadata when Docker targets another daemon (#12260)", async () => { - const h = await setup(); - h.defaultDaemon.mockReturnValue(false); + const h = await setup(19260, "unix:///tmp/other-docker.sock"); const before = h.snapshot(); expect(h.run).toThrow(/default daemon/u); expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + expect(h.containers).not.toHaveBeenCalled(); + expect(h.volumes).not.toHaveBeenCalled(); }); it("preserves recovery when its gateway differs from the owning registry root (#12260)", async () => { diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts index 61fd2603dd7..824aa356fd6 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -182,8 +182,11 @@ export function reconcileIdentityFreeRecovery( ) { refuse(sandboxName, "the owning Docker runtime could not be established"); } - // Native Linux Docker gateways use the local default daemon. An ambient override is not absence proof. - if (!dockerContextIsDefaultFromBuild(process.env)) { + // The runner can normalize the native Linux default context to its explicit Unix endpoint. + if ( + process.env.DOCKER_HOST?.trim() !== "unix:///var/run/docker.sock" && + !dockerContextIsDefaultFromBuild(process.env) + ) { refuse( sandboxName, "the Docker observation target is not the native gateway's default daemon", From 3d4d6aeb8cfd31bd1c487b18a3418226aa0cfdb2 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Fri, 9 Oct 2026 19:11:41 +0530 Subject: [PATCH 8/9] fix(sandbox): qualify the recorded recovery daemon Require a default Docker runtime marker that predates retained recovery. Recheck runtime authority after absence probes before retiring metadata. Exercise the real marker owner and preserve state after daemon changes. Keep the recovery schema unchanged. Signed-off-by: Hung Le --- src/lib/actions/sandbox/destroy-gateway.ts | 4 ++ .../lifecycle/retained-recovery.test.ts | 61 ++++++++++++++++++- .../sandbox/lifecycle/retained-recovery.ts | 22 ++++--- src/lib/onboard/host-gateway-process.ts | 14 +++++ src/lib/onboard/lifecycle-contracts.md | 2 +- 5 files changed, 92 insertions(+), 11 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index 04085eebfb1..69c6877875b 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -59,6 +59,7 @@ interface ResolveGatewayCleanupRuntimeProviderDeps extends Pick< > { configuredRuntimeProviderId?: string | null; requireOwnedRuntime?: boolean; + recoveryRecordedAt?: string; } // Compute the Docker-driver gateway state directory that belongs to @@ -96,6 +97,9 @@ export function resolveGatewayCleanupRuntimeProviderId( gatewayName, gatewayPort: perGatewayState.port, stateDir: perGatewayState.stateDir, + ...(deps.recoveryRecordedAt !== undefined + ? { recoveryRecordedAt: deps.recoveryRecordedAt } + : {}), }, ); if (deps.requireOwnedRuntime && !recorded) return null; diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index 27ca64d93bc..5e0a9cc0136 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -50,6 +50,21 @@ async function setup(port = 19260, dockerHost?: string) { const gateway = await import("../destroy-gateway"); const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); const gatewayName = port === 8080 ? "nemoclaw" : `nemoclaw-${port}`; + const { resolveGatewayStateDirForPort } = await import("../../../onboard/gateway-binding"); + const { writeDockerDriverGatewayRuntimeMarkerForStateDir } = + await import("../../../onboard/docker-driver-gateway-runtime-marker"); + const writeRuntime = (host: string | null, createdAt: string) => + writeDockerDriverGatewayRuntimeMarkerForStateDir( + resolveGatewayStateDirForPort({ home: testHome, port }), + { + pid: 4242, + desiredEnv: {}, + endpoint: `https://127.0.0.1:${port}`, + dockerHost: host, + createdAt, + }, + ); + writeRuntime(dockerHost ?? null, new Date(Date.now() - 1_000).toISOString()); const route = { provider: "compatible-endpoint", model: "test-model", @@ -90,9 +105,7 @@ async function setup(port = 19260, dockerHost?: string) { malformedRows: 0, }); const volumes = vi.spyOn(docker, "dockerRun").mockReturnValue(emptyDockerResult); - const runtime = vi - .spyOn(gateway, "resolveGatewayCleanupRuntimeProviderId") - .mockReturnValue("docker"); + const runtime = vi.spyOn(gateway, "resolveGatewayCleanupRuntimeProviderId"); const files = [ registry.REGISTRY_FILE, session.SESSION_FILE, @@ -114,6 +127,7 @@ async function setup(port = 19260, dockerHost?: string) { containers, volumes, runtime, + writeRuntime, snapshot, run, }; @@ -328,6 +342,10 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", it("pins container and volume observations to the default Docker daemon (#12260)", async () => { const h = await setup(); + h.writeRuntime( + "unix:///var/run/docker.sock", + new Date(Date.parse(h.record.recordedAt) - 1_000).toISOString(), + ); h.containers.mockRestore(); expect(process.env.DOCKER_HOST).toBe("unix:///var/run/docker.sock"); expect(process.env.DOCKER_CONTEXT).toBeUndefined(); @@ -408,6 +426,29 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.volumes).not.toHaveBeenCalled(); }); + it("preserves recovery created on another Docker daemon (#12260)", async () => { + const h = await setup(19260, "unix:///tmp/other-docker.sock"); + vi.stubEnv("DOCKER_HOST", "unix:///var/run/docker.sock"); + const before = h.snapshot(); + + expect(h.run).toThrow(/owning Docker runtime/u); + + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + }); + + it("preserves recovery after its gateway is replaced on the default daemon (#12260)", async () => { + const h = await setup(19260, "unix:///tmp/other-docker.sock"); + vi.stubEnv("DOCKER_HOST", "unix:///var/run/docker.sock"); + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) + 1_000).toISOString()); + const before = h.snapshot(); + + expect(h.run).toThrow(/owning Docker runtime/u); + + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + }); + it("preserves recovery when its gateway differs from the owning registry root (#12260)", async () => { const h = await setup(); const before = h.snapshot(); @@ -441,6 +482,20 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", ).toEqual(["alpha-provider"]); }); + it("preserves recovery when its gateway changes during absence probes (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.capture.mockImplementationOnce(() => { + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) + 1_000).toISOString()); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; + }); + + expect(h.run).toThrow(/owning Docker runtime/u); + + expect(h.capture).toHaveBeenCalledTimes(2); + expect(h.snapshot()).toEqual(before); + }); + it("preserves metadata when the reservation gateway name and port conflict (#12260)", async () => { const h = await setup(); expect(h.registry.updateSandbox("alpha", { gatewayPort: 8080 })).toBe(true); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts index 824aa356fd6..fd5209d2b63 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -175,13 +175,20 @@ export function reconcileIdentityFreeRecovery( refuse(sandboxName, "the registry changed before reconciliation"); } if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); - if ( - resolveGatewayCleanupRuntimeProviderId(record.gatewayName, entry?.openshellDriver, { - requireOwnedRuntime: true, - }) !== "docker" - ) { - refuse(sandboxName, "the owning Docker runtime could not be established"); - } + const requireOwnedRuntime = () => { + if ( + resolveGatewayCleanupRuntimeProviderId(record.gatewayName, entry?.openshellDriver, { + requireOwnedRuntime: true, + recoveryRecordedAt: record.recordedAt, + }) !== "docker" + ) { + refuse( + sandboxName, + "the owning Docker runtime on the original default daemon could not be established", + ); + } + }; + requireOwnedRuntime(); // The runner can normalize the native Linux default context to its explicit Unix endpoint. if ( process.env.DOCKER_HOST?.trim() !== "unix:///var/run/docker.sock" && @@ -193,6 +200,7 @@ export function reconcileIdentityFreeRecovery( ); } requireAbsence(record, state); + requireOwnedRuntime(); // The onboarding lock prevents a new create while CAS protects the observed reservation. const currentRecords = sessionState .listRetainedSandboxRecoveryRecords() diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index ca27f4a8dfc..19a0f9425ab 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -230,6 +230,7 @@ export function resolveOwnedHostGatewayRuntimeProviderId(options: { architecture?: NodeJS.Architecture; platform?: NodeJS.Platform; uid?: number; + recoveryRecordedAt?: string; }): string | null { const platform = options.platform ?? process.platform; const architecture = options.architecture ?? process.arch; @@ -250,6 +251,19 @@ export function resolveOwnedHostGatewayRuntimeProviderId(options: { return null; } if (markerPort !== options.gatewayPort) return null; + if (options.recoveryRecordedAt !== undefined) { + // A replacement gateway cannot establish the daemon used by an earlier failed create. + const recordedAt = Date.parse(options.recoveryRecordedAt); + const startedAt = Date.parse(marker.createdAt); + if ( + (marker.dockerHost !== null && marker.dockerHost !== "unix:///var/run/docker.sock") || + !Number.isFinite(recordedAt) || + !Number.isFinite(startedAt) || + startedAt >= recordedAt + ) { + return null; + } + } const provider = resolveRegisteredRuntimeProvider(marker.driver); return provider?.gateway.supported === true ? provider.identity.id : null; } diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 7c4d7fd0696..fde0cfeee62 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -137,7 +137,7 @@ runtime mutation | **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers launch OpenShell service forwarding only on free host ports. OpenShell ends each forward when its sandbox or gateway becomes unavailable. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, and gateway provider state. An interrupted onboarding session records the selected resource values or an explicit OpenShell-default choice; the resolved create intent remains process-local. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution effect transaction/checkpoint. | For identity-free recovery on native Linux, `actions/sandbox/lifecycle/retained-recovery.ts` owns local metadata retirement and preserves runtime resources. -It requires a recorded Docker runtime owner, owning-gateway absence, and no matching containers or managed state volumes on the default Docker daemon. +It requires an owned default-Docker runtime marker that predates the recovery record, owning-gateway absence, and no matching containers or managed state volumes on that daemon. Missing, alternate-daemon, or newer runtime evidence keeps recovery blocked. Any reservation must match its recovery-only session; conflicting state, recorded sandbox-scoped providers, or additional resource ownership block retirement. Legacy Shields state retires before registry and recovery metadata; interrupted retirement retains recovery authority for retry. The public CLI admits `destroy` from the selected root's retained record after reservation removal; the lifecycle owner revalidates authority and absence and preserves unrelated sessions. From ddab26b6f88aa7b0bcacaa56076c350cb68ad310 Mon Sep 17 00:00:00 2001 From: Hung Le Date: Fri, 9 Oct 2026 21:36:19 +0530 Subject: [PATCH 9/9] refactor(sandbox): trim redundant recovery checks and tests Reuse the route classifier for reservation ownership checks. Consolidate coverage around destroy and failure and retry paths. Keep distinct daemon, ownership and CLI admission regressions. Signed-off-by: Hung Le --- .../actions/sandbox/destroy-gateway.test.ts | 17 -- .../lifecycle/retained-recovery.test.ts | 188 ++++++++---------- .../sandbox/lifecycle/retained-recovery.ts | 16 +- 3 files changed, 84 insertions(+), 137 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-gateway.test.ts b/src/lib/actions/sandbox/destroy-gateway.test.ts index 7df8cf31354..b2caf65b7f9 100644 --- a/src/lib/actions/sandbox/destroy-gateway.test.ts +++ b/src/lib/actions/sandbox/destroy-gateway.test.ts @@ -109,23 +109,6 @@ describe("cleanupGatewayAfterLastSandbox", () => { }); }); - it("requires an owned runtime marker for identity-free recovery (#12260)", () => { - mocks.resolveOwnedHostGatewayRuntimeProviderId.mockReturnValue(null); - expect( - resolveGatewayCleanupRuntimeProviderId("nemoclaw-8081", "docker", { - configuredRuntimeProviderId: "docker", - requireOwnedRuntime: true, - }), - ).toBeNull(); - - mocks.resolveOwnedHostGatewayRuntimeProviderId.mockReturnValueOnce("docker"); - expect( - resolveGatewayCleanupRuntimeProviderId("nemoclaw-8081", undefined, { - requireOwnedRuntime: true, - }), - ).toBe("docker"); - }); - it("rejects disagreement between sandbox and gateway provider authority", () => { mocks.resolveOwnedHostGatewayRuntimeProviderId.mockReturnValueOnce("docker"); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index 5e0a9cc0136..1d1d3682b4a 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -47,23 +47,23 @@ async function setup(port = 19260, dockerHost?: string) { const registry = await import("../../../state/registry"); const docker = await import("../../../adapters/docker/run"); const presence = await import("../destroy-presence"); - const gateway = await import("../destroy-gateway"); const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); const gatewayName = port === 8080 ? "nemoclaw" : `nemoclaw-${port}`; const { resolveGatewayStateDirForPort } = await import("../../../onboard/gateway-binding"); - const { writeDockerDriverGatewayRuntimeMarkerForStateDir } = - await import("../../../onboard/docker-driver-gateway-runtime-marker"); - const writeRuntime = (host: string | null, createdAt: string) => - writeDockerDriverGatewayRuntimeMarkerForStateDir( - resolveGatewayStateDirForPort({ home: testHome, port }), - { - pid: 4242, - desiredEnv: {}, - endpoint: `https://127.0.0.1:${port}`, - dockerHost: host, - createdAt, - }, - ); + const { + clearDockerDriverGatewayRuntimeMarker, + writeDockerDriverGatewayRuntimeMarkerForStateDir, + } = await import("../../../onboard/docker-driver-gateway-runtime-marker"); + const stateDir = resolveGatewayStateDirForPort({ home: testHome, port }); + const writeRuntime = (host: string | null, createdAt: string, runtimeProviderId = "docker") => + writeDockerDriverGatewayRuntimeMarkerForStateDir(stateDir, { + pid: 4242, + desiredEnv: {}, + endpoint: `https://127.0.0.1:${port}`, + dockerHost: host, + createdAt, + runtimeProviderId, + }); writeRuntime(dockerHost ?? null, new Date(Date.now() - 1_000).toISOString()); const route = { provider: "compatible-endpoint", @@ -105,7 +105,6 @@ async function setup(port = 19260, dockerHost?: string) { malformedRows: 0, }); const volumes = vi.spyOn(docker, "dockerRun").mockReturnValue(emptyDockerResult); - const runtime = vi.spyOn(gateway, "resolveGatewayCleanupRuntimeProviderId"); const files = [ registry.REGISTRY_FILE, session.SESSION_FILE, @@ -126,7 +125,7 @@ async function setup(port = 19260, dockerHost?: string) { capture, containers, volumes, - runtime, + clearRuntime: () => clearDockerDriverGatewayRuntimeMarker(stateDir), writeRuntime, snapshot, run, @@ -173,6 +172,13 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", "releases the retained name through destroy on gateway port %s without resource cleanup (#12260)", async (port) => { const h = await setupDestroy(port); + h.writeRuntime( + "unix:///var/run/docker.sock", + new Date(Date.parse(h.record.recordedAt) - 1_000).toISOString(), + ); + h.containers.mockRestore(); + expect(process.env.DOCKER_HOST).toBe("unix:///var/run/docker.sock"); + expect(process.env.DOCKER_CONTEXT).toBeUndefined(); expect(h.registry.getSandbox("alpha")?.gatewayPort).toBeUndefined(); expect(h.record.sandboxIdentityFingerprint).toBeNull(); @@ -197,9 +203,13 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect( h.capture.mock.calls.every(([args]) => args[0] === "sandbox" && args[1] === "list"), ).toBe(true); - expect(h.volumes.mock.calls.every(([args]) => args[2] === "volume" && args[3] === "ls")).toBe( - true, - ); + expect(h.volumes.mock.calls.some(([args]) => args[2] === "ps")).toBe(true); + expect( + h.volumes.mock.calls.every( + ([args]) => + args[0] === "--context" && args[1] === "default" && ["ps", "volume"].includes(args[2]!), + ), + ).toBe(true); expect( h.registry.reserveSandboxInferenceRoute("alpha", { ...h.route, @@ -255,40 +265,32 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.ordinaryDestroy).not.toHaveBeenCalled(); }); - it.each([ - ["failed", { status: 1, output: "", stdout: "[]", stderr: "connection refused" }], - ["malformed", { status: 0, output: "invalid", stdout: "invalid", stderr: "" }], - ["diagnostic", { status: 0, output: "[]", stdout: "[]", stderr: "partial result" }], - [ - "present", - { - status: 0, - output: "", - stdout: JSON.stringify([ - { - id: "sandbox-alpha", - name: "alpha", - labels: {}, - phase: "Ready", - created_at: "2026-10-08", - resource_version: 1, - current_policy_version: 1, - }, - ]), - stderr: "", - }, - ], - ])("preserves state when the gateway observation is %s (#12260)", async (_label, observation) => { + it("preserves state when the gateway still reports the sandbox present (#12260)", async () => { const h = await setup(); const before = h.snapshot(); - h.capture.mockReturnValue(observation); + h.capture.mockReturnValue({ + status: 0, + output: "", + stdout: JSON.stringify([ + { + id: "sandbox-alpha", + name: "alpha", + labels: {}, + phase: "Ready", + created_at: "2026-10-08", + resource_version: 1, + current_policy_version: 1, + }, + ]), + stderr: "", + }); expect(h.run).toThrow(/presence as/u); expect(h.snapshot()).toEqual(before); }); - it.each(["residual", "failed", "malformed"])( + it.each(["residual", "failed"])( "preserves state for a %s container observation (#12260)", async (kind) => { const h = await setup(); @@ -298,18 +300,15 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", ? { status: "probe-failed", detail: "Docker unavailable" } : { status: "observed", - malformedRows: kind === "malformed" ? 1 : 0, - rows: - kind === "residual" - ? [ - { - id: "b".repeat(64), - managedBy: "openshell", - workspace: "default", - sandboxId: "sandbox-alpha", - }, - ] - : [], + malformedRows: 0, + rows: [ + { + id: "b".repeat(64), + managedBy: "openshell", + workspace: "default", + sandboxId: "sandbox-alpha", + }, + ], }, ); @@ -340,31 +339,6 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.snapshot()).toEqual(before); }); - it("pins container and volume observations to the default Docker daemon (#12260)", async () => { - const h = await setup(); - h.writeRuntime( - "unix:///var/run/docker.sock", - new Date(Date.parse(h.record.recordedAt) - 1_000).toISOString(), - ); - h.containers.mockRestore(); - expect(process.env.DOCKER_HOST).toBe("unix:///var/run/docker.sock"); - expect(process.env.DOCKER_CONTEXT).toBeUndefined(); - - expect(h.run()).toBe(true); - - expect( - h.volumes.mock.calls.some( - ([args]) => args[0] === "--context" && args[1] === "default" && args[2] === "ps", - ), - ).toBe(true); - expect( - h.volumes.mock.calls.every( - ([args]) => - args[0] === "--context" && args[1] === "default" && ["ps", "volume"].includes(args[2]!), - ), - ).toBe(true); - }); - it("preserves sandbox-scoped provider ownership after sandbox absence (#12260)", async () => { const h = await setup(); h.session.recordRetainedSandboxRecovery({ @@ -376,16 +350,23 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.snapshot()).toEqual(before); }); - it.each([null, "podman"])( - "rejects unproven Docker absence for runtime %s (#12260)", - async (runtime) => { - const h = await setup(); - const before = h.snapshot(); - h.runtime.mockReturnValue(runtime); - expect(h.run).toThrow(/owning Docker runtime/u); - expect(h.snapshot()).toEqual(before); - }, - ); + it("preserves recovery when the recorded Docker runtime marker is missing (#12260)", async () => { + const h = await setup(); + h.registry.updateSandbox("alpha", { openshellDriver: "docker" }); + h.clearRuntime(); + const before = h.snapshot(); + expect(h.run).toThrow(/owning Docker runtime/u); + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + }); + + it("preserves recovery owned by a different runtime provider (#12260)", async () => { + const h = await setup(); + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) - 1_000).toISOString(), "podman"); + const before = h.snapshot(); + expect(h.run).toThrow(/owning Docker runtime/u); + expect(h.snapshot()).toEqual(before); + }); it("preserves records when more than one failed create uses the same name (#12260)", async () => { const h = await setup(); @@ -417,7 +398,8 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", }); it("preserves metadata when Docker targets another daemon (#12260)", async () => { - const h = await setup(19260, "unix:///tmp/other-docker.sock"); + const h = await setup(); + vi.stubEnv("DOCKER_HOST", "unix:///tmp/other-docker.sock"); const before = h.snapshot(); expect(h.run).toThrow(/default daemon/u); expect(h.snapshot()).toEqual(before); @@ -508,21 +490,6 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.volumes).not.toHaveBeenCalled(); }); - it("preserves a replacement session after registry retirement (#12260)", async () => { - const h = await setup(); - h.registry.removeSandboxRouteReservationIfCurrent(h.registry.getSandbox("alpha")!); - h.session.saveSession( - h.session.createSession({ - sessionId: "replacement-session", - sandboxName: "other-sandbox", - }), - ); - const replacement = fs.readFileSync(h.session.SESSION_FILE, "utf8"); - expect(h.run()).toBe(true); - expect(fs.readFileSync(h.session.SESSION_FILE, "utf8")).toBe(replacement); - expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); - }); - it("preserves a registry replacement that appears during absence verification (#12260)", async () => { const h = await setup(); h.capture.mockImplementationOnce(() => { @@ -565,8 +532,13 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([h.record]); expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(true); failure.mockRestore(); + h.session.saveSession( + h.session.createSession({ sessionId: "replacement-session", sandboxName: "other-sandbox" }), + ); + const replacement = fs.readFileSync(h.session.SESSION_FILE, "utf8"); expect(h.run()).toBe(true); + expect(fs.readFileSync(h.session.SESSION_FILE, "utf8")).toBe(replacement); expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(false); }); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts index fd5209d2b63..e83de88d853 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -14,7 +14,6 @@ import { resolveNemoclawStateGatewayPort } from "../../../state/paths"; import type * as Registry from "../../../state/registry"; import { classifySandboxInferenceRouteReservation, - isPendingReservationForSession, isRouteOnlySandboxReservation, } from "../../../state/registry/route-reservation"; import { resolveGatewayCleanupRuntimeProviderId } from "../destroy-gateway"; @@ -108,18 +107,13 @@ function requireReservationOwner( session: OnboardSession.Session | null, state: RecoveryState, ): void { + const { name, gatewayName, gatewayPort } = entry; if ( session?.status !== "recovery_required" || session.sandboxName !== record.sandboxName || session.cancellationRecovery?.reason !== record.reason || !state.session.retainedSandboxRecoveryMatchesSession(record, session) || - !isPendingReservationForSession(entry, session.sessionId) || - state.registryEntryGatewayPort({ - name: entry.name, - gatewayName: entry.gatewayName, - gatewayPort: entry.gatewayPort, - }) !== record.gatewayPort || - entry.gatewayName !== record.gatewayName || + state.registryEntryGatewayPort({ name, gatewayName, gatewayPort }) !== record.gatewayPort || entry.hostLocalInferenceReceipt != null || entry.nativeNvidiaProviderAttachment !== undefined || classifySandboxInferenceRouteReservation( @@ -211,10 +205,8 @@ export function reconcileIdentityFreeRecovery( if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); // Legacy state retirement must succeed while the recovery authority is still available for retry. state.retireRemovedImmutabilityState?.(); - if (entry) { - if (!registry.removeSandboxRouteReservationIfCurrent(entry)) { - refuse(sandboxName, "the registry changed during absence verification"); - } + if (entry && !registry.removeSandboxRouteReservationIfCurrent(entry)) { + refuse(sandboxName, "the registry changed during absence verification"); } if (registry.getSandbox(sandboxName) !== null) { refuse(sandboxName, "a registry entry appeared during reconciliation");