From 64e5e672a50cb805a2dcaa783105e90fd04972f9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:36:07 -0700 Subject: [PATCH 01/10] refactor(openshell): unify CLI exec capture Signed-off-by: Aaron Erickson --- .../openshell/sandbox-control.test.ts | 35 ++++++----- src/lib/adapters/openshell/sandbox-control.ts | 62 +++++-------------- 2 files changed, 37 insertions(+), 60 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 949087a9886..493df4eaa15 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -3,20 +3,22 @@ import { describe, expect, it, vi } from "vitest"; -import type { CaptureOpenshellBinaryResult, CaptureOpenshellResult } from "./client"; +import type { CaptureOpenshellBinaryResult } from "./client"; import { createCliOpenShellSandboxControl } from "./sandbox-control"; describe("CLI OpenShell sandbox control", () => { it("maps a typed exec request to the existing CLI contract", async () => { - const capture = vi.fn( - (): CaptureOpenshellResult => ({ + const captureBinary = vi.fn( + (): CaptureOpenshellBinaryResult => ({ status: 0, - output: "hello", - stdout: "hello\n", - stderr: "warning\n", + stdout: Buffer.from("hello\n"), + stderr: Buffer.from("warning\n"), }), ); - const control = createCliOpenShellSandboxControl(capture); + const control = createCliOpenShellSandboxControl({ + resolveBinary: () => "/usr/bin/openshell", + captureBinary, + }); const result = await control.exec({ sandboxName: "alpha", @@ -26,11 +28,10 @@ describe("CLI OpenShell sandbox control", () => { timeoutMs: 30_000, }); - expect(capture).toHaveBeenCalledWith( + expect(captureBinary).toHaveBeenCalledWith( + "/usr/bin/openshell", ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], { - ignoreError: true, - includeStreams: true, input: Buffer.from("request body"), maxBuffer: 4096, timeout: 30_000, @@ -45,15 +46,19 @@ describe("CLI OpenShell sandbox control", () => { it("preserves transport failures without throwing", async () => { const error = Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }); - const capture = vi.fn( - (): CaptureOpenshellResult => ({ + const captureBinary = vi.fn( + (): CaptureOpenshellBinaryResult => ({ status: null, - output: "partial", + stdout: Buffer.from("partial"), + stderr: Buffer.alloc(0), error, signal: "SIGTERM", }), ); - const control = createCliOpenShellSandboxControl(capture); + const control = createCliOpenShellSandboxControl({ + resolveBinary: () => "/usr/bin/openshell", + captureBinary, + }); await expect(control.exec({ sandboxName: "alpha", command: ["true"] })).resolves.toEqual({ status: null, @@ -73,7 +78,7 @@ describe("CLI OpenShell sandbox control", () => { stderr: Buffer.from("warning"), }), ); - const control = createCliOpenShellSandboxControl(vi.fn(), { + const control = createCliOpenShellSandboxControl({ resolveBinary: () => "/usr/bin/openshell", captureBinary, }); diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index 7e44893359b..8c6da3c60e1 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -1,9 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { type CaptureOpenshellResult, captureOpenshellCommandBinary } from "./client"; +import { captureOpenshellCommandBinary } from "./client"; import { resolveOpenshell } from "./resolve"; -import { captureOpenshell } from "./runtime"; export interface SandboxExecRequest { sandboxName: string; @@ -32,7 +31,6 @@ export interface OpenShellSandboxControl { exec(request: SandboxExecRequest): Promise; } -type CaptureOpenShell = typeof captureOpenshell; type CaptureOpenShellBinary = typeof captureOpenshellCommandBinary; export interface CliOpenShellSandboxControlDependencies { @@ -45,64 +43,38 @@ const defaultCliDependencies: CliOpenShellSandboxControlDependencies = { resolveBinary: resolveOpenshell, }; -function normalizeExecResult(result: CaptureOpenshellResult): SandboxExecResult { - const normalized: SandboxExecResult = { - status: result.status, - stdout: result.stdout ?? result.output, - stderr: result.stderr ?? "", - }; - if (result.error) normalized.error = result.error; - if (result.signal !== undefined) normalized.signal = result.signal; - return normalized; -} - export function createCliOpenShellSandboxControl( - capture: CaptureOpenShell = captureOpenshell, dependencies: CliOpenShellSandboxControlDependencies = defaultCliDependencies, ): OpenShellSandboxControl { return { async exec(request): Promise { - if (request.stdoutEncoding === "buffer") { - const binary = dependencies.resolveBinary(); - if (!binary) { - return { - status: null, - stdout: "", - stderr: "", - error: new Error("openshell CLI not found"), - }; - } - const result = dependencies.captureBinary( - binary, - ["sandbox", "exec", "--name", request.sandboxName, "--", ...request.command], - { - input: request.stdin, - maxBuffer: request.maxOutputBytes, - timeout: request.timeoutMs, - }, - ); + const binary = dependencies.resolveBinary(); + if (!binary) { return { - status: result.status, + status: null, stdout: "", - stdoutBytes: result.stdout, - stderr: result.stderr.toString("utf8"), - ...(result.error ? { error: result.error } : {}), - ...(result.signal !== undefined ? { signal: result.signal } : {}), + stderr: "", + error: new Error("openshell CLI not found"), }; } - const result = capture( + const result = dependencies.captureBinary( + binary, ["sandbox", "exec", "--name", request.sandboxName, "--", ...request.command], { - ignoreError: true, - includeStreams: true, input: request.stdin, maxBuffer: request.maxOutputBytes, timeout: request.timeoutMs, }, ); - return normalizeExecResult(result); + const binaryStdout = request.stdoutEncoding === "buffer"; + return { + status: result.status, + stdout: binaryStdout ? "" : result.stdout.toString("utf8"), + ...(binaryStdout ? { stdoutBytes: result.stdout } : {}), + stderr: result.stderr.toString("utf8"), + ...(result.error ? { error: result.error } : {}), + ...(result.signal !== undefined ? { signal: result.signal } : {}), + }; }, }; } - -export const openShellSandboxControl = createCliOpenShellSandboxControl(); From 7115ff2483f780d86f43a13f5878b28967b06244 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:45:03 -0700 Subject: [PATCH 02/10] refactor(snapshot): remove Kubernetes image probe Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 1 - src/lib/actions/sandbox/snapshot.test.ts | 1 - src/lib/actions/sandbox/snapshot.ts | 55 +++------------------ test/snapshot-gateway-guard.test.ts | 12 ++--- test/snapshot-restore-existing-dest.test.ts | 20 ++------ 5 files changed, 16 insertions(+), 73 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 033603488e5..edfb74d4a6a 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -35,7 +35,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/actions/dns/index.ts", "docker-exec-command", 4], ["src/lib/actions/sandbox/host-aliases.ts", "docker-exec-command", 1], ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], - ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/onboard.ts", "docker-exec-builder", 1], ["src/lib/resources-cmd.ts", "docker-exec-command", 1], diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 28592708ed1..e260ef4f31b 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -146,7 +146,6 @@ const latestBackupFixture = { }; vi.mock("../../adapters/docker", () => ({ - dockerCapture: vi.fn(() => ""), dockerInspect: dockerInspectMock, })); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index e254ee20640..3b437205c3b 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -3,7 +3,6 @@ import fs from "node:fs"; import path from "node:path"; -import { dockerCapture } from "../../adapters/docker"; import { captureOpenshell, getOpenshellBinary, @@ -56,11 +55,7 @@ import { createSandboxExecMarker, extractSandboxExecCommandStdoutFromStreams, } from "./sandbox-exec-output"; -import { - probeGatewayRunning, - selectSandboxGatewayIfRegistered, - usesGatewayMetadataProbe, -} from "./sandbox-gateway-routing"; +import { probeGatewayRunning, selectSandboxGatewayIfRegistered } from "./sandbox-gateway-routing"; const useColor = !process.env.NO_COLOR && !!process.stdout.isTTY; const trueColor = @@ -139,45 +134,11 @@ function renderSnapshotTable( } } -// Resolve the running src pod's image. Docker- and VM-driver sandboxes don't -// have the legacy cluster container — trust the registered imageTag and fail -// fast if it's missing. Only the "kubernetes" driver falls back to the -// kubectl probe inside the gateway container. -function resolveSrcPodImage( - srcName: string, - srcEntry?: SandboxEntry | { name: string }, -): string | null { - const registeredImage = (srcEntry as { imageTag?: string | null } | undefined)?.imageTag; - const registeredDriver = (srcEntry as { openshellDriver?: string | null } | undefined) - ?.openshellDriver; - if (usesGatewayMetadataProbe(registeredDriver)) { - return registeredImage ?? null; - } - - const srcGatewayName = resolveSandboxGatewayName( - srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, - ); - const gatewayContainer = `openshell-cluster-${srcGatewayName}`; - try { - const output = dockerCapture( - [ - "exec", - gatewayContainer, - "kubectl", - "get", - "pod", - srcName, - "-n", - "openshell", - "-o", - 'jsonpath={.spec.containers[?(@.name=="agent")].image}', - ], - { ignoreError: true, timeout: 10000 }, - ); - return output.trim().split(/\s+/)[0] || null; - } catch { - return null; - } +// The registry image is recorded from OpenShell's create result and remains +// the authoritative rebuild input. Legacy entries without it fail closed; +// do not bypass the control plane to inspect a Kubernetes pod through Docker. +function registeredSandboxImage(srcEntry: SandboxEntry | { name: string }): string | null { + return (srcEntry as { imageTag?: string | null }).imageTag ?? null; } // Auto-create a sandbox that clones the image of an existing one. @@ -854,7 +815,7 @@ async function runSnapshotRestoreUnlocked( snapshotExit(1); } const srcEntry = registry.getSandbox(sandboxName) || { name: sandboxName }; - const fromImage = resolveSrcPodImage(sandboxName, srcEntry); + const fromImage = registeredSandboxImage(srcEntry); if (!fromImage) { console.error( ` Cannot resolve image for source sandbox '${sandboxName}' — aborting before ` + @@ -900,7 +861,7 @@ async function runSnapshotRestoreUnlocked( ); snapshotExit(1); } - const lockedFromImage = resolveSrcPodImage(sandboxName, lockedSourceEntry); + const lockedFromImage = registeredSandboxImage(lockedSourceEntry); if (!lockedFromImage) { console.error( ` Cannot resolve the current image for source sandbox '${sandboxName}' — aborting before changing '${targetSandbox}'.`, diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index 6624c0e858f..da6bbad8f1f 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -143,9 +143,7 @@ function makeHealthyVmGatewayEnv(prefix: string): Record { }; } -// VM-driver env with an `imageTag` set in the sandbox registry so the -// `resolveSrcPodImage()` fast path returns the image without falling back to -// the docker/kubectl probe. +// VM-driver env with the authoritative `imageTag` set in the sandbox registry. function makeVmRestoreToEnv( prefix: string, entry: Record = { imageTag: "openshell/sandbox-from:fast-path-test" }, @@ -181,9 +179,7 @@ function makeVmRestoreToEnv( "exit 0", ]); - // `docker exec` must never run: if the fast path regresses, - // resolveSrcPodImage falls into the kubectl-via-docker probe and this - // marker shows up in the captured output. + // Snapshot restore must never bypass OpenShell through Docker. writeExecutable(path.join(localBin, "docker"), [ 'if [ "$1" = "exec" ]; then', ' echo "kubectl-must-not-run"', @@ -223,9 +219,7 @@ describe("snapshot VM-driver gateway guard", () => { expect(r.out).not.toContain("Failed to query live sandbox state"); }); - // `snapshot restore --to ` on VM driver must use the registered - // imageTag, not the legacy `docker exec ... kubectl` probe. - it("snapshot restore --to uses registered imageTag for VM-driver auto-create instead of kubectl probe", () => { + it("snapshot restore --to uses the registered imageTag for VM-driver auto-create", () => { const env = makeVmRestoreToEnv("nemoclaw-snap-vm-gw-restore-to-"); const seed = runCli("alpha snapshot create --name baseline", env); diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index fc30cafb93a..327d114bdf6 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -56,7 +56,7 @@ function runCli( interface MakeEnvOptions { /** When false, omit the snapshot manifest so getLatestBackup returns null. */ withSnapshot?: boolean; - /** When false, fake docker exec returns an empty image string. */ + /** When false, omit the source registry image. */ withSourceImage?: boolean; /** Put dst on a registered non-default gateway and hide it from src's gateway list. */ destinationGatewayPort?: number; @@ -78,10 +78,7 @@ interface MakeEnvOptions { * - `sandbox delete dst` exits 0 (and logs the call) * - `sandbox create` exits non-zero (intentional; the integration tests * only need to verify control flow reached/passed the delete step) - * - fake docker that: - * - `inspect ... State.Running` returns "true" (gateway up) - * - `exec ... kubectl get pod src ...` returns an image string (or empty - * when withSourceImage=false), exercising resolveSrcPodImage's preflight + * - fake docker whose `inspect ... State.Running` returns "true" (gateway up) */ function makeExistingDestEnv( prefix: string, @@ -102,6 +99,9 @@ function makeExistingDestEnv( sandboxes: { src: { name: "src", + ...(opts.withSourceImage === false + ? {} + : { imageTag: "ghcr.io/nvidia/nemoclaw/sandbox-src:test" }), model: "test-model", provider: "nvidia-prod", gpuEnabled: false, @@ -190,8 +190,6 @@ function makeExistingDestEnv( { mode: 0o755 }, ); - const sourceImageOutput = - opts.withSourceImage === false ? "" : "ghcr.io/nvidia/nemoclaw/sandbox-src:test"; fs.writeFileSync( path.join(localBin, "docker"), [ @@ -203,14 +201,6 @@ function makeExistingDestEnv( ' echo "true"', " exit 0", "fi", - 'if [ "$1" = "exec" ]; then', - // The action calls `docker exec kubectl get pod ...`. - // Return the configured image (or an empty string to simulate - // "image cannot be resolved", which #3756 P1 says must abort before - // we touch the destination). - ` printf '%s' ${JSON.stringify(sourceImageOutput)}`, - " exit 0", - "fi", "exit 0", ].join("\n"), { mode: 0o755 }, From 19b0a67a00c67cc75734cc6671afb76babcb8033 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 17:34:58 -0700 Subject: [PATCH 03/10] feat(openshell): read sandbox descriptors over gRPC Signed-off-by: Aaron Erickson --- .../openshell/grpc-sandbox-control.test.ts | 61 +++++++++++++++--- .../openshell/grpc-sandbox-control.ts | 62 +++++++++++++++---- .../openshell/sandbox-control-routing.test.ts | 52 +++++++++++++++- .../openshell/sandbox-control-routing.ts | 41 ++++++++---- 4 files changed, 183 insertions(+), 33 deletions(-) diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 242d271459b..42e8dbce332 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -24,6 +24,7 @@ import { type OpenShellGrpcApi, OpenShellGrpcOutputLimitError, OpenShellGrpcPreDispatchError, + type OpenShellSandboxDescriptor, } from "./grpc-sandbox-control"; import { OPENSHELL_EXEC_MAX_OUTPUT_BYTES, @@ -38,12 +39,24 @@ class FakeStream extends EventEmitter { } } +type GetSandboxCallback = Parameters[3]; +type FakeGetSandboxResponse = NonNullable[1]>; + interface FakeApiOptions { sandboxId?: string; + getResponse?: FakeGetSandboxResponse; getError?: ServiceError; emit?: (stream: FakeStream) => void; } +function descriptorResponse({ + id = "sb-id", + name = "alpha", + image = "nvcr.io/nvidia/nemoclaw:test", +}: Partial = {}): FakeGetSandboxResponse { + return { sandbox: { metadata: { id, name }, spec: { template: { image } } } }; +} + function fakeApi(fixture: FakeApiOptions = {}): { api: OpenShellGrpcApi; stream: FakeStream; @@ -67,11 +80,14 @@ function fakeApi(fixture: FakeApiOptions = {}): { queueMicrotask(() => { fixture.getError ? callback(fixture.getError) - : callback(null, { - sandbox: { - metadata: fixture.sandboxId === "" ? {} : { id: fixture.sandboxId ?? "sb-id" }, + : callback( + null, + fixture.getResponse ?? { + sandbox: { + metadata: fixture.sandboxId === "" ? {} : { id: fixture.sandboxId ?? "sb-id" }, + }, }, - }); + ); }); return request; }, @@ -299,13 +315,18 @@ describe("gRPC OpenShell sandbox control", () => { }; const server = new Server(); const requests: unknown[] = []; + const deadlines: Array = []; server.addService(loaded.openshell.v1.OpenShell.service, { getSandbox( - call: ServerUnaryCall<{ name: string }, { sandbox: { metadata: { id: string } } }>, - callback: sendUnaryData<{ sandbox: { metadata: { id: string } } }>, + call: ServerUnaryCall<{ name: string }, FakeGetSandboxResponse>, + callback: sendUnaryData, ) { requests.push(call.request); - callback(null, { sandbox: { metadata: { id: "wire-id" } } }); + deadlines.push(call.getDeadline()); + callback( + null, + descriptorResponse({ id: "wire-id", image: "nvcr.io/nvidia/nemoclaw:wire" }), + ); }, execSandbox( call: ServerWritableStream< @@ -331,6 +352,15 @@ describe("gRPC OpenShell sandbox control", () => { endpoint: `http://127.0.0.1:${port}`, }); try { + const before = Date.now(); + await expect(control.getSandboxDescriptor("alpha")).resolves.toEqual({ + id: "wire-id", + name: "alpha", + image: "nvcr.io/nvidia/nemoclaw:wire", + }); + const deadline = new Date(deadlines[0]).getTime(); + expect(deadline).toBeGreaterThanOrEqual(before + 15_000); + expect(deadline).toBeLessThanOrEqual(Date.now() + 15_000); await expect( control.exec({ sandboxName: "alpha", @@ -343,6 +373,7 @@ describe("gRPC OpenShell sandbox control", () => { stderr: "wire stderr", }); expect(requests).toEqual([ + { name: "alpha" }, { name: "alpha" }, { sandboxId: "wire-id", @@ -456,6 +487,22 @@ describe("gRPC OpenShell sandbox control", () => { }); }); + it.each([ + [descriptorResponse({ id: " " }), "without an id"], + [descriptorResponse({ name: "" }), "without a name"], + [descriptorResponse({ name: "beta" }), "returned sandbox 'beta' for requested sandbox 'alpha'"], + [descriptorResponse({ image: " " }), "without an image"], + ])("rejects incomplete or mismatched descriptors", async (getResponse, message) => { + const fake = fakeApi({ getResponse }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect(control.getSandboxDescriptor("alpha")).rejects.toThrow(message); + expect(fake.execMetadata).toEqual([]); + }); + it.each([ [{ maxOutputBytes: -1 }, "maxOutputBytes"], [{ maxOutputBytes: 1.5 }, "maxOutputBytes"], diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 1bfaf8d95e5..15a339e27a3 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -17,11 +17,15 @@ import { type SandboxExecResult, validateOpenShellExecRequest, } from "./sandbox-control"; +import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; const PROTO_VERSION = "0.0.72"; interface GetSandboxResponse { - sandbox?: { metadata?: { id?: string } }; + sandbox?: { + metadata?: { id?: string; name?: string }; + spec?: { template?: { image?: string } }; + }; } interface ExecSandboxEvent { @@ -68,9 +72,12 @@ export interface OpenShellGrpcClientConfig { } export interface GrpcOpenShellSandboxControl extends OpenShellSandboxControl { + getSandboxDescriptor(sandboxName: string): Promise; close(): void; } +export type OpenShellSandboxDescriptor = { id: string; name: string; image: string }; + export { OpenShellExecOutputLimitError as OpenShellGrpcOutputLimitError } from "./sandbox-control"; export class OpenShellGrpcPreDispatchError extends Error { @@ -187,28 +194,52 @@ function callMetadata(bearerToken: string | undefined): grpc.Metadata { return metadata; } -function sandboxId( +function getSandboxResponse( client: OpenShellGrpcApi, sandboxName: string, metadata: grpc.Metadata, options: grpc.CallOptions, -): Promise { +): Promise { return new Promise((resolve, reject) => { client.getSandbox({ name: sandboxName }, metadata, options, (error, response) => { - if (error) { - reject(error); - return; - } - const id = response?.sandbox?.metadata?.id; - if (!id) { - reject(new Error(`OpenShell returned sandbox '${sandboxName}' without an id`)); - return; - } - resolve(id); + error ? reject(error) : resolve(response); }); }); } +async function sandboxId( + client: OpenShellGrpcApi, + sandboxName: string, + metadata: grpc.Metadata, + options: grpc.CallOptions, +): Promise { + const id = (await getSandboxResponse(client, sandboxName, metadata, options))?.sandbox?.metadata + ?.id; + if (!id) throw new Error(`OpenShell returned sandbox '${sandboxName}' without an id`); + return id; +} + +async function sandboxDescriptor( + client: OpenShellGrpcApi, + sandboxName: string, + metadata: grpc.Metadata, + options: grpc.CallOptions, +): Promise { + const sandbox = (await getSandboxResponse(client, sandboxName, metadata, options))?.sandbox; + const id = sandbox?.metadata?.id; + const name = sandbox?.metadata?.name; + const image = sandbox?.spec?.template?.image; + if (!id?.trim()) throw new Error(`OpenShell returned sandbox '${sandboxName}' without an id`); + if (!name?.trim()) throw new Error(`OpenShell returned sandbox '${sandboxName}' without a name`); + if (name !== sandboxName) { + throw new Error(`OpenShell returned sandbox '${name}' for requested sandbox '${sandboxName}'`); + } + if (!image?.trim()) { + throw new Error(`OpenShell returned sandbox '${sandboxName}' without an image`); + } + return { id, name, image }; +} + function asBuffer(data: Buffer | Uint8Array | string | undefined): Buffer { if (data === undefined) return Buffer.alloc(0); return Buffer.isBuffer(data) ? data : Buffer.from(data); @@ -297,6 +328,11 @@ export function createGrpcOpenShellSandboxControl( const client = injectedClient ?? createOpenShellGrpcApi(config); return { close: () => client.close(), + getSandboxDescriptor(sandboxName): Promise { + return sandboxDescriptor(client, sandboxName, callMetadata(config.bearerToken), { + deadline: new Date(Date.now() + OPENSHELL_PROBE_TIMEOUT_MS), + }); + }, async exec(request): Promise { // Validate against the exact v0.0.72 UUID-width request before lookup so // transport-independent limits cannot cause any gateway activity. diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index a48592259ce..d08197ace34 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -18,6 +18,7 @@ import { } from "./sandbox-control"; import { execSandboxReadOnlyWithGrpcFallback, + getOpenShellSandboxDescriptor, selectOpenShellSandboxControlForMutation, } from "./sandbox-control-routing"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; @@ -27,7 +28,12 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox const grpcExec = vi.fn(() => grpcResult instanceof Error ? Promise.reject(grpcResult) : Promise.resolve(grpcResult), ); - const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec }; + const getSandboxDescriptor = vi.fn(async (sandboxName: string) => ({ + id: "sb-id", + name: sandboxName, + image: "nvcr.io/nvidia/nemoclaw:test", + })); + const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec, getSandboxDescriptor }; const cliExec = vi.fn(async () => cliResult ?? { status: 0, stdout: "cli", stderr: "" }); const cli: OpenShellSandboxControl = { exec: cliExec }; const createCli = vi.fn(() => cli); @@ -37,6 +43,7 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox close, cli, grpcExec, + getSandboxDescriptor, cliExec, createCli, createGrpc, @@ -51,6 +58,49 @@ const request = { maxOutputBytes: 4096, }; +describe("OpenShell sandbox descriptor routing", () => { + it("reads from the selected gateway and closes without invoking the CLI", async () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + + await expect( + getOpenShellSandboxDescriptor("nemoclaw-9090", "alpha", test.deps), + ).resolves.toEqual({ + id: "sb-id", + name: "alpha", + image: "nvcr.io/nvidia/nemoclaw:test", + }); + expect(test.createGrpc).toHaveBeenCalledWith("nemoclaw-9090"); + expect(test.getSandboxDescriptor).toHaveBeenCalledWith("alpha"); + expect(test.createCli).not.toHaveBeenCalled(); + expect(test.cliExec).not.toHaveBeenCalled(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("propagates read failures, closes, and never falls back to the CLI", async () => { + const error = new Error("descriptor unavailable"); + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + test.getSandboxDescriptor.mockRejectedValue(error); + + await expect(getOpenShellSandboxDescriptor("nemoclaw", "alpha", test.deps)).rejects.toBe(error); + expect(test.createCli).not.toHaveBeenCalled(); + expect(test.cliExec).not.toHaveBeenCalled(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("rejects a gateway endpoint override before creating a client", async () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other.example.test"); + try { + await expect(getOpenShellSandboxDescriptor("nemoclaw", "alpha", test.deps)).rejects.toThrow( + "Unset OPENSHELL_GATEWAY_ENDPOINT", + ); + expect(test.createGrpc).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + } + }); +}); + describe("read-only OpenShell sandbox control routing", () => { it.each([ ["too many session arguments", ["openclaw", "sessions", "list", ...Array(1022).fill("x")]], diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index aa8bc47c308..d7b46218885 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { log } from "../../cli/logger"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { createGrpcOpenShellSandboxControlForGateway, OpenShellGrpcEdgeTunnelRequiredError, @@ -9,6 +10,7 @@ import { import { type GrpcOpenShellSandboxControl, OpenShellGrpcPreDispatchError, + type OpenShellSandboxDescriptor, } from "./grpc-sandbox-control"; import { createGatewayScopedCliOpenShellSandboxControl, @@ -39,6 +41,31 @@ export interface OpenShellMutationControlSelection { close(): void; } +function closeGrpc( + grpc: GrpcOpenShellSandboxControl | undefined, + dependencies: ReadOnlyRoutingDependencies, +): void { + try { + grpc?.close(); + } catch (error) { + dependencies.debug("OpenShell direct gRPC client close failed", error); + } +} + +export async function getOpenShellSandboxDescriptor( + gatewayName: string, + sandboxName: string, + dependencies: ReadOnlyRoutingDependencies = defaultDependencies, +): Promise { + assertNoOpenShellGatewayEndpointOverride(); + const grpc = dependencies.createGrpc(gatewayName); + try { + return await grpc.getSandboxDescriptor(sandboxName); + } finally { + closeGrpc(grpc, dependencies); + } +} + /** * Select one transport before a mutating workflow starts. Direct gRPC is the * default. The CLI is selected only for the explicit Cloudflare edge-tunnel @@ -54,13 +81,7 @@ export function selectOpenShellSandboxControlForMutation( return { control: grpc, transport: "grpc", - close: () => { - try { - grpc.close(); - } catch (error) { - dependencies.debug("OpenShell direct gRPC client close failed", error); - } - }, + close: () => closeGrpc(grpc, dependencies), }; } catch (error) { if (!(error instanceof OpenShellGrpcEdgeTunnelRequiredError)) throw error; @@ -128,11 +149,7 @@ export async function execSandboxReadOnlyWithGrpcFallback( return { status: null, stdout: "", stderr: "", error: cause }; } } finally { - try { - grpc.close(); - } catch (error) { - dependencies.debug("OpenShell direct gRPC client close failed", error); - } + closeGrpc(grpc, dependencies); } dependencies.debug( From 013b6f93874f7bfd1fb1ab484e0d243356bc9374 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 22:00:05 -0700 Subject: [PATCH 04/10] refactor(snapshot): read source image over gRPC Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 1 - .../snapshot-auto-create-failure.test.ts | 3 ++ .../snapshot-restore-lifecycle.test.ts | 43 +++++++++++++++++++ .../sandbox/snapshot-restore-test-fixture.ts | 16 +++++++ src/lib/actions/sandbox/snapshot.test.ts | 5 ++- src/lib/actions/sandbox/snapshot.ts | 36 +++++----------- .../openshell-sandbox-descriptor-preload.ts | 32 ++++++++++++++ test/snapshot-restore-existing-dest.test.ts | 41 +++++++++--------- 8 files changed, 128 insertions(+), 49 deletions(-) create mode 100644 test/helpers/openshell-sandbox-descriptor-preload.ts diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 755bad7e2b3..eb33d6db101 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -39,7 +39,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/actions/sandbox/host-aliases.ts", "docker-exec-command", 1], ["src/lib/actions/sandbox/sessions/passthrough.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], - ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/diagnostics/debug.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/onboard.ts", "docker-exec-builder", 1], diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index 2166ee58bf4..970c9cb169f 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -33,6 +33,9 @@ vi.mock("../../adapters/openshell/runtime", () => ({ getOpenshellBinary: vi.fn(() => "openshell"), runOpenshell: vi.fn(() => ({ status: 0, output: "" })), })); +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + getOpenShellSandboxDescriptor: vi.fn(), +})); vi.mock("../../credentials/store", () => ({ prompt: vi.fn() })); vi.mock("../../domain/sandbox/destroy", () => ({ getSandboxDeleteOutcome: vi.fn(() => ({ alreadyGone: false, gatewayUnreachable: false })), diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index fc2f75a9b8f..9294a465199 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -249,6 +249,49 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { expect(f.restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); }); + it("uses the live OpenShell descriptor image for Kubernetes snapshot clones", async () => { + let registeredClone: ReturnType = null; + f.registerSandboxMock.mockImplementation((entry) => (registeredClone = entry as never)); + f.getSandboxMock.mockImplementation((name) => + name === "alpha" + ? { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw-8090", + imageTag: "nemoclaw-alpha:stale-registry", + openshellDriver: "kubernetes", + provider: "nvidia-nim", + model: "nvidia/model-a", + } + : registeredClone, + ); + f.getOpenShellSandboxDescriptorMock.mockResolvedValue({ + id: "alpha-id", + name: "alpha", + image: "nemoclaw-alpha:live-descriptor", + }); + f.captureOpenshellMock.mockImplementation((args) => + f.openshellResponses(args, { + "sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") }, + "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, + }), + ); + f.getLatestBackupMock.mockReturnValue({ ...f.latestBackupFixture }); + const { runSandboxSnapshot } = await import("./snapshot"); + + await runSandboxSnapshot("alpha", { kind: "restore", to: "beta" }); + + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenCalledTimes(2); + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith( + 1, + "nemoclaw-8090", + "alpha", + ); + const createArgs = f.streamSandboxCreateMock.mock.calls[0]?.[1] ?? []; + expect(createArgs).toContain("nemoclaw-alpha:live-descriptor"); + expect(createArgs).not.toContain("nemoclaw-alpha:stale-registry"); + }); + it("blocks auto-create before deleting a destination when a gateway peer conflicts", async () => { const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); f.getSandboxMock.mockImplementation((name) => ({ diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index e0117b0f9b1..f0c072618ae 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -114,6 +114,13 @@ export const getCustomPoliciesMock = vi.fn( () => [] as Array<{ name: string; content: string; sourcePath?: string }>, ); export const getLatestBackupMock = vi.fn(() => null as Record | null); +export const getOpenShellSandboxDescriptorMock = vi.fn( + async (_gatewayName: string, sandboxName: string) => ({ + id: `${sandboxName}-id`, + name: sandboxName, + image: `nemoclaw-${sandboxName}:live`, + }), +); export const applyPresetMock = vi.fn((_sandbox: string, _preset: string) => true); export const applyPresetContentMock = vi.fn( (_sandbox: string, _name: string, _content: string, _options?: unknown) => true, @@ -162,6 +169,10 @@ vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: runOpenshellMock, })); +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + getOpenShellSandboxDescriptor: getOpenShellSandboxDescriptorMock, +})); + vi.mock("../../credentials/store", () => ({ prompt: vi.fn(), })); @@ -261,6 +272,11 @@ export function resetSnapshotRestoreMocks(): void { getAppliedPresetsMock.mockReturnValue([]); getCustomPoliciesMock.mockReturnValue([]); getLatestBackupMock.mockReturnValue(null); + getOpenShellSandboxDescriptorMock.mockImplementation(async (_gatewayName, sandboxName) => ({ + id: `${sandboxName}-id`, + name: sandboxName, + image: `nemoclaw-${sandboxName}:live`, + })); applyPresetMock.mockReturnValue(true); applyPresetContentMock.mockReturnValue(true); removePresetMock.mockReturnValue(true); diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 52b189a727b..69a92999644 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -146,7 +146,6 @@ const latestBackupFixture = { }; vi.mock("../../adapters/docker", () => ({ - dockerCapture: vi.fn(() => ""), dockerInspect: dockerInspectMock, })); @@ -156,6 +155,10 @@ vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: runOpenshellMock, })); +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + getOpenShellSandboxDescriptor: vi.fn(), +})); + vi.mock("../../credentials/store", () => ({ prompt: vi.fn(), })); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 89af67ce0db..9240a5908e8 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -3,12 +3,12 @@ import fs from "node:fs"; import path from "node:path"; -import { dockerCapture } from "../../adapters/docker"; import { captureOpenshell, getOpenshellBinary, runOpenshell, } from "../../adapters/openshell/runtime"; +import { getOpenShellSandboxDescriptor } from "../../adapters/openshell/sandbox-control-routing"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; @@ -152,14 +152,14 @@ function renderSnapshotTable( } } -// Resolve the running src pod's image. Docker- and VM-driver sandboxes don't -// have the legacy cluster container — trust the registered imageTag and fail -// fast if it's missing. Only the "kubernetes" driver falls back to the -// kubectl probe inside the gateway container. -function resolveSrcPodImage( +// Resolve the running source sandbox's image. Docker- and VM-driver sandboxes +// trust the registered imageTag. Kubernetes sandboxes use OpenShell's strict +// descriptor read instead of reaching through the gateway container to run +// kubectl on OpenShell's internal cluster. +async function resolveSrcPodImage( srcName: string, srcEntry?: SandboxEntry | { name: string }, -): string | null { +): Promise { const registeredImage = (srcEntry as { imageTag?: string | null } | undefined)?.imageTag; const registeredDriver = (srcEntry as { openshellDriver?: string | null } | undefined) ?.openshellDriver; @@ -170,24 +170,8 @@ function resolveSrcPodImage( const srcGatewayName = resolveSandboxGatewayName( srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, ); - const gatewayContainer = `openshell-cluster-${srcGatewayName}`; try { - const output = dockerCapture( - [ - "exec", - gatewayContainer, - "kubectl", - "get", - "pod", - srcName, - "-n", - "openshell", - "-o", - 'jsonpath={.spec.containers[?(@.name=="agent")].image}', - ], - { ignoreError: true, timeout: 10000 }, - ); - return output.trim().split(/\s+/)[0] || null; + return (await getOpenShellSandboxDescriptor(srcGatewayName, srcName)).image; } catch { return null; } @@ -959,7 +943,7 @@ async function runSnapshotRestoreUnlocked( snapshotExit(1); } const srcEntry = registry.getSandbox(sandboxName) || { name: sandboxName }; - const fromImage = resolveSrcPodImage(sandboxName, srcEntry); + const fromImage = await resolveSrcPodImage(sandboxName, srcEntry); if (!fromImage) { console.error( ` Cannot resolve image for source sandbox '${sandboxName}' — aborting before ` + @@ -1005,7 +989,7 @@ async function runSnapshotRestoreUnlocked( ); snapshotExit(1); } - const lockedFromImage = resolveSrcPodImage(sandboxName, lockedSourceEntry); + const lockedFromImage = await resolveSrcPodImage(sandboxName, lockedSourceEntry); if (!lockedFromImage) { console.error( ` Cannot resolve the current image for source sandbox '${sandboxName}' — aborting before changing '${targetSandbox}'.`, diff --git a/test/helpers/openshell-sandbox-descriptor-preload.ts b/test/helpers/openshell-sandbox-descriptor-preload.ts new file mode 100644 index 00000000000..f515e46b36b --- /dev/null +++ b/test/helpers/openshell-sandbox-descriptor-preload.ts @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +/** Replace only the strict descriptor read in fake-OpenShell CLI subprocess tests. */ +export function writeOpenShellSandboxDescriptorPreload(home: string, image: string): string { + const preload = path.join(home, "openshell-sandbox-descriptor-preload.cjs"); + fs.writeFileSync( + preload, + `const Module = require("node:module"); +const originalLoad = Module._load; +Module._load = function loadWithSandboxDescriptor(request, parent, isMain) { + const loaded = originalLoad.call(this, request, parent, isMain); + if (typeof request === "string" && /sandbox-control-routing(?:\\.[cm]?[jt]s)?$/.test(request)) { + return { + ...loaded, + getOpenShellSandboxDescriptor: async (_gatewayName, sandboxName) => ({ + id: sandboxName + "-id", + name: sandboxName, + image: ${JSON.stringify(image)}, + }), + }; + } + return loaded; +}; +`, + { mode: 0o600 }, + ); + return [process.env.NODE_OPTIONS, `--require=${preload}`].filter(Boolean).join(" "); +} diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index fc30cafb93a..ed152c8b2e9 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -7,8 +7,8 @@ // or --yes / NEMOCLAW_NON_INTERACTIVE=1) to delete-and-recreate the // destination from the snapshot. // -// The --force path preflights both the snapshot selector and the source pod -// image *before* deleting anything (#3756 P1 Codex). A bad selector, a +// The --force path preflights both the snapshot selector and the live source +// descriptor *before* deleting anything (#3756 P1 Codex). A bad selector, a // missing snapshot, or an unresolvable source image must not be allowed to // delete `dst` and only fail afterwards. @@ -17,8 +17,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, it, expect } from "vitest"; +import { describe, expect, it } from "vitest"; +import { writeOpenShellSandboxDescriptorPreload } from "./helpers/openshell-sandbox-descriptor-preload"; import { execTimeout } from "./helpers/timeouts"; const CLI = path.join(import.meta.dirname, "..", "bin", "nemoclaw.js"); @@ -56,7 +57,7 @@ function runCli( interface MakeEnvOptions { /** When false, omit the snapshot manifest so getLatestBackup returns null. */ withSnapshot?: boolean; - /** When false, fake docker exec returns an empty image string. */ + /** When false, return an empty image from the live source descriptor. */ withSourceImage?: boolean; /** Put dst on a registered non-default gateway and hide it from src's gateway list. */ destinationGatewayPort?: number; @@ -78,10 +79,7 @@ interface MakeEnvOptions { * - `sandbox delete dst` exits 0 (and logs the call) * - `sandbox create` exits non-zero (intentional; the integration tests * only need to verify control flow reached/passed the delete step) - * - fake docker that: - * - `inspect ... State.Running` returns "true" (gateway up) - * - `exec ... kubectl get pod src ...` returns an image string (or empty - * when withSourceImage=false), exercising resolveSrcPodImage's preflight + * - fake docker whose `inspect ... State.Running` returns "true" (gateway up) */ function makeExistingDestEnv( prefix: string, @@ -149,6 +147,10 @@ function makeExistingDestEnv( } const osLog = path.join(home, "openshell.log"); + const descriptorNodeOptions = writeOpenShellSandboxDescriptorPreload( + home, + opts.withSourceImage === false ? "" : "ghcr.io/nvidia/nemoclaw/sandbox-src:test", + ); const activeGateway = path.join(home, "active-gateway"); fs.writeFileSync( path.join(localBin, "openshell"), @@ -190,8 +192,6 @@ function makeExistingDestEnv( { mode: 0o755 }, ); - const sourceImageOutput = - opts.withSourceImage === false ? "" : "ghcr.io/nvidia/nemoclaw/sandbox-src:test"; fs.writeFileSync( path.join(localBin, "docker"), [ @@ -203,20 +203,19 @@ function makeExistingDestEnv( ' echo "true"', " exit 0", "fi", - 'if [ "$1" = "exec" ]; then', - // The action calls `docker exec kubectl get pod ...`. - // Return the configured image (or an empty string to simulate - // "image cannot be resolved", which #3756 P1 says must abort before - // we touch the destination). - ` printf '%s' ${JSON.stringify(sourceImageOutput)}`, - " exit 0", - "fi", "exit 0", ].join("\n"), { mode: 0o755 }, ); - return { env: { HOME: home, PATH: `${localBin}:${process.env.PATH ?? ""}` }, osLog }; + return { + env: { + HOME: home, + NODE_OPTIONS: descriptorNodeOptions, + PATH: `${localBin}:${process.env.PATH ?? ""}`, + }, + osLog, + }; } describe("snapshot restore --to existing destination (#3756)", () => { @@ -242,8 +241,8 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).not.toMatch(/sandbox delete dst/); }); - it("refuses by default before running source-image preflight per Codex P2 review (#3796)", () => { - // Existing destination + unresolvable source image. The user must see the + it("refuses by default before running source-descriptor preflight (#3796)", () => { + // Existing destination + invalid source descriptor. The user must see the // precise "destination exists" error, not the "cannot resolve image" // misdirection that would land if the refusal came after preflight. const { env } = makeExistingDestEnv("nemoclaw-snap-restore-refuse-before-preflight-", { From 6ebca2ccdaa90c5b4ac3d15a1d74d888d1000e66 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 22:24:16 -0700 Subject: [PATCH 05/10] test(snapshot): bound descriptor preload seam Signed-off-by: Aaron Erickson --- ...enshell-sandbox-descriptor-preload.test.ts | 70 +++++++++++++++++++ .../openshell-sandbox-descriptor-preload.ts | 18 ++++- 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 test/helpers/openshell-sandbox-descriptor-preload.test.ts diff --git a/test/helpers/openshell-sandbox-descriptor-preload.test.ts b/test/helpers/openshell-sandbox-descriptor-preload.test.ts new file mode 100644 index 00000000000..4f2be5a1dec --- /dev/null +++ b/test/helpers/openshell-sandbox-descriptor-preload.test.ts @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { expect, it } from "vitest"; + +import { writeOpenShellSandboxDescriptorPreload } from "./openshell-sandbox-descriptor-preload"; + +it("overrides only the configured sandbox routing module", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-descriptor-preload-")); + try { + const routingDirectory = path.join(home, "adapters", "openshell"); + const snapshotDirectory = path.join(home, "actions", "sandbox"); + fs.mkdirSync(routingDirectory, { recursive: true }); + fs.mkdirSync(snapshotDirectory, { recursive: true }); + const routingModule = path.join(routingDirectory, "sandbox-control-routing.js"); + const snapshotModule = path.join(snapshotDirectory, "snapshot.cjs"); + const unrelatedModule = path.join(home, "unrelated.cjs"); + fs.writeFileSync(routingModule, 'module.exports = { source: "routing-original" };\n'); + fs.writeFileSync( + snapshotModule, + 'module.exports = require("../../adapters/openshell/sandbox-control-routing");\n', + ); + fs.writeFileSync(unrelatedModule, 'module.exports = { source: "unrelated-original" };\n'); + const nodeOptions = writeOpenShellSandboxDescriptorPreload(home, "sandbox:test"); + + const output = execFileSync( + process.execPath, + [ + "-e", + `const routing = require(process.env.SNAPSHOT_MODULE); +const directRouting = require(process.env.ROUTING_MODULE); +const unrelated = require(process.env.UNRELATED_MODULE); +routing.getOpenShellSandboxDescriptor("nemoclaw", "alpha").then((descriptor) => { + process.stdout.write(JSON.stringify({ + descriptor, + directRouting, + directRoutingWasOverridden: typeof directRouting.getOpenShellSandboxDescriptor === "function", + routingSource: routing.source, + unrelated, + })); +});`, + ], + { + encoding: "utf8", + env: { + ...process.env, + NODE_OPTIONS: nodeOptions, + ROUTING_MODULE: routingModule, + SNAPSHOT_MODULE: snapshotModule, + UNRELATED_MODULE: unrelatedModule, + }, + }, + ); + + expect(JSON.parse(output)).toEqual({ + descriptor: { id: "alpha-id", image: "sandbox:test", name: "alpha" }, + directRouting: { source: "routing-original" }, + directRoutingWasOverridden: false, + routingSource: "routing-original", + unrelated: { source: "unrelated-original" }, + }); + } finally { + fs.rmSync(home, { force: true, recursive: true }); + } +}); diff --git a/test/helpers/openshell-sandbox-descriptor-preload.ts b/test/helpers/openshell-sandbox-descriptor-preload.ts index f515e46b36b..5409c92d1cf 100644 --- a/test/helpers/openshell-sandbox-descriptor-preload.ts +++ b/test/helpers/openshell-sandbox-descriptor-preload.ts @@ -4,7 +4,18 @@ import fs from "node:fs"; import path from "node:path"; -/** Replace only the strict descriptor read in fake-OpenShell CLI subprocess tests. */ +/** + * Replace the strict descriptor read in fake-OpenShell CLI subprocess tests. + * + * Those fixtures provide a fake `openshell` executable, but descriptor reads + * bypass the CLI and connect directly to the gateway's gRPC endpoint. They + * therefore cannot model this response with another fake CLI argv branch. + * Limit the child-process interception to the one exact compiled + * snapshot-to-routing import edge; unrelated module loads retain Node's + * normal result. Remove this + * preload when the subprocess harness owns a fake gRPC gateway (or official + * bindings expose a fixture-local injectable client). + */ export function writeOpenShellSandboxDescriptorPreload(home: string, image: string): string { const preload = path.join(home, "openshell-sandbox-descriptor-preload.cjs"); fs.writeFileSync( @@ -13,7 +24,10 @@ export function writeOpenShellSandboxDescriptorPreload(home: string, image: stri const originalLoad = Module._load; Module._load = function loadWithSandboxDescriptor(request, parent, isMain) { const loaded = originalLoad.call(this, request, parent, isMain); - if (typeof request === "string" && /sandbox-control-routing(?:\\.[cm]?[jt]s)?$/.test(request)) { + const fromSnapshot = + typeof parent?.filename === "string" && + /[\\/]actions[\\/]sandbox[\\/]snapshot\\.[cm]?js$/.test(parent.filename); + if (fromSnapshot && request === "../../adapters/openshell/sandbox-control-routing") { return { ...loaded, getOpenShellSandboxDescriptor: async (_gatewayName, sandboxName) => ({ From 7a3d3ffb8af33e78fe105c8ab1a6d60490cfcd7a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 22:34:39 -0700 Subject: [PATCH 06/10] ci: retry PR advisor analysis Signed-off-by: Aaron Erickson From 77e65534633db6e86b1d9a1a81cbaafadb4c7922 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 22:08:49 -0700 Subject: [PATCH 07/10] refactor(snapshot): pin live restore source descriptors Signed-off-by: Aaron Erickson --- .../snapshot-auto-create-failure.test.ts | 7 +- .../snapshot-restore-lifecycle.test.ts | 87 +-- .../sandbox/snapshot-restore-source.test.ts | 160 +++++ .../sandbox/snapshot-restore-source.ts | 74 +++ src/lib/actions/sandbox/snapshot.test.ts | 611 +----------------- src/lib/actions/sandbox/snapshot.ts | 191 +++--- test/snapshot-gateway-guard.test.ts | 23 +- test/snapshot-restore-existing-dest.test.ts | 15 +- 8 files changed, 413 insertions(+), 755 deletions(-) create mode 100644 src/lib/actions/sandbox/snapshot-restore-source.test.ts create mode 100644 src/lib/actions/sandbox/snapshot-restore-source.ts diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index 970c9cb169f..07dd02030dd 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -20,6 +20,11 @@ const getSandboxMock = vi.fn((name?: string) => ); const registerSandboxMock = vi.fn(); const restoreSandboxStateMock = vi.fn(); +const getOpenShellSandboxDescriptorMock = vi.fn(async (_gateway: string, name: string) => ({ + id: `${name}-id`, + name, + image: "nemoclaw-alpha:live", +})); const streamSandboxCreateMock = vi.fn(async () => ({ status: 7, output: "create failed before registry write", @@ -34,7 +39,7 @@ vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: vi.fn(() => ({ status: 0, output: "" })), })); vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ - getOpenShellSandboxDescriptor: vi.fn(), + getOpenShellSandboxDescriptor: getOpenShellSandboxDescriptorMock, })); vi.mock("../../credentials/store", () => ({ prompt: vi.fn() })); vi.mock("../../domain/sandbox/destroy", () => ({ diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index 9294a465199..af707dfbe55 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -185,6 +185,26 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { }); it("hardens an active timer window before force-deleting a restore destination", async () => { + const mutationOrder: string[] = []; + f.getOpenShellSandboxDescriptorMock.mockImplementation(async (_gateway, sandboxName) => { + mutationOrder.push("read descriptor"); + return { + id: `${sandboxName}-id`, + name: sandboxName, + image: "nemoclaw-alpha:live-descriptor", + }; + }); + f.runOpenshellMock.mockImplementation((args) => { + if (args[0] === "sandbox" && args[1] === "delete") { + mutationOrder.push("delete"); + f.lifecycleMock.events.push("delete"); + } + return { status: 0, output: "" }; + }); + f.streamSandboxCreateMock.mockImplementation(async () => { + mutationOrder.push("create"); + return { status: 0, output: "", sawProgress: false, forcedReady: false }; + }); f.lifecycleMock.readTimerMarkerMock.mockReturnValue({ pid: 4242, sandboxName: "beta", @@ -246,50 +266,43 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { f.lifecycleMock.events.indexOf("cleanup-shields"), ); expect(f.streamSandboxCreateMock).toHaveBeenCalled(); + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith(1, "nemoclaw", "alpha"); + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith(2, "nemoclaw", "alpha"); + expect(f.streamSandboxCreateMock.mock.calls[0]?.[1]).toContain( + "nemoclaw-alpha:live-descriptor", + ); + expect(mutationOrder).toEqual(["read descriptor", "read descriptor", "delete", "create"]); expect(f.restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); }); - it("uses the live OpenShell descriptor image for Kubernetes snapshot clones", async () => { - let registeredClone: ReturnType = null; - f.registerSandboxMock.mockImplementation((entry) => (registeredClone = entry as never)); - f.getSandboxMock.mockImplementation((name) => - name === "alpha" - ? { - name: "alpha", - agent: "openclaw", - gatewayName: "nemoclaw-8090", - imageTag: "nemoclaw-alpha:stale-registry", - openshellDriver: "kubernetes", - provider: "nvidia-nim", - model: "nvidia/model-a", - } - : registeredClone, - ); - f.getOpenShellSandboxDescriptorMock.mockResolvedValue({ - id: "alpha-id", - name: "alpha", - image: "nemoclaw-alpha:live-descriptor", - }); - f.captureOpenshellMock.mockImplementation((args) => - f.openshellResponses(args, { - "sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") }, - "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, - }), - ); + it("does not delete or create when the live source descriptor drifts", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); + f.getSandboxMock.mockImplementation((name) => ({ + name: name ?? "alpha", + agent: "openclaw", + provider: "nvidia-nim", + model: "nvidia/model-a", + })); + f.parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"])); f.getLatestBackupMock.mockReturnValue({ ...f.latestBackupFixture }); + f.getOpenShellSandboxDescriptorMock + .mockResolvedValueOnce({ id: "alpha-id", name: "alpha", image: "alpha:v1" }) + .mockResolvedValueOnce({ id: "alpha-id", name: "alpha", image: "alpha:v2" }); const { runSandboxSnapshot } = await import("./snapshot"); - await runSandboxSnapshot("alpha", { kind: "restore", to: "beta" }); + await expect( + runSandboxSnapshot("alpha", { + kind: "restore", + to: "beta", + force: true, + yes: true, + }), + ).rejects.toMatchObject({ exitCode: 1 }); - expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenCalledTimes(2); - expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith( - 1, - "nemoclaw-8090", - "alpha", - ); - const createArgs = f.streamSandboxCreateMock.mock.calls[0]?.[1] ?? []; - expect(createArgs).toContain("nemoclaw-alpha:live-descriptor"); - expect(createArgs).not.toContain("nemoclaw-alpha:stale-registry"); + expect(consoleError.mock.calls.flat().join("\n")).toContain("Source sandbox image changed"); + expect(f.lifecycleMock.events).not.toContain("delete"); + expect(f.streamSandboxCreateMock).not.toHaveBeenCalled(); + expect(f.registerSandboxMock).not.toHaveBeenCalled(); }); it("blocks auto-create before deleting a destination when a gateway peer conflicts", async () => { diff --git a/src/lib/actions/sandbox/snapshot-restore-source.test.ts b/src/lib/actions/sandbox/snapshot-restore-source.test.ts new file mode 100644 index 00000000000..a3195b3af4c --- /dev/null +++ b/src/lib/actions/sandbox/snapshot-restore-source.test.ts @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { + commitWithStableSnapshotRestoreSource, + type SnapshotRestoreSourceDescriptor, +} from "./snapshot-restore-source"; + +const source = { + gatewayName: "gateway-a", + id: "sandbox-id", + name: "source", + image: "registry/source@sha256:abc", +} satisfies SnapshotRestoreSourceDescriptor; + +describe("commitWithStableSnapshotRestoreSource", () => { + it("reads twice and commits only the second descriptor with preflight state", async () => { + const events: string[] = []; + const reads = [ + { ...source, readNumber: 1 }, + { ...source, readNumber: 2 }, + ]; + const readDescriptor = vi.fn(async () => { + events.push("read"); + return reads[readDescriptor.mock.calls.length - 1]; + }); + const result = await commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor, + preMutationCheck: () => { + events.push("preflight"); + return "checked"; + }, + commit: (descriptor, preflight) => { + events.push("commit"); + expect((descriptor as (typeof reads)[number]).readNumber).toBe(2); + expect(preflight).toBe("checked"); + return descriptor.image; + }, + }); + + expect(result).toBe(source.image); + expect(events).toEqual(["read", "preflight", "read", "commit"]); + expect(readDescriptor).toHaveBeenCalledTimes(2); + }); + + it("does not re-read or commit when read-only preflight fails", async () => { + const readDescriptor = vi.fn(async () => source); + const commit = vi.fn(); + await expect( + commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor, + preMutationCheck: () => { + throw new Error("unsafe destination"); + }, + commit, + }), + ).rejects.toThrow("unsafe destination"); + expect(readDescriptor).toHaveBeenCalledOnce(); + expect(commit).not.toHaveBeenCalled(); + }); + + it.each([ + ["empty id", { ...source, id: "" }], + ["padded image", { ...source, image: ` ${source.image}` }], + ])("fails closed for an invalid %s", async (_label, invalid) => { + const commit = vi.fn(); + await expect( + commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor: async () => invalid, + preMutationCheck: vi.fn(), + commit, + }), + ).rejects.toThrow(/Failed to read source sandbox before mutation/); + expect(commit).not.toHaveBeenCalled(); + }); + + it.each([ + ["name", { ...source, name: "other" }], + ["gateway", { ...source, gatewayName: "gateway-b" }], + ])("fails closed when the persisted %s does not match", async (_label, descriptor) => { + const commit = vi.fn(); + await expect( + commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor: async () => descriptor, + preMutationCheck: vi.fn(), + commit, + }), + ).rejects.toThrow(/does not match the persisted source route/); + expect(commit).not.toHaveBeenCalled(); + }); + + it.each([ + "gatewayName", + "id", + "name", + "image", + ] as const)("fails closed when source %s drifts", async (key) => { + const commit = vi.fn(); + const values = [source[key], `${source[key]}-changed`]; + const readDescriptor = vi.fn(async () => ({ + ...source, + [key]: values[readDescriptor.mock.calls.length - 1], + })); + await expect( + commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor, + preMutationCheck: vi.fn(), + commit, + }), + ).rejects.toThrow(`Source sandbox ${key} changed`); + expect(commit).not.toHaveBeenCalled(); + }); + + it.each([1, 2])("fails closed when descriptor read %i fails", async (failedRead) => { + const commit = vi.fn(); + const preMutationCheck = vi.fn(); + let calls = 0; + await expect( + commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor: async () => { + calls += 1; + if (calls === failedRead) throw new Error("unavailable"); + return source; + }, + preMutationCheck, + commit, + }), + ).rejects.toThrow(/Failed to read source sandbox .*mutation: unavailable/); + expect(preMutationCheck).toHaveBeenCalledTimes(failedRead - 1); + expect(commit).not.toHaveBeenCalled(); + }); + + it("preserves mutation failures without relabeling them as descriptor failures", async () => { + const failure = new Error("create failed"); + await expect( + commitWithStableSnapshotRestoreSource({ + gatewayName: source.gatewayName, + sandboxName: source.name, + readDescriptor: async () => source, + preMutationCheck: vi.fn(), + commit: () => { + throw failure; + }, + }), + ).rejects.toBe(failure); + }); +}); diff --git a/src/lib/actions/sandbox/snapshot-restore-source.ts b/src/lib/actions/sandbox/snapshot-restore-source.ts new file mode 100644 index 00000000000..9457c2f8a8a --- /dev/null +++ b/src/lib/actions/sandbox/snapshot-restore-source.ts @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export interface SnapshotRestoreSourceDescriptor { + gatewayName: string; + id: string; + name: string; + image: string; +} + +export type SnapshotRestoreSourceReader = ( + sandboxName: string, +) => Promise; + +export class SnapshotRestoreSourceError extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "SnapshotRestoreSourceError"; + } +} + +interface StableSourceOptions { + gatewayName: string; + sandboxName: string; + readDescriptor: SnapshotRestoreSourceReader; + preMutationCheck: () => Promise | TPreflight; + commit: ( + descriptor: SnapshotRestoreSourceDescriptor, + preflight: TPreflight, + ) => Promise | TResult; +} + +function checkedDescriptor( + descriptor: SnapshotRestoreSourceDescriptor, +): SnapshotRestoreSourceDescriptor { + for (const key of ["gatewayName", "id", "name", "image"] as const) { + const value = descriptor[key]; + if (!value || value.trim() !== value) { + throw new Error(`OpenShell sandbox descriptor has an invalid ${key}.`); + } + } + return { ...descriptor }; +} + +export async function commitWithStableSnapshotRestoreSource( + options: StableSourceOptions, +): Promise { + const read = async (phase: string) => { + try { + return checkedDescriptor(await options.readDescriptor(options.sandboxName)); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new SnapshotRestoreSourceError(`Failed to read source sandbox ${phase}: ${detail}`, { + cause: error, + }); + } + }; + const pinned = await read("before mutation"); + if (pinned.gatewayName !== options.gatewayName || pinned.name !== options.sandboxName) { + throw new SnapshotRestoreSourceError( + "OpenShell sandbox descriptor does not match the persisted source route.", + ); + } + const preflight = await options.preMutationCheck(); + const current = await read("immediately before mutation"); + for (const key of ["gatewayName", "id", "name", "image"] as const) { + if (current[key] !== pinned[key]) { + throw new SnapshotRestoreSourceError( + `Source sandbox ${key} changed before snapshot restore mutation.`, + ); + } + } + return options.commit(current, preflight); +} diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 69a92999644..9515af756fb 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -106,6 +106,13 @@ const getCustomPoliciesMock = vi.fn( () => [] as Array<{ name: string; content: string; sourcePath?: string }>, ); const getLatestBackupMock = vi.fn(() => null as Record | null); +const getOpenShellSandboxDescriptorMock = vi.fn( + async (_gatewayName: string, sandboxName: string) => ({ + id: `${sandboxName}-id`, + name: sandboxName, + image: `nemoclaw-${sandboxName}:live`, + }), +); const applyPresetMock = vi.fn((_sandbox: string, _preset: string) => true); const applyPresetContentMock = vi.fn( (_sandbox: string, _name: string, _content: string, _options?: unknown) => true, @@ -156,7 +163,7 @@ vi.mock("../../adapters/openshell/runtime", () => ({ })); vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ - getOpenShellSandboxDescriptor: vi.fn(), + getOpenShellSandboxDescriptor: getOpenShellSandboxDescriptorMock, })); vi.mock("../../credentials/store", () => ({ @@ -259,6 +266,11 @@ describe("runSandboxSnapshot", () => { getAppliedPresetsMock.mockReturnValue([]); getCustomPoliciesMock.mockReturnValue([]); getLatestBackupMock.mockReturnValue(null); + getOpenShellSandboxDescriptorMock.mockImplementation(async (_gatewayName, sandboxName) => ({ + id: `${sandboxName}-id`, + name: sandboxName, + image: `nemoclaw-${sandboxName}:live`, + })); applyPresetMock.mockReturnValue(true); applyPresetContentMock.mockReturnValue(true); removePresetMock.mockReturnValue(true); @@ -791,603 +803,6 @@ describe("runSandboxSnapshot", () => { expect(output).toContain("alpha snapshot restore"); }); - it("restores the latest snapshot into the source sandbox", async () => { - const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}); - getLatestBackupMock.mockReturnValue({ - snapshotVersion: 4, - name: "stable", - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - }); - restoreSandboxStateMock.mockReturnValue({ - success: true, - restoredDirs: ["workspace"], - restoredFiles: ["user.md"], - failedDirs: [], - failedFiles: [], - }); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(restoreSandboxStateMock).toHaveBeenCalledWith("alpha", "/tmp/backup-alpha"); - const output = consoleLog.mock.calls.flat().join("\n"); - expect(output).toContain("Using latest snapshot v4 name=stable"); - expect(output).toContain("Restoring snapshot into 'alpha'"); - expect(output).toContain("Restored 1 directories, 1 files"); - }); - - it("keeps active-timer restore, permission repair, and policy reconciliation serialized", async () => { - lifecycleMock.readTimerMarkerMock.mockReturnValue({ - pid: 4242, - sandboxName: "alpha", - snapshotPath: "/tmp/policy.yaml", - restoreAt: "2026-06-27T06:00:00.000Z", - processToken: "a".repeat(32), - }); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: ["github"], - }); - restoreSandboxStateMock.mockReturnValue({ - success: true, - restoredDirs: ["workspace"], - restoredFiles: ["openclaw.json"], - failedDirs: [], - failedFiles: [], - }); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(lifecycleMock.events).toContain("lock:restore sandbox snapshot"); - expect(restoreSandboxStateMock).toHaveBeenCalledWith("alpha", "/tmp/backup-alpha"); - expect(shieldsMock.repairMutableConfigPermsMock).toHaveBeenCalledWith("alpha"); - expect(applyPresetMock).toHaveBeenCalledWith("alpha", "github"); - }); - - it("hardens an active timer window before force-deleting a restore destination", async () => { - lifecycleMock.readTimerMarkerMock.mockReturnValue({ - pid: 4242, - sandboxName: "beta", - snapshotPath: "/tmp/policy.yaml", - restoreAt: "2026-06-27T06:00:00.000Z", - processToken: "b".repeat(32), - }); - getSandboxMock.mockImplementation((name) => - name === "alpha" - ? { - name: "alpha", - agent: "openclaw", - imageTag: "nemoclaw-alpha:test", - openshellDriver: "docker", - provider: "nvidia-nim", - model: "nvidia/model-a", - } - : { - name: "beta", - agent: "openclaw", - imageTag: "nemoclaw-beta:test", - openshellDriver: "docker", - provider: "nvidia-nim", - model: "nvidia/model-a", - }, - ); - parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"])); - captureOpenshellMock.mockImplementation((args) => - openshellResponses(args, { - "sandbox exec": { status: 0, output: dcodeProbeOutput("no-runtime") }, - "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, - }), - ); - getLatestBackupMock.mockReturnValue({ ...latestBackupFixture }); - restoreSandboxStateMock.mockReturnValue({ - success: true, - restoredDirs: ["workspace"], - restoredFiles: ["user.md"], - failedDirs: [], - failedFiles: [], - }); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { - kind: "restore", - to: "beta", - force: true, - yes: true, - }); - - expect(shieldsMock.shieldsUpMock).toHaveBeenCalledWith("beta", { - throwOnError: true, - allowLegacyHermesProtocol: true, - }); - expect(lifecycleMock.events.indexOf("harden")).toBeLessThan( - lifecycleMock.events.indexOf("delete"), - ); - expect(lifecycleMock.events.indexOf("delete")).toBeLessThan( - lifecycleMock.events.indexOf("cleanup-shields"), - ); - expect(streamSandboxCreateMock).toHaveBeenCalled(); - expect(restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); - }); - - it("blocks auto-create before deleting a destination when a gateway peer conflicts", async () => { - const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); - getSandboxMock.mockImplementation((name) => ({ - name: name ?? "alpha", - agent: "openclaw", - gatewayName: "nemoclaw", - imageTag: `nemoclaw-${name}:test`, - openshellDriver: "docker", - provider: name === "gamma" ? "anthropic-prod" : "nvidia-nim", - model: name === "gamma" ? "claude-new" : "nvidia/model-a", - })); - parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"])); - captureOpenshellMock.mockImplementation((args) => - openshellResponses(args, { - "sandbox exec": { status: 0, output: dcodeProbeOutput("no-runtime") }, - "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, - }), - ); - getLatestBackupMock.mockReturnValue({ ...latestBackupFixture }); - const { runSandboxSnapshot } = await import("./snapshot"); - - await expect( - runSandboxSnapshot("alpha", { - kind: "restore", - to: "beta", - force: true, - yes: true, - }), - ).rejects.toMatchObject({ exitCode: 1 }); - - expect(consoleError.mock.calls.flat().join("\n")).toContain("gamma"); - expect(lifecycleMock.events).not.toContain("delete"); - expect(streamSandboxCreateMock).not.toHaveBeenCalled(); - expect(registerSandboxMock).not.toHaveBeenCalled(); - }); - - it.each([ - { enabled: true, expectedValue: "1" }, - { enabled: false, expectedValue: "0" }, - ])("starts a snapshot clone with the authoritative source observability state when enabled=$enabled", async ({ - enabled, - expectedValue, - }) => { - let registeredClone: SandboxRecord | null = null; - registerSandboxMock.mockImplementation((entry) => (registeredClone = entry as SandboxRecord)); - vi.stubEnv("NEMOCLAW_OBSERVABILITY", "1"); - getSandboxMock.mockImplementation((name) => - name === "alpha" - ? { - name: "alpha", - agent: "langchain-deepagents-code", - imageTag: "nemoclaw-alpha:test", - openshellDriver: "docker", - observabilityEnabled: enabled, - provider: "nvidia-nim", - model: "nvidia/model-a", - } - : registeredClone, - ); - captureOpenshellMock.mockImplementation((args) => - openshellResponses(args, { - "sandbox exec": { status: 0, output: dcodeProbeOutput("idle") }, - "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, - }), - ); - parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha"])); - getLatestBackupMock.mockReturnValue({ ...latestBackupFixture }); - const { runSandboxSnapshot } = await import("./snapshot"); - await runSandboxSnapshot("alpha", { kind: "restore", to: "beta" }); - const createCall = streamSandboxCreateMock.mock.calls[0] ?? []; - const createArgs = createCall[1] as readonly string[]; - const createEnv = createCall[2] as NodeJS.ProcessEnv | undefined; - expect(createCall[0]).toBe("openshell"); - expect(createArgs).toContain(`NEMOCLAW_OBSERVABILITY=${expectedValue}`); - expect(createEnv?.NEMOCLAW_OBSERVABILITY).toBeUndefined(); - expect(registerSandboxMock).toHaveBeenCalledWith( - expect.objectContaining({ - name: "beta", - observabilityEnabled: enabled, - }), - ); - expect(applyPresetMock).toHaveBeenCalledTimes(enabled ? 1 : 0); - }); - - it.each([ - { label: "recorded", policyPresets: ["npm"] }, - { label: "legacy", policyPresets: undefined }, - ])("adds built-in OTLP egress for a $label snapshot", async ({ policyPresets }) => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: true, - policyTier: "balanced", - } as never); - getLatestBackupMock.mockReturnValue({ ...latestBackupFixture, policyPresets }); - getAppliedPresetsMock.mockReturnValue(["npm"]); - const { runSandboxSnapshot } = await import("./snapshot"); - await runSandboxSnapshot("alpha", { kind: "restore" }); - expect(applyPresetMock).toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(removePresetMock).not.toHaveBeenCalled(); - }); - - it("removes historical built-in OTLP egress when observability was disabled after the snapshot", async () => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: ["npm", "observability-otlp-local"], - }); - getAppliedPresetsMock.mockReturnValue(["npm", "observability-otlp-local"]); - getPresetContentGatewayStateMock.mockReturnValueOnce("match").mockReturnValueOnce("absent"); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(removePresetMock).toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(applyPresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - }); - - it("removes an exact unrecorded built-in OTLP policy when observability is disabled", async () => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - policies: [], - } as never); - getLatestBackupMock.mockReturnValue({ ...latestBackupFixture, policyPresets: [] }); - getAppliedPresetsMock.mockReturnValue([]); - getPresetContentGatewayStateMock.mockReturnValueOnce("match").mockReturnValueOnce("absent"); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(getPresetContentGatewayStateMock).toHaveBeenCalledWith( - "alpha", - builtinObservabilityPolicy, - ); - expect(removePresetMock).toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(updateSandboxMock).not.toHaveBeenCalled(); - }); - - it.each([ - { - label: "returns false", - configureRemoval: () => removePresetMock.mockReturnValue(false), - }, - { - label: "throws", - configureRemoval: () => - removePresetMock.mockImplementation(() => { - throw new Error("remove exploded"); - }), - }, - { - label: "claims success without removing", - configureRemoval: () => removePresetMock.mockReturnValue(true), - }, - ])("retains built-in OTLP attribution when removal $label", async ({ configureRemoval }) => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - policies: [], - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: [], - }); - getAppliedPresetsMock.mockReturnValue([]); - getPresetContentGatewayStateMock.mockReturnValue("match"); - configureRemoval(); - const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(getPresetContentGatewayStateMock).toHaveBeenCalledTimes(2); - expect(updateSandboxMock).toHaveBeenCalledWith("alpha", { - policies: ["observability-otlp-local"], - }); - expect(consoleWarn.mock.calls.flat().join("\n")).toContain( - "exact content still live after remove", - ); - }); - - it("does not resurrect an earlier removed preset while restoring unverified OTLP attribution", async () => { - let registryEntry = { - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - policies: ["github", "observability-otlp-local"], - }; - getSandboxMock.mockImplementation(() => registryEntry as never); - updateSandboxMock.mockImplementation((_sandboxName, update) => { - registryEntry = { ...registryEntry, ...(update as Partial) }; - }); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: [], - }); - getAppliedPresetsMock.mockReturnValue(["github", "observability-otlp-local"]); - getPresetContentGatewayStateMock.mockReturnValue("match"); - removePresetMock - .mockImplementationOnce((_sandboxName, presetName) => { - expect(presetName).toBe("github"); - registryEntry = { - ...registryEntry, - policies: registryEntry.policies.filter((name) => name !== "github"), - }; - return true; - }) - .mockReturnValue(true); - vi.spyOn(console, "warn").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(removePresetMock.mock.calls.map((call) => call[1])).toEqual([ - "github", - "observability-otlp-local", - ]); - expect(updateSandboxMock).toHaveBeenLastCalledWith("alpha", { - policies: ["observability-otlp-local"], - }); - expect(registryEntry.policies).toEqual(["observability-otlp-local"]); - }); - - it.each([ - { - label: "records an exact live enabled policy", - observabilityEnabled: true, - liveState: "match" as const, - policies: ["npm"], - expectedPolicies: ["npm", "observability-otlp-local"], - }, - { - label: "prunes an exact absent disabled policy", - observabilityEnabled: false, - liveState: "absent" as const, - policies: ["npm", "observability-otlp-local"], - expectedPolicies: ["npm"], - }, - ])("repairs stale OTLP registry state: $label", async ({ - observabilityEnabled, - liveState, - policies: recordedPolicies, - expectedPolicies, - }) => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled, - policyTier: "balanced", - policies: recordedPolicies, - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: ["npm"], - }); - getAppliedPresetsMock.mockReturnValue(recordedPolicies); - getPresetContentGatewayStateMock.mockReturnValue(liveState); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(updateSandboxMock).toHaveBeenCalledWith("alpha", { policies: expectedPolicies }); - expect(applyPresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(removePresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - }); - - it("does not let a same-name, different-key custom replay suppress stale built-in OTLP cleanup", async () => { - const customPolicy = { - name: "observability-otlp-local", - content: "network_policies:\n operator-collector: {}\n", - sourcePath: "/policies/operator-collector.yaml", - }; - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: [customPolicy.name], - customPolicies: [customPolicy], - }); - getCustomPoliciesMock.mockReturnValueOnce([]).mockReturnValue([customPolicy]); - getAppliedPresetsMock.mockReturnValue(["observability-otlp-local"]); - getPresetContentGatewayStateMock.mockReturnValueOnce("match").mockReturnValueOnce("absent"); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(applyPresetContentMock).toHaveBeenCalledWith( - "alpha", - customPolicy.name, - customPolicy.content, - { custom: { sourcePath: customPolicy.sourcePath } }, - ); - expect(removePresetMock).toHaveBeenCalledTimes(1); - expect(removePresetMock).toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(applyPresetMock).not.toHaveBeenCalledWith("alpha", customPolicy.name); - expect(updateSandboxMock).not.toHaveBeenCalled(); - }); - - it("lets successfully replayed corp-otel content own its exact live OTLP key", async () => { - const customPolicy = { - name: "corp-otel", - content: - "network_policies:\n observability-otlp-local:\n endpoints:\n - host: collector.corp.example\n", - sourcePath: "/policies/corp-otel.yaml", - }; - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - policies: ["npm", "observability-otlp-local"], - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: ["npm", "observability-otlp-local"], - customPolicies: [customPolicy], - }); - getCustomPoliciesMock.mockReturnValueOnce([]).mockReturnValue([customPolicy]); - getAppliedPresetsMock.mockReturnValue(["npm", "corp-otel", "observability-otlp-local"]); - getPresetContentGatewayStateMock.mockImplementation((_sandbox, content) => - content === customPolicy.content ? "match" : "drift", - ); - const { runSandboxSnapshot } = await import("./snapshot"); - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(applyPresetContentMock).toHaveBeenCalledWith( - "alpha", - customPolicy.name, - customPolicy.content, - { custom: { sourcePath: customPolicy.sourcePath } }, - ); - expect(applyPresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(removePresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(removePresetMock).not.toHaveBeenCalledWith("alpha", customPolicy.name); - expect(updateSandboxMock).toHaveBeenCalledWith("alpha", { policies: ["npm"] }); - expect(getPresetContentGatewayStateMock).toHaveBeenCalledTimes(1); - expect(getPresetContentGatewayStateMock.mock.calls[0]?.[1]).toBe(customPolicy.content); - expect(getPresetContentGatewayStateMock.mock.calls[0]?.[2]).toBe("observability-otlp-local"); - }); - - it("does not let a failed corp-otel replay suppress stale built-in OTLP cleanup", async () => { - const customPolicy = { - name: "corp-otel", - content: - "network_policies:\n observability-otlp-local:\n endpoints:\n - host: collector.corp.example\n", - sourcePath: "/policies/corp-otel.yaml", - }; - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - policies: ["npm", "observability-otlp-local"], - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: ["npm", "observability-otlp-local"], - customPolicies: [customPolicy], - }); - getAppliedPresetsMock.mockReturnValue(["npm", "observability-otlp-local"]); - applyPresetContentMock.mockReturnValue(false); - getPresetContentGatewayStateMock.mockReturnValueOnce("match").mockReturnValueOnce("absent"); - const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(consoleWarn.mock.calls.flat().join("\n")).toContain("corp-otel (apply failed)"); - expect(removePresetMock).toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(getPresetContentGatewayStateMock).toHaveBeenCalledTimes(2); - expect(getPresetContentGatewayStateMock).toHaveBeenCalledWith( - "alpha", - builtinObservabilityPolicy, - ); - }); - - it("aborts preset reconciliation when custom OTLP ownership is unreadable", async () => { - const currentCustomPolicy = { - name: "corp-otel", - content: "network_policies:\n observability-otlp-local: {}\n", - sourcePath: "/policies/old-collector.yaml", - }; - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: true, - policyTier: "balanced", - } as never); - getLatestBackupMock.mockReturnValue({ - ...latestBackupFixture, - policyPresets: [], - customPolicies: [], - }); - getCustomPoliciesMock.mockReturnValue([currentCustomPolicy]); - removePresetMock.mockReturnValue(false); - getPresetContentGatewayStateMock.mockImplementation((_sandbox, content) => - content === currentCustomPolicy.content ? null : "absent", - ); - const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - await runSandboxSnapshot("alpha", { kind: "restore" }); - expect(removePresetMock).toHaveBeenCalledWith("alpha", currentCustomPolicy.name); - expect(applyPresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - expect(consoleWarn.mock.calls.flat().join("\n")).toContain( - "leaving live policy presets unchanged", - ); - }); - it.each([ - "drift", - null, - ] as const)("does not remove built-in OTLP when its exact live content state is %s", async (gatewayState) => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: false, - policyTier: "balanced", - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: ["observability-otlp-local"], - }); - getAppliedPresetsMock.mockReturnValue(["observability-otlp-local"]); - getPresetContentGatewayStateMock.mockReturnValue(gatewayState); - const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(removePresetMock).not.toHaveBeenCalled(); - expect(consoleWarn.mock.calls.flat().join("\n")).toContain( - "leaving its live policy content unchanged", - ); - }); - - it("normalizes a legacy restricted tier before deciding built-in OTLP egress", async () => { - getSandboxMock.mockReturnValue({ - name: "alpha", - agent: "langchain-deepagents-code", - observabilityEnabled: true, - policyTier: " Restricted ", - } as never); - getLatestBackupMock.mockReturnValue({ - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - policyPresets: [], - }); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "restore" }); - - expect(applyPresetMock).not.toHaveBeenCalledWith("alpha", "observability-otlp-local"); - }); - it("refuses snapshot creation before backup when the sandbox is not live", async () => { parseLiveSandboxNamesMock.mockReturnValue(new Set(["beta"])); const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 9240a5908e8..4a4379054dd 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -69,11 +69,12 @@ import { createSandboxExecMarker, extractSandboxExecCommandStdoutFromStreams, } from "./sandbox-exec-output"; +import { probeGatewayRunning, selectSandboxGatewayIfRegistered } from "./sandbox-gateway-routing"; import { - probeGatewayRunning, - selectSandboxGatewayIfRegistered, - usesGatewayMetadataProbe, -} from "./sandbox-gateway-routing"; + commitWithStableSnapshotRestoreSource, + type SnapshotRestoreSourceDescriptor, + SnapshotRestoreSourceError, +} from "./snapshot-restore-source"; const useColor = !process.env.NO_COLOR && !!process.stdout.isTTY; const trueColor = @@ -152,29 +153,18 @@ function renderSnapshotTable( } } -// Resolve the running source sandbox's image. Docker- and VM-driver sandboxes -// trust the registered imageTag. Kubernetes sandboxes use OpenShell's strict -// descriptor read instead of reaching through the gateway container to run -// kubectl on OpenShell's internal cluster. -async function resolveSrcPodImage( - srcName: string, - srcEntry?: SandboxEntry | { name: string }, -): Promise { - const registeredImage = (srcEntry as { imageTag?: string | null } | undefined)?.imageTag; - const registeredDriver = (srcEntry as { openshellDriver?: string | null } | undefined) - ?.openshellDriver; - if (usesGatewayMetadataProbe(registeredDriver)) { - return registeredImage ?? null; - } - - const srcGatewayName = resolveSandboxGatewayName( - srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, - ); - try { - return (await getOpenShellSandboxDescriptor(srcGatewayName, srcName)).image; - } catch { - return null; +async function readSnapshotRestoreSourceDescriptor( + sandboxName: string, +): Promise { + const sourceEntry = registry.getSandbox(sandboxName); + if (!sourceEntry) { + throw new Error(`Source sandbox '${sandboxName}' has no durable route metadata.`); } + const gatewayName = resolveSandboxGatewayName(sourceEntry); + return { + gatewayName, + ...(await getOpenShellSandboxDescriptor(gatewayName, sandboxName)), + }; } // Allocate the clone's own dashboard port. Dashboard ports are per-sandbox @@ -913,7 +903,7 @@ async function runSnapshotRestoreUnlocked( // used to overlay onto the live filesystem silently. Refuse by default // *before* doing any source-side preflight, so the user sees the // precise "destination exists" error instead of a misleading - // "source not found" or "cannot resolve image" message when both are + // "source not found" or "invalid source descriptor" message when both are // also broken. if (targetExists && !request.force) { console.error(` Destination sandbox '${targetSandbox}' already exists.`); @@ -926,9 +916,7 @@ async function runSnapshotRestoreUnlocked( snapshotExit(1); } // Cross-sandbox restore — whether dst exists (with --force) or not, - // we must be able to clone the source's running pod image. Resolve it - // upfront so a missing source / unresolvable image cannot delete the - // destination first (#3756 P1). + // the source must still be live before entering the guarded clone flow. if (!sourceLiveNames.has(sandboxName)) { if (targetExists) { console.error( @@ -942,12 +930,10 @@ async function runSnapshotRestoreUnlocked( } snapshotExit(1); } - const srcEntry = registry.getSandbox(sandboxName) || { name: sandboxName }; - const fromImage = await resolveSrcPodImage(sandboxName, srcEntry); - if (!fromImage) { + const srcEntry = registry.getSandbox(sandboxName); + if (!srcEntry) { console.error( - ` Cannot resolve image for source sandbox '${sandboxName}' — aborting before ` + - (targetExists ? `deleting '${targetSandbox}'.` : `creating '${targetSandbox}'.`), + ` Cannot auto-create '${targetSandbox}': source '${sandboxName}' has no durable route metadata.`, ); snapshotExit(1); } @@ -970,73 +956,78 @@ async function runSnapshotRestoreUnlocked( } const sourceGatewayName = resolveSandboxGatewayName(srcEntry); const createAndRegisterClone = async (): Promise => { - if (!targetExists && registry.getSandbox(targetSandbox)) { - console.error( - ` Destination sandbox '${targetSandbox}' was registered while this restore was waiting. Retry with --force only after reviewing that sandbox.`, - ); - snapshotExit(1); - } - const lockedSourceEntry = registry.getSandbox(sandboxName); - if (!lockedSourceEntry) { - console.error( - ` Cannot auto-create '${targetSandbox}': source '${sandboxName}' has no durable inference route metadata.`, - ); - snapshotExit(1); - } - if (getSandboxEntryInference(lockedSourceEntry).kind !== "configured") { - console.error( - ` Cannot auto-create '${targetSandbox}': source '${sandboxName}' has no complete durable inference route.`, - ); - snapshotExit(1); - } - const lockedFromImage = await resolveSrcPodImage(sandboxName, lockedSourceEntry); - if (!lockedFromImage) { - console.error( - ` Cannot resolve the current image for source sandbox '${sandboxName}' — aborting before changing '${targetSandbox}'.`, - ); - snapshotExit(1); - } - const lockedGatewayName = resolveSandboxGatewayName(lockedSourceEntry); - if (lockedGatewayName !== sourceGatewayName) { - console.error( - ` Source sandbox '${sandboxName}' changed OpenShell gateways while waiting to restore. Retry the command.`, - ); - snapshotExit(1); - } - const compatibility = checkGatewayRouteCompatibility({ - gatewayName: sourceGatewayName, - sandboxName: targetSandbox, - route: lockedSourceEntry, - sandboxes: registry.listSandboxes().sandboxes, - }); - if (!compatibility.ok) { - console.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); - snapshotExit(1); - } - // Allocate the clone's dashboard port before any destructive action, so - // dashboard-port-range exhaustion aborts before `deleteSandboxForRestore` - // removes the existing `--force` destination — matching the pre-delete - // validation the image and gateway-route checks above already do (#3756). - const dstDashboardPort = allocateCloneDashboardPort(targetSandbox, lockedSourceEntry); - const dashboardEnvArgs = resolveCloneDashboardEnvArgs(lockedSourceEntry, dstDashboardPort); - if (targetExists) { - if (targetEntry) { - verifyRestoreDestinationOnOwnGateway(targetSandbox); - } - deleteSandboxForRestore(targetSandbox); - requireLiveSandboxesOnSandboxGateway( + try { + await commitWithStableSnapshotRestoreSource({ + gatewayName: sourceGatewayName, sandboxName, - " Failed to re-select source sandbox gateway after deleting destination.", - ); + readDescriptor: readSnapshotRestoreSourceDescriptor, + preMutationCheck: () => { + if (!targetExists && registry.getSandbox(targetSandbox)) { + console.error( + ` Destination sandbox '${targetSandbox}' was registered while this restore was waiting. Retry with --force only after reviewing that sandbox.`, + ); + snapshotExit(1); + } + const sourceEntry = registry.getSandbox(sandboxName); + if (!sourceEntry) { + console.error( + ` Cannot auto-create '${targetSandbox}': source '${sandboxName}' has no durable inference route metadata.`, + ); + snapshotExit(1); + } + if (getSandboxEntryInference(sourceEntry).kind !== "configured") { + console.error( + ` Cannot auto-create '${targetSandbox}': source '${sandboxName}' has no complete durable inference route.`, + ); + snapshotExit(1); + } + if (resolveSandboxGatewayName(sourceEntry) !== sourceGatewayName) { + console.error( + ` Source sandbox '${sandboxName}' changed OpenShell gateways while waiting to restore. Retry the command.`, + ); + snapshotExit(1); + } + const compatibility = checkGatewayRouteCompatibility({ + gatewayName: sourceGatewayName, + sandboxName: targetSandbox, + route: sourceEntry, + sandboxes: registry.listSandboxes().sandboxes, + }); + if (!compatibility.ok) { + console.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); + snapshotExit(1); + } + const dashboardPort = allocateCloneDashboardPort(targetSandbox, sourceEntry); + const dashboardEnvArgs = resolveCloneDashboardEnvArgs(sourceEntry, dashboardPort); + if (targetExists && targetEntry) { + verifyRestoreDestinationOnOwnGateway(targetSandbox); + } + return { dashboardEnvArgs, dashboardPort, sourceEntry }; + }, + commit: async (descriptor, preflight) => { + if (targetExists) { + deleteSandboxForRestore(targetSandbox); + requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to re-select source sandbox gateway after deleting destination.", + ); + } + await autoCreateSandboxFromSource( + sandboxName, + targetSandbox, + preflight.sourceEntry, + descriptor.image, + preflight.dashboardPort, + preflight.dashboardEnvArgs, + ); + }, + }); + } catch (error) { + if (!(error instanceof SnapshotRestoreSourceError)) throw error; + const detail = error instanceof Error ? error.message : String(error); + console.error(` Cannot verify source sandbox '${sandboxName}': ${detail}`); + snapshotExit(1); } - await autoCreateSandboxFromSource( - sandboxName, - targetSandbox, - lockedSourceEntry, - lockedFromImage, - dstDashboardPort, - dashboardEnvArgs, - ); }; // Lock order matches onboard: sandbox (outer caller), host dashboard, // gateway route. The host-wide lease stays held from port selection until diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index e4192bb0bc7..a8fc1b9107a 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -10,7 +10,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; - +import { writeOpenShellSandboxDescriptorPreload } from "./helpers/openshell-sandbox-descriptor-preload"; import { execTimeout } from "./helpers/timeouts"; const CLI = path.join(import.meta.dirname, "..", "bin", "nemoclaw.js"); @@ -144,9 +144,7 @@ function makeHealthyVmGatewayEnv(prefix: string): Record { }; } -// VM-driver env with an `imageTag` set in the sandbox registry so the -// `resolveSrcPodImage()` fast path returns the image without falling back to -// the docker/kubectl probe. +// VM-driver env with the authoritative `imageTag` set in the sandbox registry. function makeVmRestoreToEnv( prefix: string, entry: Record = { imageTag: "openshell/sandbox-from:fast-path-test" }, @@ -158,6 +156,10 @@ function makeVmRestoreToEnv( openshellDriver: "vm", ...entry, }); + const descriptorNodeOptions = writeOpenShellSandboxDescriptorPreload( + home, + typeof entry.imageTag === "string" ? entry.imageTag : "", + ); const gatewayDir = path.join(home, ".config", "openshell", "gateways", "nemoclaw"); fs.mkdirSync(gatewayDir, { recursive: true }); fs.writeFileSync( @@ -185,9 +187,7 @@ function makeVmRestoreToEnv( "exit 0", ]); - // `docker exec` must never run: if the fast path regresses, - // resolveSrcPodImage falls into the kubectl-via-docker probe and this - // marker shows up in the captured output. + // Snapshot restore must never bypass OpenShell through Docker. writeExecutable(path.join(localBin, "docker"), [ 'if [ "$1" = "exec" ]; then', ' echo "kubectl-must-not-run"', @@ -198,6 +198,7 @@ function makeVmRestoreToEnv( return { HOME: home, + NODE_OPTIONS: descriptorNodeOptions, PATH: `${localBin}:${process.env.PATH ?? ""}`, XDG_CONFIG_HOME: path.join(home, ".config"), }; @@ -228,9 +229,7 @@ describe("snapshot VM-driver gateway guard", () => { expect(r.out).not.toContain("Failed to query live sandbox state"); }); - // `snapshot restore --to ` on VM driver must use the registered - // imageTag, not the legacy `docker exec ... kubectl` probe. - it("snapshot restore --to uses registered imageTag for VM-driver auto-create instead of kubectl probe", () => { + it("snapshot restore --to uses the live descriptor image for VM-driver auto-create", () => { const env = makeVmRestoreToEnv("nemoclaw-snap-vm-gw-restore-to-"); const seed = runCli("alpha snapshot create --name baseline", env); @@ -244,7 +243,7 @@ describe("snapshot VM-driver gateway guard", () => { expect(r.out).toContain("openshell/sandbox-from:fast-path-test"); }, 15000); - it("snapshot restore --to fails closed for VM-driver entries missing imageTag", () => { + it("snapshot restore --to fails closed when the live descriptor has no image", () => { const env = makeVmRestoreToEnv("nemoclaw-snap-vm-gw-restore-to-missing-image-", { imageTag: null, }); @@ -254,7 +253,7 @@ describe("snapshot VM-driver gateway guard", () => { const r = runCli("alpha snapshot restore baseline --to clone-1", env); expect(r.code).toBe(1); - expect(r.out).toContain("Cannot resolve image"); + expect(r.out).toContain("invalid image"); expect(r.out).not.toContain("kubectl-must-not-run"); }, 15000); }); diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index ed152c8b2e9..fe86b5268e4 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -7,8 +7,8 @@ // or --yes / NEMOCLAW_NON_INTERACTIVE=1) to delete-and-recreate the // destination from the snapshot. // -// The --force path preflights both the snapshot selector and the live source -// descriptor *before* deleting anything (#3756 P1 Codex). A bad selector, a +// The --force path preflights both the snapshot selector and the source pod +// image *before* deleting anything (#3756 P1 Codex). A bad selector, a // missing snapshot, or an unresolvable source image must not be allowed to // delete `dst` and only fail afterwards. @@ -18,7 +18,6 @@ import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; - import { writeOpenShellSandboxDescriptorPreload } from "./helpers/openshell-sandbox-descriptor-preload"; import { execTimeout } from "./helpers/timeouts"; @@ -100,6 +99,9 @@ function makeExistingDestEnv( sandboxes: { src: { name: "src", + ...(opts.withSourceImage === false + ? {} + : { imageTag: "ghcr.io/nvidia/nemoclaw/sandbox-src:test" }), model: "test-model", provider: "nvidia-prod", gpuEnabled: false, @@ -243,7 +245,7 @@ describe("snapshot restore --to existing destination (#3756)", () => { it("refuses by default before running source-descriptor preflight (#3796)", () => { // Existing destination + invalid source descriptor. The user must see the - // precise "destination exists" error, not the "cannot resolve image" + // precise "destination exists" error, not the descriptor validation // misdirection that would land if the refusal came after preflight. const { env } = makeExistingDestEnv("nemoclaw-snap-restore-refuse-before-preflight-", { withSourceImage: false, @@ -339,14 +341,13 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).not.toMatch(/sandbox delete dst/); }); - it("does NOT delete the destination when the source pod image cannot be resolved (--force --yes)", () => { + it("does NOT delete the destination when the live source image is invalid (--force --yes)", () => { const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-no-image-", { withSourceImage: false, }); const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); expect(r.code).toBe(1); - expect(r.out).toMatch(/Cannot resolve image for source sandbox 'src'/); - expect(r.out).toMatch(/aborting before deleting 'dst'/); + expect(r.out).toMatch(/invalid image/); expect(r.out).not.toMatch(/Deleting existing destination 'dst'/); const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; expect(log).not.toMatch(/sandbox delete dst/); From 7d78a80bac8ce390c3c4c97d1a62bb1b5a2aab92 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 23:05:04 -0700 Subject: [PATCH 08/10] test(snapshot): keep descriptor checks linear Signed-off-by: Aaron Erickson --- .../snapshot-restore-lifecycle.test.ts | 38 +++++++++---------- .../sandbox/snapshot-restore-source.test.ts | 16 ++++---- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index af707dfbe55..f1907895349 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -185,25 +185,10 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { }); it("hardens an active timer window before force-deleting a restore destination", async () => { - const mutationOrder: string[] = []; - f.getOpenShellSandboxDescriptorMock.mockImplementation(async (_gateway, sandboxName) => { - mutationOrder.push("read descriptor"); - return { - id: `${sandboxName}-id`, - name: sandboxName, - image: "nemoclaw-alpha:live-descriptor", - }; - }); - f.runOpenshellMock.mockImplementation((args) => { - if (args[0] === "sandbox" && args[1] === "delete") { - mutationOrder.push("delete"); - f.lifecycleMock.events.push("delete"); - } - return { status: 0, output: "" }; - }); - f.streamSandboxCreateMock.mockImplementation(async () => { - mutationOrder.push("create"); - return { status: 0, output: "", sawProgress: false, forcedReady: false }; + f.getOpenShellSandboxDescriptorMock.mockResolvedValue({ + id: "alpha-id", + name: "alpha", + image: "nemoclaw-alpha:live-descriptor", }); f.lifecycleMock.readTimerMarkerMock.mockReturnValue({ pid: 4242, @@ -268,10 +253,23 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { expect(f.streamSandboxCreateMock).toHaveBeenCalled(); expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith(1, "nemoclaw", "alpha"); expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith(2, "nemoclaw", "alpha"); + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenCalledTimes(2); expect(f.streamSandboxCreateMock.mock.calls[0]?.[1]).toContain( "nemoclaw-alpha:live-descriptor", ); - expect(mutationOrder).toEqual(["read descriptor", "read descriptor", "delete", "create"]); + expect(f.streamSandboxCreateMock).toHaveBeenCalledOnce(); + const destinationDeleteCalls = f.runOpenshellMock.mock.calls.filter( + ([args]) => args.join("\0") === "sandbox\0delete\0beta", + ); + expect(destinationDeleteCalls).toHaveLength(1); + const deleteCallIndex = f.runOpenshellMock.mock.calls.indexOf(destinationDeleteCalls[0]); + const [firstReadOrder, secondReadOrder] = + f.getOpenShellSandboxDescriptorMock.mock.invocationCallOrder; + const deleteOrder = f.runOpenshellMock.mock.invocationCallOrder[deleteCallIndex]; + const [createOrder] = f.streamSandboxCreateMock.mock.invocationCallOrder; + expect(firstReadOrder).toBeLessThan(secondReadOrder); + expect(secondReadOrder).toBeLessThan(deleteOrder); + expect(deleteOrder).toBeLessThan(createOrder); expect(f.restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); }); diff --git a/src/lib/actions/sandbox/snapshot-restore-source.test.ts b/src/lib/actions/sandbox/snapshot-restore-source.test.ts index a3195b3af4c..7c6d4e0547d 100644 --- a/src/lib/actions/sandbox/snapshot-restore-source.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-source.test.ts @@ -122,19 +122,21 @@ describe("commitWithStableSnapshotRestoreSource", () => { expect(commit).not.toHaveBeenCalled(); }); - it.each([1, 2])("fails closed when descriptor read %i fails", async (failedRead) => { + it.each([ + [1, [() => Promise.reject(new Error("unavailable")), async () => source]], + [2, [async () => source, () => Promise.reject(new Error("unavailable"))]], + ] as const)("fails closed when descriptor read %i fails", async (failedRead, reads) => { const commit = vi.fn(); const preMutationCheck = vi.fn(); - let calls = 0; + const readDescriptor = vi + .fn() + .mockImplementationOnce(reads[0]) + .mockImplementationOnce(reads[1]); await expect( commitWithStableSnapshotRestoreSource({ gatewayName: source.gatewayName, sandboxName: source.name, - readDescriptor: async () => { - calls += 1; - if (calls === failedRead) throw new Error("unavailable"); - return source; - }, + readDescriptor, preMutationCheck, commit, }), From 0b3695e6b3c7542049330971fe8c873037576336 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 23:24:00 -0700 Subject: [PATCH 09/10] fix(snapshot): describe source recheck boundary Signed-off-by: Aaron Erickson --- .../snapshot-restore-lifecycle.test.ts | 6 +- .../sandbox/snapshot-restore-source.test.ts | 72 +++++++++---------- .../sandbox/snapshot-restore-source.ts | 28 +++++--- src/lib/actions/sandbox/snapshot.ts | 6 +- 4 files changed, 61 insertions(+), 51 deletions(-) diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index f1907895349..855cf456b30 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -273,7 +273,7 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { expect(f.restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); }); - it("does not delete or create when the live source descriptor drifts", async () => { + it("does not delete or create when a descriptor difference is observed between samples", async () => { const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); f.getSandboxMock.mockImplementation((name) => ({ name: name ?? "alpha", @@ -297,7 +297,9 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { }), ).rejects.toMatchObject({ exitCode: 1 }); - expect(consoleError.mock.calls.flat().join("\n")).toContain("Source sandbox image changed"); + expect(consoleError.mock.calls.flat().join("\n")).toContain( + "Source sandbox image differed between pre-mutation descriptor samples", + ); expect(f.lifecycleMock.events).not.toContain("delete"); expect(f.streamSandboxCreateMock).not.toHaveBeenCalled(); expect(f.registerSandboxMock).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/snapshot-restore-source.test.ts b/src/lib/actions/sandbox/snapshot-restore-source.test.ts index 7c6d4e0547d..752a6a849d0 100644 --- a/src/lib/actions/sandbox/snapshot-restore-source.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-source.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { - commitWithStableSnapshotRestoreSource, + runSnapshotRestoreMutationAfterSourceRecheck, type SnapshotRestoreSourceDescriptor, } from "./snapshot-restore-source"; @@ -14,8 +14,8 @@ const source = { image: "registry/source@sha256:abc", } satisfies SnapshotRestoreSourceDescriptor; -describe("commitWithStableSnapshotRestoreSource", () => { - it("reads twice and commits only the second descriptor with preflight state", async () => { +describe("runSnapshotRestoreMutationAfterSourceRecheck", () => { + it("samples twice and mutates only with the second descriptor and preflight state", async () => { const events: string[] = []; const reads = [ { ...source, readNumber: 1 }, @@ -25,7 +25,7 @@ describe("commitWithStableSnapshotRestoreSource", () => { events.push("read"); return reads[readDescriptor.mock.calls.length - 1]; }); - const result = await commitWithStableSnapshotRestoreSource({ + const result = await runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor, @@ -33,8 +33,8 @@ describe("commitWithStableSnapshotRestoreSource", () => { events.push("preflight"); return "checked"; }, - commit: (descriptor, preflight) => { - events.push("commit"); + mutate: (descriptor, preflight) => { + events.push("mutate"); expect((descriptor as (typeof reads)[number]).readNumber).toBe(2); expect(preflight).toBe("checked"); return descriptor.image; @@ -42,60 +42,60 @@ describe("commitWithStableSnapshotRestoreSource", () => { }); expect(result).toBe(source.image); - expect(events).toEqual(["read", "preflight", "read", "commit"]); + expect(events).toEqual(["read", "preflight", "read", "mutate"]); expect(readDescriptor).toHaveBeenCalledTimes(2); }); - it("does not re-read or commit when read-only preflight fails", async () => { + it("does not re-read or mutate when read-only preflight fails", async () => { const readDescriptor = vi.fn(async () => source); - const commit = vi.fn(); + const mutate = vi.fn(); await expect( - commitWithStableSnapshotRestoreSource({ + runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor, preMutationCheck: () => { throw new Error("unsafe destination"); }, - commit, + mutate, }), ).rejects.toThrow("unsafe destination"); expect(readDescriptor).toHaveBeenCalledOnce(); - expect(commit).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); }); it.each([ ["empty id", { ...source, id: "" }], ["padded image", { ...source, image: ` ${source.image}` }], ])("fails closed for an invalid %s", async (_label, invalid) => { - const commit = vi.fn(); + const mutate = vi.fn(); await expect( - commitWithStableSnapshotRestoreSource({ + runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor: async () => invalid, preMutationCheck: vi.fn(), - commit, + mutate, }), ).rejects.toThrow(/Failed to read source sandbox before mutation/); - expect(commit).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); }); it.each([ ["name", { ...source, name: "other" }], ["gateway", { ...source, gatewayName: "gateway-b" }], ])("fails closed when the persisted %s does not match", async (_label, descriptor) => { - const commit = vi.fn(); + const mutate = vi.fn(); await expect( - commitWithStableSnapshotRestoreSource({ + runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor: async () => descriptor, preMutationCheck: vi.fn(), - commit, + mutate, }), ).rejects.toThrow(/does not match the persisted source route/); - expect(commit).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); }); it.each([ @@ -103,57 +103,57 @@ describe("commitWithStableSnapshotRestoreSource", () => { "id", "name", "image", - ] as const)("fails closed when source %s drifts", async (key) => { - const commit = vi.fn(); + ] as const)("rejects source %s drift observed between samples", async (key) => { + const mutate = vi.fn(); const values = [source[key], `${source[key]}-changed`]; const readDescriptor = vi.fn(async () => ({ ...source, [key]: values[readDescriptor.mock.calls.length - 1], })); await expect( - commitWithStableSnapshotRestoreSource({ + runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor, preMutationCheck: vi.fn(), - commit, + mutate, }), - ).rejects.toThrow(`Source sandbox ${key} changed`); - expect(commit).not.toHaveBeenCalled(); + ).rejects.toThrow(`Source sandbox ${key} differed between pre-mutation descriptor samples`); + expect(mutate).not.toHaveBeenCalled(); }); it.each([ - [1, [() => Promise.reject(new Error("unavailable")), async () => source]], - [2, [async () => source, () => Promise.reject(new Error("unavailable"))]], - ] as const)("fails closed when descriptor read %i fails", async (failedRead, reads) => { - const commit = vi.fn(); + [1, [() => Promise.reject(new Error("unavailable")), async () => source], "before mutation"], + [2, [async () => source, () => Promise.reject(new Error("unavailable"))], "after preflight"], + ] as const)("fails closed when descriptor read %i fails", async (failedRead, reads, phase) => { + const mutate = vi.fn(); const preMutationCheck = vi.fn(); const readDescriptor = vi .fn() .mockImplementationOnce(reads[0]) .mockImplementationOnce(reads[1]); await expect( - commitWithStableSnapshotRestoreSource({ + runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor, preMutationCheck, - commit, + mutate, }), - ).rejects.toThrow(/Failed to read source sandbox .*mutation: unavailable/); + ).rejects.toThrow(`Failed to read source sandbox ${phase}: unavailable`); expect(preMutationCheck).toHaveBeenCalledTimes(failedRead - 1); - expect(commit).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); }); it("preserves mutation failures without relabeling them as descriptor failures", async () => { const failure = new Error("create failed"); await expect( - commitWithStableSnapshotRestoreSource({ + runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: source.gatewayName, sandboxName: source.name, readDescriptor: async () => source, preMutationCheck: vi.fn(), - commit: () => { + mutate: () => { throw failure; }, }), diff --git a/src/lib/actions/sandbox/snapshot-restore-source.ts b/src/lib/actions/sandbox/snapshot-restore-source.ts index 9457c2f8a8a..54fe0b10c7d 100644 --- a/src/lib/actions/sandbox/snapshot-restore-source.ts +++ b/src/lib/actions/sandbox/snapshot-restore-source.ts @@ -19,12 +19,12 @@ export class SnapshotRestoreSourceError extends Error { } } -interface StableSourceOptions { +interface SourceRecheckOptions { gatewayName: string; sandboxName: string; readDescriptor: SnapshotRestoreSourceReader; preMutationCheck: () => Promise | TPreflight; - commit: ( + mutate: ( descriptor: SnapshotRestoreSourceDescriptor, preflight: TPreflight, ) => Promise | TResult; @@ -42,8 +42,16 @@ function checkedDescriptor( return { ...descriptor }; } -export async function commitWithStableSnapshotRestoreSource( - options: StableSourceOptions, +/** + * Rechecks the source descriptor before handing control to the mutation callback. + * + * This is a best-effort sampled drift check, not an atomic source lock. It rejects + * changes observed between the two reads, but an external OpenShell mutation can + * still occur after the second read. Callers must not infer source stability across + * the callback without a server-side revision or compare-and-create primitive. + */ +export async function runSnapshotRestoreMutationAfterSourceRecheck( + options: SourceRecheckOptions, ): Promise { const read = async (phase: string) => { try { @@ -55,20 +63,20 @@ export async function commitWithStableSnapshotRestoreSource }); } }; - const pinned = await read("before mutation"); - if (pinned.gatewayName !== options.gatewayName || pinned.name !== options.sandboxName) { + const firstSample = await read("before mutation"); + if (firstSample.gatewayName !== options.gatewayName || firstSample.name !== options.sandboxName) { throw new SnapshotRestoreSourceError( "OpenShell sandbox descriptor does not match the persisted source route.", ); } const preflight = await options.preMutationCheck(); - const current = await read("immediately before mutation"); + const secondSample = await read("after preflight"); for (const key of ["gatewayName", "id", "name", "image"] as const) { - if (current[key] !== pinned[key]) { + if (secondSample[key] !== firstSample[key]) { throw new SnapshotRestoreSourceError( - `Source sandbox ${key} changed before snapshot restore mutation.`, + `Source sandbox ${key} differed between pre-mutation descriptor samples.`, ); } } - return options.commit(current, preflight); + return options.mutate(secondSample, preflight); } diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 4a4379054dd..5d179fb4bfa 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -71,7 +71,7 @@ import { } from "./sandbox-exec-output"; import { probeGatewayRunning, selectSandboxGatewayIfRegistered } from "./sandbox-gateway-routing"; import { - commitWithStableSnapshotRestoreSource, + runSnapshotRestoreMutationAfterSourceRecheck, type SnapshotRestoreSourceDescriptor, SnapshotRestoreSourceError, } from "./snapshot-restore-source"; @@ -957,7 +957,7 @@ async function runSnapshotRestoreUnlocked( const sourceGatewayName = resolveSandboxGatewayName(srcEntry); const createAndRegisterClone = async (): Promise => { try { - await commitWithStableSnapshotRestoreSource({ + await runSnapshotRestoreMutationAfterSourceRecheck({ gatewayName: sourceGatewayName, sandboxName, readDescriptor: readSnapshotRestoreSourceDescriptor, @@ -1004,7 +1004,7 @@ async function runSnapshotRestoreUnlocked( } return { dashboardEnvArgs, dashboardPort, sourceEntry }; }, - commit: async (descriptor, preflight) => { + mutate: async (descriptor, preflight) => { if (targetExists) { deleteSandboxForRestore(targetSandbox); requireLiveSandboxesOnSandboxGateway( From c821e588d77b84d15e3230971d9df1cc5218219f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aaron=20Erickson=20=F0=9F=A6=9E?= Date: Mon, 20 Jul 2026 13:49:31 -0700 Subject: [PATCH 10/10] refactor(openshell): remove gateway-stop kubectl path (#6812) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Makes the supported OpenShell sandbox exec API the sole path for graceful in-sandbox gateway shutdown. This is PR 17 of 21 in the OpenShell gRPC migration stack. ## Changes - Delete Docker gateway-container discovery and kubectl pod selection. - Delete the privileged kubectl exec shutdown attempt. - Run the existing identity-guarded stop script through gateway-scoped `openshell sandbox exec` only. - Remove both shutdown sites from the reviewed legacy Docker-exec inventory. This slice removes 161 lines and adds 13. ## Stack - Stack index: https://github.com/NVIDIA/NemoClaw/pull/6790 - Depends on: https://github.com/NVIDIA/NemoClaw/pull/6811 - Review this PR against base branch `refactor/openshell-remove-snapshot-kubectl-probe/ae` to see only this slice. ## Type of Change - [x] Code change (feature, bug fix, or refactor) - [ ] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [ ] Doc only (includes code sample changes) ## Quality Gates - [x] Existing tests cover changed behavior — justification: gateway-stop, sandbox-stop, and service lifecycle tests cover success, already-stopped, missing CLI, gateway routing, and error reporting. - [ ] Existing tests cover changed behavior — justification: - [ ] Tests not applicable — justification: - [x] Docs not applicable — justification: this slice changes only internal shutdown transport behavior and tests. - [x] Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging) - [x] Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: transport-boundary self-review completed; the existing identity-guarded stop script is unchanged and now runs only through the supported OpenShell API. - [ ] Non-success, skipped, or missing CI check accepted by maintainer — check name, approval link, and follow-up issue: ## Verification - [x] PR description includes the DCO sign-off declaration and every commit appears as `Verified` in GitHub - [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or `npm run check:diff` passed when hooks were skipped or unavailable - [x] Targeted behavior tests pass for the current change set, or tests are marked not applicable above — build plus 67 gateway-stop, sandbox-stop, and service lifecycle tests passed - [x] Applicable broad gate passed — `npm run check:diff` passed at `f44c32ae` - [x] Quality Gates section completed with required justifications or waivers - [x] No secrets, API keys, or credentials committed - [ ] `npm run docs` builds without warnings (doc changes only) — not applicable - [ ] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) --- Signed-off-by: Aaron Erickson --------- Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 1 - src/commands/sandbox/stop.test.ts | 6 +- src/commands/sandbox/stop.ts | 2 +- src/commands/stop.ts | 2 +- src/commands/tunnel/stop.ts | 7 +- src/lib/actions/sandbox/destroy-flow.test.ts | 2 +- src/lib/actions/sandbox/destroy.ts | 18 +- src/lib/actions/sandbox/stop.test.ts | 88 ++--- src/lib/actions/sandbox/stop.ts | 6 +- src/lib/coverage-hotspots.test.ts | 7 +- src/lib/tunnel/gateway-stop-script.test.ts | 5 +- src/lib/tunnel/gateway-stop-script.ts | 2 +- src/lib/tunnel/sandbox-gateway-stop.test.ts | 306 ++++++++---------- src/lib/tunnel/sandbox-gateway-stop.ts | 162 ++++------ src/lib/tunnel/service-command.test.ts | 12 +- src/lib/tunnel/service-command.ts | 6 +- .../tunnel/services-gateway-ownership.test.ts | 12 +- src/lib/tunnel/services-sandbox.test.ts | 63 ++-- src/lib/tunnel/services.test.ts | 18 +- src/lib/tunnel/services.ts | 20 +- test/destroy-cleanup-sandbox-services.test.ts | 61 +++- test/helpers/destroy-flow-test-assertions.ts | 15 +- test/helpers/destroy-flow-test-harness.ts | 2 +- 23 files changed, 406 insertions(+), 417 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index eb33d6db101..a9b3160a2f2 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -53,7 +53,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/state/openclaw-plugin-restore.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/state/sandbox.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/state/user-managed-files-probe.ts", "grpc-cli-read-only-fallback", 1], - ["src/lib/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], ] as const satisfies readonly ReviewedSiteTuple[]; export const REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES: readonly LegacySandboxTransportSite[] = diff --git a/src/commands/sandbox/stop.test.ts b/src/commands/sandbox/stop.test.ts index b3243a113a9..f4502aff6dd 100644 --- a/src/commands/sandbox/stop.test.ts +++ b/src/commands/sandbox/stop.test.ts @@ -13,8 +13,8 @@ const rootDir = process.cwd(); describe("SandboxStopCommand", () => { beforeEach(() => { - stopSandbox.mockClear(); - stopSandbox.mockReturnValue({ exitCode: 0 }); + stopSandbox.mockReset(); + stopSandbox.mockResolvedValue({ exitCode: 0 }); }); afterEach(() => { @@ -30,7 +30,7 @@ describe("SandboxStopCommand", () => { it("propagates the action's failure exit code (#6026)", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); - stopSandbox.mockReturnValue({ exitCode: 1, message: " boom" }); + stopSandbox.mockResolvedValue({ exitCode: 1, message: " boom" }); await SandboxStopCommand.run(["alpha"], rootDir); diff --git a/src/commands/sandbox/stop.ts b/src/commands/sandbox/stop.ts index 46add54dc79..f33c1f5c2fd 100644 --- a/src/commands/sandbox/stop.ts +++ b/src/commands/sandbox/stop.ts @@ -21,6 +21,6 @@ export default class SandboxStopCommand extends NemoClawCommand { public async run(): Promise { const { args } = await this.parse(SandboxStopCommand); - this.applyExitResult(stopSandbox(args.sandboxName)); + this.applyExitResult(await stopSandbox(args.sandboxName)); } } diff --git a/src/commands/stop.ts b/src/commands/stop.ts index 29f4abff8df..4edff982e25 100644 --- a/src/commands/stop.ts +++ b/src/commands/stop.ts @@ -23,6 +23,6 @@ export default class DeprecatedStopCommand extends NemoClawCommand { public async run(): Promise { await this.parse(DeprecatedStopCommand); - runStopCommand({ ...serviceDeps(), stopAll, releaseGatewayPort: true }); + await runStopCommand({ ...serviceDeps(), stopAll, releaseGatewayPort: true }); } } diff --git a/src/commands/tunnel/stop.ts b/src/commands/tunnel/stop.ts index d1e5c700d8d..bb75cb21c77 100644 --- a/src/commands/tunnel/stop.ts +++ b/src/commands/tunnel/stop.ts @@ -2,10 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; - -import { stopAll } from "../../lib/tunnel/services"; -import { runStopCommand } from "../../lib/tunnel/service-command"; import { serviceDeps } from "../../lib/tunnel/command-support"; +import { runStopCommand } from "../../lib/tunnel/service-command"; +import { stopAll } from "../../lib/tunnel/services"; export default class TunnelStopCommand extends NemoClawCommand { static id = "tunnel:stop"; @@ -18,6 +17,6 @@ export default class TunnelStopCommand extends NemoClawCommand { public async run(): Promise { await this.parse(TunnelStopCommand); - runStopCommand({ ...serviceDeps(), stopAll }); + await runStopCommand({ ...serviceDeps(), stopAll }); } } diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index 7e3c1694d13..c2b857a3fd8 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -46,7 +46,7 @@ describe("destroySandbox flow", () => { }); it("selects the sandbox gateway, deletes live resources, cleans host state, and removes registry state", async () => { - const harness = createDestroyHarness(); + const harness = createDestroyHarness({ registeredSandboxCount: 1 }); await expect( harness.destroySandbox("alpha", { yes: true, cleanupGateway: true }), diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 071b8605e87..ea5187dcd46 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -29,8 +29,8 @@ import { resolveNemoclawStateDir } from "../../state/paths"; import * as registry from "../../state/registry"; import { confirmSandboxDestroy } from "./destroy-confirmation"; import { executeSandboxDestroy } from "./destroy-execution"; -import { shouldCleanupGatewayAfterConfirmedFinalDestroy } from "./destroy-gateway-cleanup"; import { cleanupGatewayAfterLastSandbox } from "./destroy-gateway"; +import { shouldCleanupGatewayAfterConfirmedFinalDestroy } from "./destroy-gateway-cleanup"; import { prepareSandboxDestroy } from "./destroy-preflight"; import { type WipeSandboxStateDeps, wipeSandboxState } from "./wipe-state"; @@ -57,7 +57,7 @@ type RunOpenshell = (args: string[], opts?: Record) => { status export type CleanupSandboxServicesDeps = { getSandbox?: typeof registry.getSandbox; - stopAll?: (opts: { sandboxName: string }) => void; + stopAll?: (opts: { sandboxName: string; skipSandboxStop: true }) => Promise; unloadOllamaModels?: () => void; runOpenshell?: RunOpenshell; rmSync?: typeof fs.rmSync; @@ -99,11 +99,11 @@ async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Pr return trimmed === "y" || trimmed === "yes"; } -export function cleanupSandboxServices( +export async function cleanupSandboxServices( sandboxName: string, { stopHostServices = false }: { stopHostServices?: boolean } = {}, deps: CleanupSandboxServicesDeps = {}, -): void { +): Promise { // Source boundary: this exported helper can be called independently of CLI // dispatch, including from forced local recovery. Validate once before every // host and provider cleanup side effect, then derive the PID path from that @@ -114,11 +114,11 @@ export function cleanupSandboxServices( const getSandbox = deps.getSandbox ?? registry.getSandbox; const stopAll = deps.stopAll ?? - ((opts: { sandboxName: string }) => { + ((opts: { sandboxName: string; skipSandboxStop: true }) => { const services = require("../../tunnel/services") as { - stopAll: (opts: { sandboxName: string }) => void; + stopAll: (opts: { sandboxName: string; skipSandboxStop: true }) => Promise; }; - services.stopAll(opts); + return services.stopAll(opts); }); const unloadOllamaModels = deps.unloadOllamaModels ?? @@ -141,7 +141,7 @@ export function cleanupSandboxServices( if (stopHostServices) { // `stopAll()` already runs `unloadOllamaModels()` unconditionally — // see src/lib/tunnel/services.ts. Don't double-call here. - stopAll({ sandboxName: validatedSandboxName }); + await stopAll({ sandboxName: validatedSandboxName, skipSandboxStop: true }); } else { // No global stop, so `stopAll()` did not run; explicitly free Ollama // models for this sandbox if its provider used Ollama. Without this @@ -380,7 +380,7 @@ async function destroySandboxUnlocked( sandboxStillRegistered: !!registry.getSandbox(sandboxName), }); - cleanupSandboxServices(sandboxName, { + await cleanupSandboxServices(sandboxName, { stopHostServices: shouldStopHostServices, }); // The sandbox's gateway was captured before the registry entry is removed — diff --git a/src/lib/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index d2ebcb2a209..6ca79a46a09 100644 --- a/src/lib/actions/sandbox/stop.test.ts +++ b/src/lib/actions/sandbox/stop.test.ts @@ -24,7 +24,9 @@ function harness(overrides: Partial = {}) { const findLabeledSandboxContainers = vi.fn< NonNullable >(() => [container("openshell-my-sandbox", true)]); - const stopSandboxChannels = vi.fn>(); + const stopSandboxChannels = vi.fn>( + async () => {}, + ); const dockerStop = vi.fn>(() => ({ status: 0 })); const log = vi.fn<(message: string) => void>(); const warn = vi.fn<(message: string) => void>(); @@ -53,16 +55,28 @@ function harness(overrides: Partial = {}) { } describe("stopSandbox", () => { - it("gracefully stops in-sandbox channels before stopping the container (#6026)", () => { + it("waits for in-sandbox channels before stopping the container (#6026)", async () => { const h = harness(); + let resolveChannelStop!: () => void; + h.stopSandboxChannels.mockImplementation( + () => + new Promise((resolve) => { + resolveChannelStop = resolve; + }), + ); - const result = stopSandbox("my-sandbox", h.deps); + const pending = stopSandbox("my-sandbox", h.deps); - expect(result.exitCode).toBe(0); expect(h.stopSandboxChannels).toHaveBeenCalledWith( "my-sandbox", expect.objectContaining({ info: expect.any(Function), warn: expect.any(Function) }), ); + expect(h.dockerStop).not.toHaveBeenCalled(); + + resolveChannelStop(); + const result = await pending; + + expect(result.exitCode).toBe(0); expect(h.dockerStop).toHaveBeenCalledWith("openshell-my-sandbox", { ignoreError: true, timeout: 30_000, @@ -72,23 +86,23 @@ describe("stopSandbox", () => { ); }); - it("routes channel-stop reporter lines through the action's log and warn (#6026)", () => { + it("routes channel-stop reporter lines through the action's log and warn (#6026)", async () => { const h = harness(); - h.stopSandboxChannels.mockImplementation((_name, channelDeps) => { + h.stopSandboxChannels.mockImplementation(async (_name, channelDeps) => { channelDeps?.info?.("gateway stopped inside sandbox."); channelDeps?.warn?.("could not reach gateway."); }); - stopSandbox("my-sandbox", h.deps); + await stopSandbox("my-sandbox", h.deps); expect(h.log).toHaveBeenCalledWith(" gateway stopped inside sandbox."); expect(h.warn).toHaveBeenCalledWith(" could not reach gateway."); }); - it("preserves the registry entry and tells the user how to start again (#6026)", () => { + it("preserves the registry entry and tells the user how to start again (#6026)", async () => { const h = harness(); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); const output = h.log.mock.calls.map(([line]) => line).join("\n"); @@ -96,11 +110,11 @@ describe("stopSandbox", () => { expect(output).toContain("nemoclaw my-sandbox start"); }); - it("succeeds idempotently when the container is already stopped (#6026)", () => { + it("succeeds idempotently when the container is already stopped (#6026)", async () => { const h = harness(); h.findLabeledSandboxContainers.mockReturnValue([container("openshell-my-sandbox", false)]); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); expect(h.dockerStop).not.toHaveBeenCalled(); @@ -108,13 +122,13 @@ describe("stopSandbox", () => { expect(output).toContain("already stopped"); }); - it("stops a crash-looping container instead of calling it stopped (#6026)", () => { + it("stops a crash-looping container instead of calling it stopped (#6026)", async () => { const h = harness(); h.findLabeledSandboxContainers.mockReturnValue([ { name: "openshell-my-sandbox", status: "Restarting (137) 2 seconds ago", running: false }, ]); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); expect(h.dockerStop).toHaveBeenCalledWith("openshell-my-sandbox", { @@ -123,38 +137,36 @@ describe("stopSandbox", () => { }); }); - it("stops a paused container (#6026)", () => { + it("stops a paused container (#6026)", async () => { const h = harness(); h.findLabeledSandboxContainers.mockReturnValue([ { name: "openshell-my-sandbox", status: "Up 5 minutes (Paused)", running: true }, ]); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); expect(h.dockerStop).toHaveBeenCalledTimes(1); }); - it("stops every running labeled container, including backup siblings (#6026)", () => { + it("stops every running labeled container, including backup siblings (#6026)", async () => { const h = harness(); h.findLabeledSandboxContainers.mockReturnValue([ container("openshell-my-sandbox", true), container("openshell-my-sandbox-nemoclaw-gpu-backup-1700000000000", true), ]); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); expect(h.dockerStop).toHaveBeenCalledTimes(2); }); - it("continues to docker stop when the graceful channel stop throws (#6026)", () => { + it("continues to docker stop when the graceful channel stop rejects (#6026)", async () => { const h = harness(); - h.stopSandboxChannels.mockImplementation(() => { - throw new Error("gateway unreachable"); - }); + h.stopSandboxChannels.mockRejectedValue(new Error("gateway unreachable")); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); expect(h.dockerStop).toHaveBeenCalledTimes(1); @@ -162,11 +174,11 @@ describe("stopSandbox", () => { expect(warned).toContain("gateway unreachable"); }); - it("names the Docker daemon outage instead of claiming the container was removed (#6026)", () => { + it("names the Docker daemon outage instead of claiming the container was removed (#6026)", async () => { const h = harness(); h.isDockerRuntimeDown.mockReturnValue(true); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(1); expect(result.message).toBeUndefined(); @@ -177,11 +189,11 @@ describe("stopSandbox", () => { expect(h.dockerStop).not.toHaveBeenCalled(); }); - it("fails with a rebuild hint when no labeled container exists (#6026)", () => { + it("fails with a rebuild hint when no labeled container exists (#6026)", async () => { const h = harness(); h.findLabeledSandboxContainers.mockReturnValue([]); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(1); expect(result.message).toContain("No Docker container"); @@ -189,22 +201,22 @@ describe("stopSandbox", () => { expect(h.dockerStop).not.toHaveBeenCalled(); }); - it("refuses an unregistered sandbox (#6026)", () => { + it("refuses an unregistered sandbox (#6026)", async () => { const h = harness(); h.getSandbox.mockReturnValue(null); - const result = stopSandbox("ghost", h.deps); + const result = await stopSandbox("ghost", h.deps); expect(result.exitCode).toBe(1); expect(result.message).toContain("not registered"); expect(h.findLabeledSandboxContainers).not.toHaveBeenCalled(); }); - it("refuses non-direct drivers instead of guessing at container control (#6026)", () => { + it("refuses non-direct drivers instead of guessing at container control (#6026)", async () => { const h = harness(); h.getSandbox.mockReturnValue(sandbox({ openshellDriver: "kubernetes" })); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(1); expect(result.message).toContain("kubernetes"); @@ -215,27 +227,27 @@ describe("stopSandbox", () => { ["null driver", sandbox({ openshellDriver: null })], ["docker driver", sandbox({ openshellDriver: "docker" })], ["vm driver", sandbox({ openshellDriver: "vm" })], - ])("allows the %s like privileged exec does (#6026)", (_label, entry) => { + ])("allows the %s like privileged exec does (#6026)", async (_label, entry) => { const h = harness(); h.getSandbox.mockReturnValue(entry); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(0); }); - it("surfaces a docker stop failure with the container name (#6026)", () => { + it("surfaces a docker stop failure with the container name (#6026)", async () => { const h = harness(); h.dockerStop.mockReturnValue({ status: 125 }); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(1); expect(result.message).toContain("openshell-my-sandbox"); expect(result.message).toContain("125"); }); - it("attempts every container and aggregates failures when one stop fails (#6026)", () => { + it("attempts every container and aggregates failures when one stop fails (#6026)", async () => { const h = harness(); h.findLabeledSandboxContainers.mockReturnValue([ container("openshell-my-sandbox", true), @@ -244,7 +256,7 @@ describe("stopSandbox", () => { // First container fails to stop; the sibling still must be attempted. h.dockerStop.mockReturnValueOnce({ status: 137 }).mockReturnValueOnce({ status: 0 }); - const result = stopSandbox("my-sandbox", h.deps); + const result = await stopSandbox("my-sandbox", h.deps); expect(result.exitCode).toBe(1); expect(h.dockerStop).toHaveBeenCalledTimes(2); @@ -261,10 +273,10 @@ describe("stopSandbox", () => { expect(result.message).not.toContain("gpu-backup"); }); - it("never removes containers or touches the registry entry (#6026)", () => { + it("never removes containers or touches the registry entry (#6026)", async () => { const h = harness(); - stopSandbox("my-sandbox", h.deps); + await stopSandbox("my-sandbox", h.deps); // The deps surface has no removal lever at all; assert the only docker // mutation issued is the stop of the labeled container. diff --git a/src/lib/actions/sandbox/stop.ts b/src/lib/actions/sandbox/stop.ts index 1fc5e20376d..2dd57d48504 100644 --- a/src/lib/actions/sandbox/stop.ts +++ b/src/lib/actions/sandbox/stop.ts @@ -106,10 +106,10 @@ export function gateDockerRuntimeUp( * The shared host gateway, tunnel, and any NIM inference container are * gateway-scoped and serve other sandboxes — deliberately untouched. */ -export function stopSandbox( +export async function stopSandbox( sandboxName: string, deps: SandboxStopDeps = {}, -): SandboxLifecycleResult { +): Promise { const log = deps.log ?? console.log; const warn = deps.warn ?? console.warn; @@ -148,7 +148,7 @@ export function stopSandbox( // Agent-managed gateways (e.g. Hermes) are supervised inside the sandbox // and shut down with the container's stop signal instead. try { - (deps.stopSandboxChannels ?? stopSandboxChannels)(sandboxName, { + await (deps.stopSandboxChannels ?? stopSandboxChannels)(sandboxName, { info: (message) => log(` ${message}`), warn: (message) => warn(` ${message}`), }); diff --git a/src/lib/coverage-hotspots.test.ts b/src/lib/coverage-hotspots.test.ts index 899ddf4a8a4..ba7956182db 100644 --- a/src/lib/coverage-hotspots.test.ts +++ b/src/lib/coverage-hotspots.test.ts @@ -5,7 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; - +import { getVersion } from "./core/version"; import { parseDuration } from "./domain/duration"; import { parseGatewayTokenArgs, runGatewayTokenCommand } from "./gateway-token-command"; import { @@ -13,7 +13,6 @@ import { runStartCommand, runStopCommand, } from "./tunnel/service-command"; -import { getVersion } from "./core/version"; // Narrow coverage guard for small helper modules that are otherwise only // exercised through subprocess CLI flows in this migration stack. @@ -70,9 +69,9 @@ describe("small CLI helper coverage", () => { expect(startCalls).toEqual([{ sandboxName: "alpha" }]); const stopCalls: Array<{ sandboxName?: string }> = []; - runStopCommand({ + await runStopCommand({ listSandboxes: () => ({ defaultSandbox: null }), - stopAll: (options) => { + stopAll: async (options) => { stopCalls.push(options); }, }); diff --git a/src/lib/tunnel/gateway-stop-script.test.ts b/src/lib/tunnel/gateway-stop-script.test.ts index c7b2a331138..33f231f5f1f 100644 --- a/src/lib/tunnel/gateway-stop-script.test.ts +++ b/src/lib/tunnel/gateway-stop-script.test.ts @@ -19,7 +19,7 @@ import { GATEWAY_STOP_SCRIPT } from "./gateway-stop-script"; // Linux-only: execute the production shell script against real processes while // scoping its ps snapshot to PIDs created by this test. This guards all gateway // argv forms without risking unrelated developer or CI processes. -describe("GATEWAY_STOP_SCRIPT (executed)", () => { +describe("GATEWAY_STOP_SCRIPT (executed via production sh -s stdin)", () => { // eslint-disable-next-line @typescript-eslint/no-require-imports const cp = require("node:child_process"); const children: Array<{ pid?: number }> = []; @@ -81,8 +81,9 @@ ps() { fi } ${script}`; - const result = cp.spawnSync("sh", ["-lc", scopedScript], { + const result = cp.spawnSync("sh", ["-s"], { encoding: "utf-8", + input: scopedScript, timeout: 20000, }); assert(result.status !== null, `stop script did not exit: ${result.signal} ${result.stderr}`); diff --git a/src/lib/tunnel/gateway-stop-script.ts b/src/lib/tunnel/gateway-stop-script.ts index 57cd5bf51da..bae5c6d4265 100644 --- a/src/lib/tunnel/gateway-stop-script.ts +++ b/src/lib/tunnel/gateway-stop-script.ts @@ -26,7 +26,7 @@ // IMPORTANT: keep example argv strings (e.g. "openclaw gateway") out of the awk // program text. awk's own argv is captured by the concurrent `ps` snapshot, so // any such literal inside the program makes awk match itself and the scan never -// drains. The shell `sh -lc` process is exempt (excluded as $self), comments in +// drains. The shell `sh -s` process is exempt (excluded as $self), comments in // the shell portion below are fine, but the awk body must stay token-clean. export const GATEWAY_STOP_SCRIPT = String.raw` set -eu diff --git a/src/lib/tunnel/sandbox-gateway-stop.test.ts b/src/lib/tunnel/sandbox-gateway-stop.test.ts index 8e1dda492d7..2eca9986055 100644 --- a/src/lib/tunnel/sandbox-gateway-stop.test.ts +++ b/src/lib/tunnel/sandbox-gateway-stop.test.ts @@ -1,22 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { SpawnSyncReturns } from "node:child_process"; import { describe, expect, it, vi } from "vitest"; +import type { SandboxExecResult } from "../adapters/openshell/sandbox-control"; import type { AgentDefinition } from "../agent/defs"; import type { SandboxEntry } from "../state/registry"; +import { GATEWAY_STOP_SCRIPT } from "./gateway-stop-script"; import { type SandboxGatewayStopDeps, stopSandboxChannels } from "./sandbox-gateway-stop"; -function spawnResult(status: number | null, stdout = "", stderr = ""): SpawnSyncReturns { - return { - pid: 1, - output: [null, stdout, stderr], - stdout, - stderr, - status, - signal: null, - }; +function execResult(status: number | null, stdout = "", stderr = ""): SandboxExecResult { + return { status, stdout, stderr }; } function registeredAgent( @@ -34,119 +28,152 @@ function harness() { const getRegisteredAgent = vi.fn>( () => null, ); - const resolveOpenshell = vi.fn>( - () => "/usr/local/bin/openshell", - ); - const runDocker = vi.fn>(() => spawnResult(1)); - const runProcess = vi.fn>(() => spawnResult(0)); + const exec = vi.fn(async () => execResult(0)); + const close = vi.fn(); + const assertNoGatewayEndpointOverride = vi.fn(); + const selectControl = vi.fn>(() => ({ + control: { exec }, + transport: "grpc", + close, + })); const info = vi.fn<(message: string) => void>(); const warn = vi.fn<(message: string) => void>(); const deps: SandboxGatewayStopDeps = { + assertNoGatewayEndpointOverride, getSandbox, getRegisteredAgent, - resolveOpenshell, - runDocker, - runProcess, + selectControl, info, warn, }; return { + assertNoGatewayEndpointOverride, + close, deps, + exec, getRegisteredAgent, getSandbox, info, - resolveOpenshell, - runDocker, - runProcess, + selectControl, warn, }; } describe("stopSandboxChannels", () => { - it("uses kubectl via the OpenShell gateway container for privileged shutdown", () => { + it("selects the persisted gateway and sends one bounded stdin request", async () => { const h = harness(); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/my-sandbox-0\n")) - .mockReturnValueOnce(spawnResult(0)); - - stopSandboxChannels("my-sandbox", h.deps); - - expect(h.runDocker).toHaveBeenNthCalledWith( - 1, - [ - "exec", - "openshell-cluster-nemoclaw", - "kubectl", - "get", - "pods", - "-n", - "openshell", - "-o", - "name", - ], - expect.objectContaining({ timeout: 10000 }), + h.getSandbox.mockReturnValue(sandbox({ gatewayName: "nemoclaw-18080", gatewayPort: 18080 })); + + await stopSandboxChannels("my-sandbox", h.deps); + + expect(h.assertNoGatewayEndpointOverride).toHaveBeenCalledTimes(1); + expect(h.selectControl).toHaveBeenCalledOnce(); + expect(h.selectControl).toHaveBeenCalledWith("nemoclaw-18080"); + expect(h.exec).toHaveBeenCalledOnce(); + expect(h.exec).toHaveBeenCalledWith({ + sandboxName: "my-sandbox", + command: ["sh", "-s"], + stdin: GATEWAY_STOP_SCRIPT, + timeoutMs: 20_000, + maxOutputBytes: 64 * 1024, + }); + expect(h.close).toHaveBeenCalledOnce(); + expect(h.assertNoGatewayEndpointOverride.mock.invocationCallOrder[0]).toBeLessThan( + h.selectControl.mock.invocationCallOrder[0], ); - const args = h.runDocker.mock.calls[1][0]; - expect(args).toEqual( - expect.arrayContaining(["kubectl", "exec", "-n", "openshell", "-c", "agent"]), + expect(h.selectControl.mock.invocationCallOrder[0]).toBeLessThan( + h.exec.mock.invocationCallOrder[0], ); - const script = String(args.at(-1)); - expect(script).toContain("ps -eo user=,pid=,args="); - expect(script).toContain("openclaw-gateway"); - expect(script).toContain("kill -TERM $pids"); - expect(script).toContain("kill -KILL $remaining"); - expect(h.info).toHaveBeenCalledWith("OpenClaw gateway stopped inside sandbox."); + expect(h.exec.mock.invocationCallOrder[0]).toBeLessThan(h.close.mock.invocationCallOrder[0]); }); - it("falls back to gateway-scoped openshell sandbox exec through stdin", () => { + it.each([ + [0, "OpenClaw gateway stopped inside sandbox."], + [1, "OpenClaw gateway was not running inside sandbox."], + ])("reports stop script exit %i as success", async (status, message) => { const h = harness(); + h.exec.mockResolvedValueOnce(execResult(status)); - stopSandboxChannels("my-sandbox", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - expect(h.runProcess).toHaveBeenCalledWith( - "/usr/local/bin/openshell", - ["sandbox", "exec", "--name", "my-sandbox", "--gateway", "nemoclaw", "--", "sh", "-s"], - expect.objectContaining({ - input: expect.stringContaining("find_gateway_pids"), - timeout: 20000, - }), - ); + expect(h.info).toHaveBeenCalledWith(message); + expect(h.warn).not.toHaveBeenCalled(); }); - it("selects the exact generated sandbox pod and excludes overlapping names", () => { + it("closes the selected control after an exec failure without replaying", async () => { const h = harness(); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/prod-app-abc\npod/app-abc\n")) - .mockReturnValueOnce(spawnResult(0)); + h.exec.mockRejectedValueOnce(new Error("connection closed")); - stopSandboxChannels("app", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - const args = h.runDocker.mock.calls[1][0]; - expect(args).toContain("pod/app-abc"); - expect(args).not.toContain("pod/prod-app-abc"); + expect(h.selectControl).toHaveBeenCalledOnce(); + expect(h.exec).toHaveBeenCalledOnce(); + expect(h.close).toHaveBeenCalledOnce(); + expect(h.warn).toHaveBeenCalledWith(expect.stringContaining("connection closed")); }); - it("falls back when no exact generated sandbox pod name is available", () => { + it("reports bounded exec failures and closes the selected control", async () => { const h = harness(); - h.runDocker.mockReturnValueOnce(spawnResult(0, "pod/prod-app-abc\npod/app-copy-abc\n")); + h.exec.mockResolvedValueOnce({ + ...execResult(null, "stdout detail", "stderr detail"), + error: new Error("deadline exceeded"), + }); - stopSandboxChannels("app", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - expect(h.runProcess).toHaveBeenCalledTimes(1); + expect(h.exec).toHaveBeenCalledOnce(); + expect(h.close).toHaveBeenCalledOnce(); + expect(h.warn).toHaveBeenCalledWith(expect.stringContaining("exit unknown")); + const output = h.warn.mock.calls.map((call) => call[0]).join("\n"); + expect(output).toContain("deadline exceeded"); + expect(output).toContain("stderr detail"); + expect(output).toContain("stdout detail"); + expect(output).toContain("gateway may still be running"); }); - it("treats stop script exit 1 as already stopped", () => { + it.each([ + [0, { error: new Error("stream reset") }, "stream reset"], + [1, { signal: "SIGTERM" as NodeJS.Signals }, "signal SIGTERM"], + ])("does not treat exit %i with transport failure state as success", async (status, failure, detail) => { const h = harness(); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/my-sandbox-0\n")) - .mockReturnValueOnce(spawnResult(1)); + h.exec.mockResolvedValueOnce({ ...execResult(status), ...failure }); - stopSandboxChannels("my-sandbox", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - expect(h.info).toHaveBeenCalledWith("OpenClaw gateway was not running inside sandbox."); + expect(h.info).not.toHaveBeenCalledWith(expect.stringMatching(/stopped|not running/u)); + expect(h.warn).toHaveBeenCalledWith(expect.stringContaining(detail)); }); - it("does not transiently kill a supervisor-managed Hermes gateway (#6392)", () => { + it("does not select a control when the endpoint guard rejects overrides", async () => { + const h = harness(); + h.assertNoGatewayEndpointOverride.mockImplementationOnce(() => { + throw new Error("endpoint override is forbidden"); + }); + + await stopSandboxChannels("my-sandbox", h.deps); + + expect(h.selectControl).not.toHaveBeenCalled(); + expect(h.exec).not.toHaveBeenCalled(); + expect(h.close).not.toHaveBeenCalled(); + expect(h.warn).toHaveBeenCalledWith(expect.stringContaining("endpoint override is forbidden")); + }); + + it("fails closed before dispatch when mutation control selection fails", async () => { + const h = harness(); + h.selectControl.mockImplementationOnce(() => { + throw new Error("direct gRPC configuration unavailable"); + }); + + await stopSandboxChannels("my-sandbox", h.deps); + + expect(h.exec).not.toHaveBeenCalled(); + expect(h.close).not.toHaveBeenCalled(); + expect(h.warn).toHaveBeenCalledWith( + expect.stringContaining("direct gRPC configuration unavailable"), + ); + }); + + it("does not transiently kill a supervisor-managed Hermes gateway (#6392)", async () => { const h = harness(); const hermes = registeredAgent({ name: "hermes", @@ -157,16 +184,15 @@ describe("stopSandboxChannels", () => { h.getSandbox.mockReturnValue(sandbox({ agent: "hermes" })); h.getRegisteredAgent.mockReturnValue(hermes); - stopSandboxChannels("my-sandbox", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - expect(h.runDocker).not.toHaveBeenCalled(); - expect(h.runProcess).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); expect(h.info.mock.calls.map((call) => call[0]).join("\n")).toContain( "Hermes Agent gateway is managed by the sandbox", ); }); - it("does not treat a terminal agent command as a gateway process", () => { + it("does not treat a terminal agent command as a gateway process", async () => { const h = harness(); const terminal = registeredAgent({ name: "langchain-deepagents-code", @@ -180,79 +206,71 @@ describe("stopSandboxChannels", () => { h.getSandbox.mockReturnValue(sandbox({ agent: "langchain-deepagents-code" })); h.getRegisteredAgent.mockReturnValue(terminal); - stopSandboxChannels("dcode-sandbox", h.deps); + await stopSandboxChannels("dcode-sandbox", h.deps); - expect(h.runDocker).not.toHaveBeenCalled(); - expect(h.runProcess).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); expect(h.info).toHaveBeenCalledWith( "LangChain Deep Agents Code has no gateway runtime; skipping in-sandbox gateway stop.", ); }); - it("ignores an unrelated global session when the target registry row is missing", () => { + it("requires an exact persisted sandbox record", async () => { const h = harness(); h.getSandbox.mockReturnValue(null); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/openclaw-target-abc\n")) - .mockReturnValueOnce(spawnResult(0)); - stopSandboxChannels("openclaw-target", h.deps); + await stopSandboxChannels("openclaw-target", h.deps); - expect(h.getRegisteredAgent).toHaveBeenCalledWith(null); - expect(h.runDocker).toHaveBeenCalledTimes(2); - expect(h.info.mock.calls.map((call) => call[0]).join("\n")).not.toContain("Hermes Agent"); + expect(h.getRegisteredAgent).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); + expect(h.warn).toHaveBeenCalledWith( + "Sandbox 'openclaw-target' is not registered; skipping in-sandbox gateway stop.", + ); }); - it("fails closed when the sandbox registry cannot be read", () => { + it("fails closed when the sandbox registry cannot be read", async () => { const h = harness(); h.getSandbox.mockImplementation(() => { throw new Error("invalid registry data"); }); - expect(() => stopSandboxChannels("my-sandbox", h.deps)).not.toThrow(); + await expect(stopSandboxChannels("my-sandbox", h.deps)).resolves.toBeUndefined(); expect(h.getRegisteredAgent).not.toHaveBeenCalled(); - expect(h.runDocker).not.toHaveBeenCalled(); - expect(h.runProcess).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); expect(h.warn).toHaveBeenCalledWith( expect.stringContaining("Could not read the sandbox registry for 'my-sandbox'"), ); }); - it("fails closed when the persisted gateway binding is invalid", () => { + it("fails closed when the persisted gateway binding is invalid", async () => { const h = harness(); h.getSandbox.mockReturnValue(sandbox({ agent: "openclaw", gatewayPort: 0 })); - stopSandboxChannels("my-sandbox", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - expect(h.runDocker).not.toHaveBeenCalled(); - expect(h.resolveOpenshell).not.toHaveBeenCalled(); - expect(h.runProcess).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); expect(h.warn.mock.calls.map((call) => call[0]).join("\n")).toContain( "Invalid persisted sandbox gateway binding", ); }); - it("fails closed when a registered non-OpenClaw agent cannot be loaded", () => { + it("fails closed when a registered non-OpenClaw agent cannot be loaded", async () => { const h = harness(); h.getSandbox.mockReturnValue(sandbox({ agent: "missing-agent" })); - stopSandboxChannels("my-sandbox", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); - expect(h.runDocker).not.toHaveBeenCalled(); - expect(h.runProcess).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); expect(h.warn).toHaveBeenCalledWith( expect.stringContaining("Could not resolve registered agent 'missing-agent'"), ); }); - it("warns when privileged shutdown reports the gateway may still be running", () => { + it("warns when sandbox exec reports the gateway may still be running", async () => { const h = harness(); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/my-sandbox-0\n")) - .mockReturnValueOnce(spawnResult(2, "", "205")); + h.exec.mockResolvedValueOnce(execResult(2, "", "205")); - stopSandboxChannels("my-sandbox", h.deps); + await stopSandboxChannels("my-sandbox", h.deps); const output = h.warn.mock.calls.map((call) => call[0]).join("\n"); expect(output).toContain("Could not stop OpenClaw gateway inside sandbox"); @@ -260,67 +278,11 @@ describe("stopSandboxChannels", () => { expect(output).toContain("205"); }); - it("warns when spawn returns null status", () => { - const h = harness(); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/my-sandbox-0\n")) - .mockReturnValueOnce(spawnResult(null)); - - stopSandboxChannels("my-sandbox", h.deps); - - expect(h.warn).toHaveBeenCalledWith(expect.stringContaining("exit unknown")); - }); - - it("warns when privileged shutdown is unavailable and openshell is not found", () => { - const h = harness(); - h.resolveOpenshell.mockReturnValue(null); - - stopSandboxChannels("my-sandbox", h.deps); - - expect(h.runProcess).not.toHaveBeenCalled(); - expect(h.warn).toHaveBeenCalledWith( - "openshell not found — cannot stop OpenClaw gateway inside sandbox.", - ); - }); - - it("routes shutdown through the sandbox's persisted non-default gateway", () => { - const h = harness(); - h.getSandbox.mockReturnValue(sandbox({ gatewayName: "nemoclaw-18080", gatewayPort: 18080 })); - - stopSandboxChannels("my-sandbox", h.deps); - - expect(h.runDocker).toHaveBeenCalledWith( - expect.arrayContaining(["exec", "openshell-cluster-nemoclaw-18080", "kubectl"]), - expect.any(Object), - ); - expect(h.runProcess).toHaveBeenCalledWith( - "/usr/local/bin/openshell", - expect.arrayContaining(["--gateway", "nemoclaw-18080"]), - expect.any(Object), - ); - }); - - it("targets launcher, re-exec, and identity-guarded bare gateway forms", () => { - const h = harness(); - h.runDocker - .mockReturnValueOnce(spawnResult(0, "pod/my-sandbox-0\n")) - .mockReturnValueOnce(spawnResult(0)); - - stopSandboxChannels("my-sandbox", h.deps); - - const script = String(h.runDocker.mock.calls[1][0].at(-1)); - expect(script).toContain("openclaw-gateway"); - expect(script).toContain("openclaw[[:space:]]+gateway"); - expect(script).toContain("openclaw[[:space:]]*$"); - expect(script).toContain("identity_files_trusted"); - }); - - it("rejects malformed sandbox names before any spawn", () => { + it("rejects malformed sandbox names before selecting a control", async () => { const h = harness(); - expect(() => stopSandboxChannels("../escape", h.deps)).toThrow("Invalid sandbox name"); + await expect(stopSandboxChannels("../escape", h.deps)).rejects.toThrow("Invalid sandbox name"); expect(h.getSandbox).not.toHaveBeenCalled(); - expect(h.runDocker).not.toHaveBeenCalled(); - expect(h.runProcess).not.toHaveBeenCalled(); + expect(h.selectControl).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/tunnel/sandbox-gateway-stop.ts b/src/lib/tunnel/sandbox-gateway-stop.ts index 7176783c7b1..37704088122 100644 --- a/src/lib/tunnel/sandbox-gateway-stop.ts +++ b/src/lib/tunnel/sandbox-gateway-stop.ts @@ -2,40 +2,33 @@ // SPDX-License-Identifier: Apache-2.0 import { - type SpawnSyncOptionsWithStringEncoding, - type SpawnSyncReturns, - spawnSync, -} from "node:child_process"; - -import { dockerSpawnSync } from "../adapters/docker"; -import { getGatewayClusterContainerName } from "../adapters/openshell/gateway-drift"; -import { resolveOpenshell } from "../adapters/openshell/resolve"; + type SandboxExecRequest, + type SandboxExecResult, + validateOpenShellExecRequest, +} from "../adapters/openshell/sandbox-control"; +import { selectOpenShellSandboxControlForMutation } from "../adapters/openshell/sandbox-control-routing"; import * as agentRuntime from "../agent/runtime"; import { resolveSandboxGatewayName } from "../onboard/gateway-binding"; +import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard"; import * as registry from "../state/registry"; import { GATEWAY_STOP_SCRIPT } from "./gateway-stop-script"; type Reporter = (message: string) => void; -type StopAttemptResult = ReturnType; -type ProcessRunner = ( - command: string, - args: readonly string[], - options: SpawnSyncOptionsWithStringEncoding, -) => SpawnSyncReturns; export type SandboxGatewayStopDeps = { getSandbox?: typeof registry.getSandbox; getRegisteredAgent?: typeof agentRuntime.getRegisteredAgent; getAgentDisplayName?: typeof agentRuntime.getAgentDisplayName; hasGatewayRuntime?: typeof agentRuntime.hasGatewayRuntime; - resolveOpenshell?: typeof resolveOpenshell; - runDocker?: typeof dockerSpawnSync; - runProcess?: ProcessRunner; + assertNoGatewayEndpointOverride?: typeof assertNoOpenShellGatewayEndpointOverride; + selectControl?: typeof selectOpenShellSandboxControlForMutation; info?: Reporter; warn?: Reporter; }; const SAFE_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/; +const GATEWAY_STOP_TIMEOUT_MS = 20_000; +const GATEWAY_STOP_MAX_OUTPUT_BYTES = 64 * 1024; function defaultInfo(message: string): void { console.log(`[services] ${message}`); @@ -53,7 +46,10 @@ function validateSandboxName(name: string): string { } /** Stop only a proven OpenClaw gateway; supervised agents remain owned by their sandbox. */ -export function stopSandboxChannels(sandboxName: string, deps: SandboxGatewayStopDeps = {}): void { +export async function stopSandboxChannels( + sandboxName: string, + deps: SandboxGatewayStopDeps = {}, +): Promise { const info = deps.info ?? defaultInfo; const warn = deps.warn ?? defaultWarn; const validatedSandboxName = validateSandboxName(sandboxName); @@ -67,6 +63,10 @@ export function stopSandboxChannels(sandboxName: string, deps: SandboxGatewaySto ); return; } + if (!sandbox) { + warn(`Sandbox '${validatedSandboxName}' is not registered; skipping in-sandbox gateway stop.`); + return; + } const agent = (deps.getRegisteredAgent ?? agentRuntime.getRegisteredAgent)(sandbox); if (sandbox?.agent && sandbox.agent !== "openclaw" && !agent) { @@ -103,106 +103,57 @@ export function stopSandboxChannels(sandboxName: string, deps: SandboxGatewaySto } const gatewayLabel = `${agentDisplayName} gateway`; + const request: SandboxExecRequest = { + sandboxName: validatedSandboxName, + command: ["sh", "-s"], + stdin: GATEWAY_STOP_SCRIPT, + timeoutMs: GATEWAY_STOP_TIMEOUT_MS, + maxOutputBytes: GATEWAY_STOP_MAX_OUTPUT_BYTES, + }; + const validationError = validateOpenShellExecRequest(request); info(`Stopping in-sandbox ${gatewayLabel} (sandbox: ${validatedSandboxName})...`); - - const privilegedResult = stopSandboxChannelsViaKubectl( - validatedSandboxName, - gatewayName, - GATEWAY_STOP_SCRIPT, - deps.runDocker ?? dockerSpawnSync, - ); - if (reportStopResult(privilegedResult, gatewayLabel, info, warn)) return; - - const openshell = (deps.resolveOpenshell ?? resolveOpenshell)(); - if (!openshell) { - warn(`openshell not found — cannot stop ${gatewayLabel} inside sandbox.`); - return; + try { + if (validationError) throw validationError; + (deps.assertNoGatewayEndpointOverride ?? assertNoOpenShellGatewayEndpointOverride)(); + // Select once and never replay: a shutdown may commit before a transport + // failure is observable, so retrying through another path is unsafe. + const selected = (deps.selectControl ?? selectOpenShellSandboxControlForMutation)(gatewayName); + try { + const result = await selected.control.exec(request); + reportStopResult(result, gatewayLabel, info, warn); + } finally { + selected.close(); + } + } catch (error) { + warn( + `Could not stop ${gatewayLabel} inside sandbox: ${error instanceof Error ? error.message : String(error)}. ` + + "The sandbox may be unreachable or the gateway may still be running.", + ); } - - const fallbackResult = (deps.runProcess ?? spawnSync)( - openshell, - ["sandbox", "exec", "--name", validatedSandboxName, "--gateway", gatewayName, "--", "sh", "-s"], - { - encoding: "utf-8", - input: GATEWAY_STOP_SCRIPT, - stdio: ["pipe", "pipe", "pipe"], - timeout: 20000, - }, - ); - reportStopResult(fallbackResult, gatewayLabel, info, warn); -} - -function isSandboxPodName(line: string, sandboxName: string): boolean { - if (!line.startsWith("pod/")) return false; - const podName = line.slice("pod/".length); - if (podName === sandboxName) return true; - const prefix = `${sandboxName}-`; - if (!podName.startsWith(prefix)) return false; - const generatedSuffix = podName.slice(prefix.length); - return /^[a-z0-9]+$/.test(generatedSuffix); -} - -function stopSandboxChannelsViaKubectl( - sandboxName: string, - gatewayName: string, - gatewayStopScript: string, - runDocker: typeof dockerSpawnSync, -): StopAttemptResult | null { - const gatewayContainer = getGatewayClusterContainerName(gatewayName); - const podsResult = runDocker( - ["exec", gatewayContainer, "kubectl", "get", "pods", "-n", "openshell", "-o", "name"], - { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], timeout: 10000 }, - ); - if (podsResult.status !== 0 || !podsResult.stdout) return null; - - const podOutput = - typeof podsResult.stdout === "string" ? podsResult.stdout : podsResult.stdout.toString(); - const pod = podOutput - .split(/\r?\n/) - .map((line: string) => line.trim()) - .find((line: string) => isSandboxPodName(line, sandboxName)); - if (!pod) return null; - - return runDocker( - [ - "exec", - gatewayContainer, - "kubectl", - "exec", - "-n", - "openshell", - "-c", - "agent", - pod, - "--", - "sh", - "-lc", - gatewayStopScript, - ], - { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], timeout: 20000 }, - ); } function reportStopResult( - result: StopAttemptResult | null, + result: SandboxExecResult, gatewayLabel: string, info: Reporter, warn: Reporter, -): boolean { - if (!result) return false; - - if (result.status === 0) { +): void { + if (!result.error && !result.signal && result.status === 0) { info(`${gatewayLabel} stopped inside sandbox.`); - return true; + return; } - if (result.status === 1) { + if (!result.error && !result.signal && result.status === 1) { info(`${gatewayLabel} was not running inside sandbox.`); - return true; + return; } - const details = [result.stderr, result.stdout] - .map((text) => (typeof text === "string" ? text : text?.toString())) - .filter((text): text is string => Boolean(text?.trim())) + const details = [ + result.error?.message, + result.signal ? `signal ${result.signal}` : undefined, + result.stderr, + result.stdout, + ] + .filter((text): text is string => typeof text === "string" && Boolean(text.trim())) .map((text) => text.trim()) .join(" "); warn( @@ -210,5 +161,4 @@ function reportStopResult( " The sandbox may be unreachable or the gateway may still be running." + (details ? ` Details: ${details}` : ""), ); - return true; } diff --git a/src/lib/tunnel/service-command.test.ts b/src/lib/tunnel/service-command.test.ts index 93eb8d12ef3..ba9d8121254 100644 --- a/src/lib/tunnel/service-command.test.ts +++ b/src/lib/tunnel/service-command.test.ts @@ -70,18 +70,18 @@ describe("services command", () => { expect(startAll).toHaveBeenCalledWith({ sandboxName: "alpha" }); }); - it("stops services without a sandbox override when the default sandbox is unsafe", () => { - const stopAll = vi.fn(); - runStopCommand({ + it("stops services without a sandbox override when the default sandbox is unsafe", async () => { + const stopAll = vi.fn(async () => {}); + await runStopCommand({ listSandboxes: () => ({ defaultSandbox: "bad name" }), stopAll, }); expect(stopAll).toHaveBeenCalledWith({ sandboxName: undefined }); }); - it("opts the legacy full-stop command into managed gateway release", () => { - const stopAll = vi.fn(); - runStopCommand({ + it("opts the legacy full-stop command into managed gateway release", async () => { + const stopAll = vi.fn(async () => {}); + await runStopCommand({ listSandboxes: () => ({ defaultSandbox: "alpha" }), stopAll, releaseGatewayPort: true, diff --git a/src/lib/tunnel/service-command.ts b/src/lib/tunnel/service-command.ts index 2053aec8c97..370b3d9e138 100644 --- a/src/lib/tunnel/service-command.ts +++ b/src/lib/tunnel/service-command.ts @@ -12,7 +12,7 @@ export interface StartCommandDeps { export interface StopCommandDeps { listSandboxes: () => SandboxSummary; - stopAll: (options: { sandboxName?: string; releaseGatewayPort?: boolean }) => void; + stopAll: (options: { sandboxName?: string; releaseGatewayPort?: boolean }) => Promise; /** Legacy `nemoclaw stop` tears down the managed host gateway too. */ releaseGatewayPort?: boolean; } @@ -34,10 +34,10 @@ export async function runStartCommand(deps: StartCommandDeps): Promise { await deps.startAll({ sandboxName: resolveDefaultSandboxName(deps.listSandboxes) }); } -export function runStopCommand(deps: StopCommandDeps): void { +export async function runStopCommand(deps: StopCommandDeps): Promise { const options: { sandboxName?: string; releaseGatewayPort?: boolean } = { sandboxName: resolveDefaultSandboxName(deps.listSandboxes), }; if (deps.releaseGatewayPort) options.releaseGatewayPort = true; - deps.stopAll(options); + await deps.stopAll(options); } diff --git a/src/lib/tunnel/services-gateway-ownership.test.ts b/src/lib/tunnel/services-gateway-ownership.test.ts index bfc348453ae..eb3befc50cf 100644 --- a/src/lib/tunnel/services-gateway-ownership.test.ts +++ b/src/lib/tunnel/services-gateway-ownership.test.ts @@ -185,13 +185,13 @@ describe("stopAll gateway-stop wiring", () => { vi.restoreAllMocks(); }); - it("orders supervised-agent full stop as sandbox guard, forwards, then gateway release", () => { + it("orders supervised-agent full stop as sandbox guard, forwards, then gateway release", async () => { const pidDir = mkdtempSync(join(tmpdir(), "nemoclaw-gateway-stop-wiring-")); vi.stubEnv("PATH", ""); const order: string[] = []; const stopSandboxGateway = vi .spyOn(sandboxGatewayStop, "stopSandboxChannels") - .mockImplementation((_sandboxName, deps) => { + .mockImplementation(async (_sandboxName, deps) => { order.push("sandbox-guard"); deps?.info?.( "Hermes Agent gateway is managed by the sandbox; leaving it running while host forwards stop.", @@ -210,7 +210,7 @@ describe("stopAll gateway-stop wiring", () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); try { - stopAll({ pidDir, sandboxName: "alpha", releaseGatewayPort: true }); + await stopAll({ pidDir, sandboxName: "alpha", releaseGatewayPort: true }); } finally { rmSync(pidDir, { recursive: true, force: true }); } @@ -233,7 +233,7 @@ describe("stopAll gateway-stop wiring", () => { expect(output).toContain("All services stopped"); }); - it("preserves the shared gateway for canonical tunnel-only stop", () => { + it("preserves the shared gateway for canonical tunnel-only stop", async () => { const pidDir = mkdtempSync(join(tmpdir(), "nemoclaw-tunnel-stop-wiring-")); vi.stubEnv("PATH", ""); const releaseForStop = vi @@ -242,10 +242,10 @@ describe("stopAll gateway-stop wiring", () => { const stopAgentForwards = vi .spyOn(agentForwardStop, "stopAgentForwardPortsForStop") .mockImplementation(() => {}); - vi.spyOn(sandboxGatewayStop, "stopSandboxChannels").mockImplementation(() => {}); + vi.spyOn(sandboxGatewayStop, "stopSandboxChannels").mockImplementation(async () => {}); try { - stopAll({ pidDir, sandboxName: "alpha" }); + await stopAll({ pidDir, sandboxName: "alpha" }); } finally { rmSync(pidDir, { recursive: true, force: true }); } diff --git a/src/lib/tunnel/services-sandbox.test.ts b/src/lib/tunnel/services-sandbox.test.ts index 3679125f0df..63d9b04ca9a 100644 --- a/src/lib/tunnel/services-sandbox.test.ts +++ b/src/lib/tunnel/services-sandbox.test.ts @@ -34,7 +34,7 @@ describe("stopAll with sandbox channels", () => { for (const name of SANDBOX_ENV_NAMES) delete process.env[name]; stopSandboxChannels = vi .spyOn(sandboxGatewayStop, "stopSandboxChannels") - .mockImplementation(() => {}); + .mockImplementation(async () => {}); }); afterEach(() => { @@ -43,10 +43,10 @@ describe("stopAll with sandbox channels", () => { vi.restoreAllMocks(); }); - it("stops in-sandbox channels when sandboxName is provided", () => { + it("stops in-sandbox channels when sandboxName is provided", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ pidDir, sandboxName: "test-sb" }); + await stopAll({ pidDir, sandboxName: "test-sb" }); expect(stopSandboxChannels).toHaveBeenCalledWith("test-sb", { info: expect.any(Function), @@ -55,10 +55,10 @@ describe("stopAll with sandbox channels", () => { expect(logSpy.mock.calls.map((call) => call[0]).join("\n")).toContain("All services stopped"); }); - it("warns when no sandbox name is available", () => { + it("warns when no sandbox name is available", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ pidDir }); + await stopAll({ pidDir }); expect(stopSandboxChannels).not.toHaveBeenCalled(); const output = logSpy.mock.calls.map((call) => call[0]).join("\n"); @@ -66,41 +66,60 @@ describe("stopAll with sandbox channels", () => { expect(output).toContain("All services stopped"); }); - it("still stops cloudflared when in-sandbox shutdown cannot stop a process", () => { + it("waits for in-sandbox shutdown before stopping cloudflared", async () => { writeFileSync(join(pidDir, "cloudflared.pid"), "999999999"); + let resolveSandboxStop: (() => void) | undefined; + stopSandboxChannels.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveSandboxStop = resolve; + }), + ); - stopAll({ pidDir, sandboxName: "test-sb" }); + const pending = stopAll({ pidDir, sandboxName: "test-sb" }); expect(stopSandboxChannels).toHaveBeenCalledTimes(1); + expect(existsSync(join(pidDir, "cloudflared.pid"))).toBe(true); + resolveSandboxStop?.(); + await pending; + expect(existsSync(join(pidDir, "cloudflared.pid"))).toBe(false); + }); + + it("skips the in-sandbox stop after sandbox deletion but still cleans host services", async () => { + writeFileSync(join(pidDir, "cloudflared.pid"), "999999999"); + + await stopAll({ pidDir, sandboxName: "test-sb", skipSandboxStop: true }); + + expect(stopSandboxChannels).not.toHaveBeenCalled(); expect(existsSync(join(pidDir, "cloudflared.pid"))).toBe(false); }); - it("reads sandbox name from NEMOCLAW_SANDBOX env when not in opts", () => { + it("reads sandbox name from NEMOCLAW_SANDBOX env when not in opts", async () => { process.env.NEMOCLAW_SANDBOX = "env-sandbox"; - stopAll({ pidDir }); + await stopAll({ pidDir }); expect(stopSandboxChannels).toHaveBeenCalledWith("env-sandbox", expect.any(Object)); }); - it("reads sandbox name from NEMOCLAW_SANDBOX_NAME when NEMOCLAW_SANDBOX is unset", () => { + it("reads sandbox name from NEMOCLAW_SANDBOX_NAME when NEMOCLAW_SANDBOX is unset", async () => { process.env.NEMOCLAW_SANDBOX_NAME = "named-sandbox"; - stopAll({ pidDir }); + await stopAll({ pidDir }); expect(stopSandboxChannels).toHaveBeenCalledWith("named-sandbox", expect.any(Object)); }); - it("prefers NEMOCLAW_SANDBOX_NAME over NEMOCLAW_SANDBOX", () => { + it("prefers NEMOCLAW_SANDBOX_NAME over NEMOCLAW_SANDBOX", async () => { process.env.NEMOCLAW_SANDBOX_NAME = "name-sandbox"; process.env.NEMOCLAW_SANDBOX = "other-sandbox"; - stopAll({ pidDir }); + await stopAll({ pidDir }); expect(stopSandboxChannels).toHaveBeenCalledWith("name-sandbox", expect.any(Object)); }); - it("uses the effective env-selected sandbox with an explicit host pidDir", () => { + it("uses the effective env-selected sandbox with an explicit host pidDir", async () => { const pidRoot = mkdtempSync(join(tmpdir(), "nemoclaw-services-pid-root-")); const effectivePidDir = join(pidRoot, "nemoclaw-services-name-sandbox"); const lowerPriorityPidDir = join(pidRoot, "nemoclaw-services-other-sandbox"); @@ -112,7 +131,7 @@ describe("stopAll with sandbox channels", () => { process.env.NEMOCLAW_SANDBOX = "other-sandbox"; try { - stopAll({ pidDir: effectivePidDir }); + await stopAll({ pidDir: effectivePidDir }); expect(stopSandboxChannels).toHaveBeenCalledWith("name-sandbox", expect.any(Object)); expect(existsSync(join(effectivePidDir, "cloudflared.pid"))).toBe(false); @@ -125,17 +144,17 @@ describe("stopAll with sandbox channels", () => { it.each([ "bad name", "../../etc/passwd", - ])("rejects malformed env sandbox name %j before in-sandbox shutdown", (invalidName) => { + ])("rejects malformed env sandbox name %j before in-sandbox shutdown", async (invalidName) => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); process.env.NEMOCLAW_SANDBOX_NAME = invalidName; - stopAll({ pidDir }); + await stopAll({ pidDir }); expect(stopSandboxChannels).not.toHaveBeenCalled(); expect(logSpy.mock.calls.map((call) => call[0]).join("\n")).toContain("Invalid sandbox name"); }); - it("keeps host cleanup running for a malformed explicit sandbox name", () => { + it("keeps host cleanup running for a malformed explicit sandbox name", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); const stopAgentForwards = vi .spyOn(agentForwardStop, "stopAgentForwardPortsForStop") @@ -145,9 +164,9 @@ describe("stopAll with sandbox channels", () => { .mockImplementation(() => {}); writeFileSync(join(pidDir, "cloudflared.pid"), "999999999"); - expect(() => + await expect( stopAll({ pidDir, sandboxName: "bad name", releaseGatewayPort: true }), - ).not.toThrow(); + ).resolves.toBeUndefined(); expect(stopSandboxChannels).not.toHaveBeenCalled(); expect(stopAgentForwards).not.toHaveBeenCalled(); @@ -158,10 +177,10 @@ describe("stopAll with sandbox channels", () => { expect(output).toContain("All services stopped"); }); - it("does not stop default cloudflared for a malformed sandbox name without an explicit pidDir", () => { + it("does not stop default cloudflared for a malformed sandbox name without an explicit pidDir", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - expect(() => stopAll({ sandboxName: "bad name" })).not.toThrow(); + await expect(stopAll({ sandboxName: "bad name" })).resolves.toBeUndefined(); expect(stopSandboxChannels).not.toHaveBeenCalled(); const output = logSpy.mock.calls.map((call) => call[0]).join("\n"); diff --git a/src/lib/tunnel/services.test.ts b/src/lib/tunnel/services.test.ts index d863f7ae070..95d9ea50238 100644 --- a/src/lib/tunnel/services.test.ts +++ b/src/lib/tunnel/services.test.ts @@ -479,34 +479,34 @@ describe("stopAll", () => { rmSync(pidDir, { recursive: true, force: true }); }); - it("removes stale PID files", () => { + it("removes stale PID files", async () => { writeFileSync(join(pidDir, "cloudflared.pid"), "999999999"); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ pidDir }); + await stopAll({ pidDir }); logSpy.mockRestore(); expect(existsSync(join(pidDir, "cloudflared.pid"))).toBe(false); }); - it("is idempotent — calling twice does not throw", () => { + it("is idempotent — calling twice does not throw", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ pidDir }); - stopAll({ pidDir }); + await stopAll({ pidDir }); + await stopAll({ pidDir }); logSpy.mockRestore(); }); - it("logs stop messages", () => { + it("logs stop messages", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ pidDir }); + await stopAll({ pidDir }); const output = logSpy.mock.calls.map((c) => c[0]).join("\n"); expect(output).toContain("All services stopped"); logSpy.mockRestore(); }); - it("unloads Ollama models before reporting services stopped", () => { + it("unloads Ollama models before reporting services stopped", async () => { const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ pidDir }); + await stopAll({ pidDir }); logSpy.mockRestore(); const psCall = spawnSyncCalls.find( diff --git a/src/lib/tunnel/services.ts b/src/lib/tunnel/services.ts index 8e80ae2ab97..9c589554aa5 100644 --- a/src/lib/tunnel/services.ts +++ b/src/lib/tunnel/services.ts @@ -45,6 +45,8 @@ export interface ServiceOptions { cloudflareTunnelToken?: string; /** Also release the managed host gateway port (legacy full-stop only). */ releaseGatewayPort?: boolean; + /** Skip the in-sandbox stop when the sandbox was already deleted. */ + skipSandboxStop?: boolean; } export interface ServiceStatus { @@ -445,7 +447,7 @@ export function showStatus(opts: ServiceOptions = {}): void { } } -export function stopAll(opts: ServiceOptions = {}): void { +export async function stopAll(opts: ServiceOptions = {}): Promise { // Resolve the target sandbox once and reuse it for in-sandbox and host-side cleanup. const rawSandboxName = opts.sandboxName ?? @@ -467,13 +469,15 @@ export function stopAll(opts: ServiceOptions = {}): void { : resolvePidDir({ ...opts, sandboxName: sandboxName ?? "default" })); if (pidDir) ensurePidDir(pidDir); - if (sandboxName) { - sandboxGatewayStop.stopSandboxChannels(sandboxName, { info, warn }); - } else if (rawSandboxName) { - warn(`Invalid sandbox name: ${JSON.stringify(rawSandboxName)} — skipping in-sandbox stop.`); - } else { - warn("No sandbox name available — cannot stop in-sandbox messaging channels."); - warn("Hint: run 'nemoclaw stop' with a registered sandbox or set NEMOCLAW_SANDBOX_NAME."); + if (!opts.skipSandboxStop) { + if (sandboxName) { + await sandboxGatewayStop.stopSandboxChannels(sandboxName, { info, warn }); + } else if (rawSandboxName) { + warn(`Invalid sandbox name: ${JSON.stringify(rawSandboxName)} — skipping in-sandbox stop.`); + } else { + warn("No sandbox name available — cannot stop in-sandbox messaging channels."); + warn("Hint: run 'nemoclaw stop' with a registered sandbox or set NEMOCLAW_SANDBOX_NAME."); + } } try { diff --git a/test/destroy-cleanup-sandbox-services.test.ts b/test/destroy-cleanup-sandbox-services.test.ts index 7e3df5163d2..2f42a500e42 100644 --- a/test/destroy-cleanup-sandbox-services.test.ts +++ b/test/destroy-cleanup-sandbox-services.test.ts @@ -23,10 +23,10 @@ function buildDeps(sandbox: SandboxLike): { "getSandbox" | "stopAll" | "unloadOllamaModels" | "runOpenshell" | "rmSync" > >; - stopAllCalls: Array<{ sandboxName: string }>; + stopAllCalls: Array<{ sandboxName: string; skipSandboxStop: true }>; unloadCalls: number; } { - const stopAllCalls: Array<{ sandboxName: string }> = []; + const stopAllCalls: Array<{ sandboxName: string; skipSandboxStop: true }> = []; let unloadCalls = 0; return { stopAllCalls, @@ -35,7 +35,7 @@ function buildDeps(sandbox: SandboxLike): { }, deps: { getSandbox: vi.fn(() => sandbox as never), - stopAll: vi.fn((opts: { sandboxName: string }) => { + stopAll: vi.fn(async (opts: { sandboxName: string; skipSandboxStop: true }) => { stopAllCalls.push(opts); }), unloadOllamaModels: vi.fn(() => { @@ -48,42 +48,73 @@ function buildDeps(sandbox: SandboxLike): { } describe("cleanupSandboxServices Ollama unload (#2717)", () => { - it("delegates GPU unload to stopAll() exactly once when stopHostServices=true", () => { + it("delegates GPU unload to stopAll() exactly once when stopHostServices=true", async () => { const harness = buildDeps({ provider: "ollama-local" }); - cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); expect(harness.deps.stopAll).toHaveBeenCalledTimes(1); - expect(harness.stopAllCalls[0]).toEqual({ sandboxName: "regression-2717" }); + expect(harness.stopAllCalls[0]).toEqual({ + sandboxName: "regression-2717", + skipSandboxStop: true, + }); // stopAll() invokes unloadOllamaModels() internally — see services.ts. // cleanupSandboxServices itself must not call it again. expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); expect(harness.unloadCalls).toBe(0); }); - it("calls unloadOllamaModels() exactly once for an Ollama sandbox when stopHostServices=false", () => { + it("waits for host stop before removing post-delete service state", async () => { + const harness = buildDeps({ provider: "ollama-local" }); + let resolveStopAll: (() => void) | undefined; + vi.mocked(harness.deps.stopAll).mockImplementationOnce( + () => + new Promise((resolve) => { + resolveStopAll = resolve; + }), + ); + + const pending = cleanupSandboxServices( + "regression-2717", + { stopHostServices: true }, + harness.deps, + ); + + expect(harness.deps.stopAll).toHaveBeenCalledWith({ + sandboxName: "regression-2717", + skipSandboxStop: true, + }); + expect(harness.deps.rmSync).not.toHaveBeenCalled(); + expect(harness.deps.runOpenshell).not.toHaveBeenCalled(); + resolveStopAll?.(); + await pending; + expect(harness.deps.rmSync).toHaveBeenCalledOnce(); + expect(harness.deps.runOpenshell).toHaveBeenCalled(); + }); + + it("calls unloadOllamaModels() exactly once for an Ollama sandbox when stopHostServices=false", async () => { const harness = buildDeps({ provider: "ollama-local" }); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.stopAll).not.toHaveBeenCalled(); expect(harness.deps.unloadOllamaModels).toHaveBeenCalledTimes(1); expect(harness.unloadCalls).toBe(1); }); - it("skips unloadOllamaModels() entirely for non-Ollama providers", () => { + it("skips unloadOllamaModels() entirely for non-Ollama providers", async () => { const harness = buildDeps({ provider: "nvidia-prod" }); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.stopAll).not.toHaveBeenCalled(); expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); }); - it("removes the sandbox PID dir and tears down all messaging providers", () => { + it("removes the sandbox PID dir and tears down all messaging providers", async () => { const harness = buildDeps({ provider: "ollama-local" }); - cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); + await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.deps.rmSync).toHaveBeenCalledWith( path.join("/tmp", "nemoclaw-services-regression-2717"), @@ -99,12 +130,12 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { ); }); - it("rejects traversal-shaped sandbox names before any cleanup side effect", () => { + it("rejects traversal-shaped sandbox names before any cleanup side effect", async () => { const harness = buildDeps({ provider: "ollama-local" }); - expect(() => + await expect( cleanupSandboxServices("x/../../victim", { stopHostServices: true }, harness.deps), - ).toThrow("Invalid sandbox name"); + ).rejects.toThrow("Invalid sandbox name"); expect(harness.deps.getSandbox).not.toHaveBeenCalled(); expect(harness.deps.stopAll).not.toHaveBeenCalled(); diff --git a/test/helpers/destroy-flow-test-assertions.ts b/test/helpers/destroy-flow-test-assertions.ts index ac9b1bb5508..d65fe1572e1 100644 --- a/test/helpers/destroy-flow-test-assertions.ts +++ b/test/helpers/destroy-flow-test-assertions.ts @@ -66,8 +66,21 @@ export function expectSuccessfulLiveDestroy(harness: DestroyHarness, exitSpy: Mo ["sandbox", "delete", "alpha"], expect.objectContaining({ ignoreError: true }), ); - expect(harness.unloadOllamaModelsSpy).toHaveBeenCalledTimes(1); + expect(harness.stopAllSpy).toHaveBeenCalledWith({ + sandboxName: "alpha", + skipSandboxStop: true, + }); + expect(harness.unloadOllamaModelsSpy).not.toHaveBeenCalled(); expect(harness.removeSandboxSpy).toHaveBeenCalledWith("alpha"); + const deleteCall = harness.runOpenshellSpy.mock.calls.findIndex( + (call) => Array.isArray(call[0]) && call[0].join(" ") === "sandbox delete alpha", + ); + expect(harness.runOpenshellSpy.mock.invocationCallOrder[deleteCall]).toBeLessThan( + harness.stopAllSpy.mock.invocationCallOrder[0], + ); + expect(harness.stopAllSpy.mock.invocationCallOrder[0]).toBeLessThan( + harness.removeSandboxSpy.mock.invocationCallOrder[0], + ); expect(harness.cleanupGatewaySpy).toHaveBeenCalledWith("nemoclaw-19080", harness.runOpenshellSpy); expect(harness.logSpy.mock.calls.map((call) => String(call[0])).join("\n")).toContain( "Sandbox 'alpha' destroyed", diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index d8a1c43c4ae..51f705eb556 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -235,7 +235,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr const unloadOllamaModelsSpy = vi .spyOn(ollamaProxy, "unloadOllamaModels") .mockImplementation(() => undefined); - const stopAllSpy = vi.spyOn(tunnelServices, "stopAll").mockImplementation(() => undefined); + const stopAllSpy = vi.spyOn(tunnelServices, "stopAll").mockImplementation(async () => undefined); vi.spyOn(timerControl, "readTimerMarker").mockReturnValue( options.activeTimer ? {