Skip to content
Merged
1 change: 0 additions & 1 deletion scripts/checks/legacy-sandbox-transports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
3 changes: 3 additions & 0 deletions src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })),
Expand Down
43 changes: 43 additions & 0 deletions src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof f.getSandboxMock> = 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) => ({
Expand Down
16 changes: 16 additions & 0 deletions src/lib/actions/sandbox/snapshot-restore-test-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | 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,
Expand Down Expand Up @@ -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(),
}));
Expand Down Expand Up @@ -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);
Expand Down
5 changes: 4 additions & 1 deletion src/lib/actions/sandbox/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ const latestBackupFixture = {
};

vi.mock("../../adapters/docker", () => ({
dockerCapture: vi.fn(() => ""),
dockerInspect: dockerInspectMock,
}));

Expand All @@ -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(),
}));
Expand Down
36 changes: 10 additions & 26 deletions src/lib/actions/sandbox/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string | null> {
const registeredImage = (srcEntry as { imageTag?: string | null } | undefined)?.imageTag;
const registeredDriver = (srcEntry as { openshellDriver?: string | null } | undefined)
?.openshellDriver;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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 ` +
Expand Down Expand Up @@ -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}'.`,
Expand Down
61 changes: 54 additions & 7 deletions src/lib/adapters/openshell/grpc-sandbox-control.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
type OpenShellGrpcApi,
OpenShellGrpcOutputLimitError,
OpenShellGrpcPreDispatchError,
type OpenShellSandboxDescriptor,
} from "./grpc-sandbox-control";
import {
OPENSHELL_EXEC_MAX_OUTPUT_BYTES,
Expand All @@ -38,12 +39,24 @@ class FakeStream extends EventEmitter {
}
}

type GetSandboxCallback = Parameters<OpenShellGrpcApi["getSandbox"]>[3];
type FakeGetSandboxResponse = NonNullable<Parameters<GetSandboxCallback>[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<OpenShellSandboxDescriptor> = {}): FakeGetSandboxResponse {
return { sandbox: { metadata: { id, name }, spec: { template: { image } } } };
}

function fakeApi(fixture: FakeApiOptions = {}): {
api: OpenShellGrpcApi;
stream: FakeStream;
Expand All @@ -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;
},
Expand Down Expand Up @@ -299,13 +315,18 @@ describe("gRPC OpenShell sandbox control", () => {
};
const server = new Server();
const requests: unknown[] = [];
const deadlines: Array<Date | number> = [];
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<FakeGetSandboxResponse>,
) {
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<
Expand All @@ -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",
Expand All @@ -343,6 +373,7 @@ describe("gRPC OpenShell sandbox control", () => {
stderr: "wire stderr",
});
expect(requests).toEqual([
{ name: "alpha" },
{ name: "alpha" },
{
sandboxId: "wire-id",
Expand Down Expand Up @@ -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"],
Expand Down
Loading