Skip to content
1 change: 1 addition & 0 deletions src/lib/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4394,6 +4394,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise<void> {
agentSupportsWebSearch,
agentSupportsWebSearchProvider,
note,
cliName,
updateSession: onboardSession.updateSession,
getStoredMessagingChannelConfig,
hydrateMessagingChannelConfig,
Expand Down
1 change: 1 addition & 0 deletions src/lib/onboard/machine/core-flow-phases.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ function createPhases(
resolvePath: (value) => value,
agentSupportsWebSearch: () => true,
note: vi.fn(),
cliName: () => "nemoclaw",
updateSession: vi.fn((mutator) => mutator(createSession()) ?? createSession()),
getStoredMessagingChannelConfig: () => null,
hydrateMessagingChannelConfig: (config) => config,
Expand Down
46 changes: 44 additions & 2 deletions src/lib/onboard/machine/handlers/sandbox-recreate-journal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ it("journals not-ready repair on the selected non-default gateway (#6492)", asyn
hermesAuthMethod: null,
gatewayName: "nemoclaw-31818",
gatewayPort: 31818,
imageTag: "openshell/sandbox-from:old",
workload: {
schemaVersion: 1 as const,
kind: "legacy-dockerfile" as const,
reference: "openshell/sandbox-from:old",
shared: false as const,
},
};
let replacementEntry = {
...sourceEntry,
imageTag: "openshell/sandbox-from:new",
workload: {
...sourceEntry.workload,
reference: "openshell/sandbox-from:new",
},
lifecycleGeneration: "replacement-generation",
lifecycleLiveIdentityFingerprint: "replacement-identity",
};
const phases: Array<string | null> = [];
const updateSession = vi.fn((mutator: (value: Session) => Session | void) => {
Expand All @@ -56,14 +73,29 @@ it("journals not-ready repair on the selected non-default gateway (#6492)", asyn
liveIdentityFingerprint: fingerprintSandboxRecreateValue("openshell-source-id"),
}) as const,
);
const createSandbox = vi.fn(async () => "saved");
let currentEntry = sourceEntry;
const createSandbox = vi.fn(async () => {
replacementEntry = {
...replacementEntry,
lifecycleGeneration: session.checkpoint?.sandboxRecreate?.targetGeneration ?? "missing",
};
currentEntry = replacementEntry;
return "saved";
});
const retireReplacedSandboxWorkload = vi.fn(() => ({
status: "failed" as const,
engineDisplayName: "Docker",
reference: sourceEntry.imageTag,
}));
const { deps, calls } = createDeps(
{
getSandboxReuseState: () => "not_ready",
getSandboxRecreateObservation,
getSandboxRegistryEntry: () => sourceEntry,
getSandboxRegistryEntry: () => currentEntry,
updateSession,
createSandbox,
retireReplacedSandboxWorkload,
cliName: () => "nemohermes",
},
session,
);
Expand All @@ -87,6 +119,16 @@ it("journals not-ready repair on the selected non-default gateway (#6492)", asyn
},
});
expect(getSandboxRecreateObservation).toHaveBeenCalledWith("saved");
expect(retireReplacedSandboxWorkload).toHaveBeenCalledExactlyOnceWith(
"saved",
replacementEntry.lifecycleGeneration,
sourceEntry,
replacementEntry,
);
expect(createSandbox.mock.invocationCallOrder[0]).toBeLessThan(
retireReplacedSandboxWorkload.mock.invocationCallOrder[0],
);
expect(calls.note).toHaveBeenCalledWith(expect.stringContaining("run 'nemohermes gc'"));
const orderedPhases = phases.filter((phase, index) => index === 0 || phase !== phases[index - 1]);
expect(orderedPhases).toEqual([null, "planned", "registry_committing", "completed", null]);
expect(session.checkpoint?.sandboxRecreate).toBeNull();
Expand Down
6 changes: 6 additions & 0 deletions src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ export function createDeps(
}),
),
createSandbox: vi.fn(async () => "my-assistant"),
retireReplacedSandboxWorkload: vi.fn(() => ({
status: "skipped" as const,
reason: "replacement-unproven" as const,
})),
updateSandbox: vi.fn(),
complete: vi.fn(async (_stepName: string, updates: SessionUpdates) => {
Object.assign(session, updates);
Expand Down Expand Up @@ -198,6 +202,7 @@ export function createDeps(
resolvePath: (value: string) => `/abs/${value}`,
agentSupportsWebSearch: () => true,
note: calls.note,
cliName: () => "nemoclaw",
updateSession: calls.updateSession,
getStoredMessagingChannelConfig: () => null,
hydrateMessagingChannelConfig: (config: MessagingChannelConfig | null) => config,
Expand Down Expand Up @@ -246,6 +251,7 @@ export function createDeps(
planRegisteredExtraProviders: calls.planRegisteredExtraProviders,
resolveSandboxCreateIntent: calls.resolveCreateIntent,
createSandbox: calls.createSandbox,
retireReplacedSandboxWorkload: calls.retireReplacedSandboxWorkload,
updateSandboxRegistry: calls.updateSandbox,
getSandboxAgentRegistryFields: () => ({ agent: null }),
recordStepComplete: calls.complete,
Expand Down
55 changes: 51 additions & 4 deletions src/lib/onboard/machine/handlers/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ import {
beginSandboxRecreateTransaction,
clearCompletedSandboxRecreateTransaction,
fingerprintSandboxRecreateValue,
type ReplacedSandboxWorkloadCleanupResult,
retireReplacedSandboxWorkload as retireReplacedSandboxWorkloadDefault,
type SandboxRecreateObservation,
selectedGatewayForSandboxRecreate,
} from "../../sandbox-recreate-transaction";
Expand Down Expand Up @@ -178,6 +180,7 @@ export interface SandboxStateOptions<
rootDir: string,
): boolean;
note(message: string): void;
cliName(): string;
updateSession(mutator: (session: Session) => Session | void): Session;
getStoredMessagingChannelConfig(
sandboxName: string | null,
Expand All @@ -195,6 +198,12 @@ export interface SandboxStateOptions<
hasSandboxGpuDrift(sandboxName: string, config: SandboxGpuConfig): boolean;
getSandboxHermesToolGateways(sandboxName: string): unknown;
getSandboxRegistryEntry(sandboxName: string): SandboxEntry | null;
retireReplacedSandboxWorkload?(
sandboxName: string,
targetGeneration: string,
source: SandboxEntry,
replacement: SandboxEntry | null,
): ReplacedSandboxWorkloadCleanupResult;
normalizeHermesToolGatewaySelections(value: unknown): string[];
stringSetsEqual(left: string[], right: string[]): boolean;
removeSandboxFromRegistry(sandboxName: string): SandboxRemovalReceipt | null;
Expand Down Expand Up @@ -389,6 +398,7 @@ type SandboxRecreateRepairMetadata = {
};
type SandboxRecreatePreparation = {
readonly transaction: CheckpointSandboxRecreateTransaction | null;
readonly sourceEntry: SandboxEntry | null;
readonly effectiveCreateIntent: CompleteSandboxCreateIntent;
readonly repairMetadata: SandboxRecreateRepairMetadata | null;
readonly removalReceipt: SandboxRemovalReceipt | null;
Expand Down Expand Up @@ -1204,6 +1214,7 @@ class SandboxStateFlow<
state: SandboxStepState<WebSearchConfig>,
sandboxName: string,
createIntent: CompleteSandboxCreateIntent,
sourceEntry: SandboxEntry | null,
): CheckpointSandboxRecreateTransaction | null {
const existing = state.session?.checkpoint?.sandboxRecreate ?? null;
if (!this.options.resume && !existing) return null;
Expand All @@ -1222,7 +1233,6 @@ class SandboxStateFlow<
);
}
if (!gateway) return null;
const sourceEntry = this.deps.getSandboxRegistryEntry(sandboxName);
if (!existing && !sourceEntry) return null;
const observation = this.deps.getSandboxRecreateObservation(sandboxName);
const updated = this.deps.updateSession((current) => {
Expand Down Expand Up @@ -1276,14 +1286,21 @@ class SandboxStateFlow<
createIntent: CompleteSandboxCreateIntent,
decision: SandboxCreationDecision,
): Promise<SandboxRecreatePreparation> {
const transaction = this.beginSandboxRecreateJournal(state, requestedSandboxName, createIntent);
const sourceEntry = this.deps.getSandboxRegistryEntry(requestedSandboxName);
const transaction = this.beginSandboxRecreateJournal(
state,
requestedSandboxName,
createIntent,
sourceEntry,
);
const repairMetadata: SandboxRecreateRepairMetadata | null =
decision.kind === "repair-and-recreate"
? { repair: "recorded-sandbox-cleanup", sandboxName: state.sandboxName }
: null;
if (!transaction) {
return {
transaction,
sourceEntry: null,
effectiveCreateIntent: createIntent,
repairMetadata,
removalReceipt: await applySandboxResumeDecision(decision, state.sandboxName, this.deps),
Expand All @@ -1309,7 +1326,13 @@ class SandboxStateFlow<
} else if (decision.kind === "recreate") {
this.deps.note(decision.note);
}
return { transaction, effectiveCreateIntent, repairMetadata, removalReceipt: null };
return {
transaction,
sourceEntry,
effectiveCreateIntent,
repairMetadata,
removalReceipt: null,
};
}

private async recordSandboxRecreateRepairFailure(
Expand Down Expand Up @@ -1343,6 +1366,29 @@ class SandboxStateFlow<
this.recordSandboxRecreatePhase(transaction, "registry_committing");
}

private retireSandboxRecreateSourceWorkload(
transaction: CheckpointSandboxRecreateTransaction | null,
sourceEntry: SandboxEntry | null,
sandboxName: string,
): void {
if (!transaction || !sourceEntry) return;
const retired = (
this.deps.retireReplacedSandboxWorkload ?? retireReplacedSandboxWorkloadDefault
)(
sandboxName,
transaction.targetGeneration,
sourceEntry,
this.deps.getSandboxRegistryEntry(sandboxName),
);
if (retired.status === "removed") {
this.deps.note(` Removed obsolete ${retired.engineDisplayName} image ${retired.reference}`);
} else if (retired.status === "failed") {
this.deps.note(
` Warning: failed to remove obsolete ${retired.engineDisplayName} image ${retired.reference}; run '${this.deps.cliName()} gc' to clean up.`,
);
}
}

private recordSandboxCreateEffects(
transaction: CheckpointSandboxRecreateTransaction | null,
sandboxName: string,
Expand Down Expand Up @@ -1414,7 +1460,7 @@ class SandboxStateFlow<
requestedSandboxName,
createIntent.resolved.policy.options.baselineExclusions,
);
const { transaction, effectiveCreateIntent, repairMetadata, removalReceipt } =
const { transaction, sourceEntry, effectiveCreateIntent, repairMetadata, removalReceipt } =
await this.prepareSandboxRecreate(state, requestedSandboxName, createIntent, decision);
let rollbackArmed = removalReceipt !== null;
const restoreRemovedRegistryEntry = () => {
Expand Down Expand Up @@ -1466,6 +1512,7 @@ class SandboxStateFlow<
await this.recordSandboxRecreateRepairFailure(transaction, repairMetadata, error);
throw error;
}
this.retireSandboxRecreateSourceWorkload(transaction, sourceEntry, sandboxName);
await this.recordSandboxRecreateRepairSuccess(transaction, repairMetadata);
this.recordSandboxRecreateRegistryCommit(transaction);
// createSandbox() owns the build fingerprint. In particular, reusing an
Expand Down
124 changes: 124 additions & 0 deletions src/lib/onboard/runtime-provider/replaced-workload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// 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 type { SandboxEntry } from "../../state/registry";
import { retireReplacedSandboxWorkload } from "../sandbox-recreate-transaction";
import { createDockerRuntimeProviderBundle } from "./docker";
import { createRuntimeProviderBundleRegistry } from "./registry";

const SOURCE_IMAGE = "openshell/sandbox-from:old";
const REPLACEMENT_IMAGE = "openshell/sandbox-from:new";

function entry(imageTag: string, generation: string): SandboxEntry {
return {
name: "alpha",
imageTag,
workload: {
schemaVersion: 1,
kind: "legacy-dockerfile",
reference: imageTag,
shared: false,
},
lifecycleGeneration: generation,
lifecycleLiveIdentityFingerprint: `${generation}-identity`,
} as SandboxEntry;
}

type DockerRuntimeProviderOverrides = NonNullable<
Parameters<typeof createDockerRuntimeProviderBundle>[0]
>;
type DockerRemoveImage = NonNullable<DockerRuntimeProviderOverrides["removeImage"]>;

function providers(removeImage: DockerRemoveImage) {
return createRuntimeProviderBundleRegistry([
["docker", createDockerRuntimeProviderBundle({ removeImage })],
]);
}

describe("same-name replacement workload cleanup", () => {
it("removes the obsolete owned image after the replacement identity is registered", () => {
const removeImage = vi.fn(() => ({ status: 0 }));

expect(
retireReplacedSandboxWorkload(
"alpha",
"target",
entry(SOURCE_IMAGE, "source"),
entry(REPLACEMENT_IMAGE, "target"),
{
runtimeProviders: providers(removeImage),
},
),
).toEqual({
status: "removed",
engineDisplayName: "Docker",
reference: SOURCE_IMAGE,
});
expect(removeImage).toHaveBeenCalledExactlyOnceWith(SOURCE_IMAGE, expect.any(Object));
});

it("does not remove an image reused by the registered replacement", () => {
const removeImage = vi.fn(() => ({ status: 0 }));

expect(
retireReplacedSandboxWorkload(
"alpha",
"target",
entry(SOURCE_IMAGE, "source"),
entry(SOURCE_IMAGE, "target"),
{
runtimeProviders: providers(removeImage),
},
),
).toEqual({ status: "skipped", reason: "image-reused" });
expect(removeImage).not.toHaveBeenCalled();
});

it("retains a source workload recorded as shared", () => {
const removeImage = vi.fn(() => ({ status: 0 }));
const recordedSource = entry(SOURCE_IMAGE, "source");
const source = {
...recordedSource,
workload: { ...recordedSource.workload, shared: true },
} as unknown as SandboxEntry;

expect(
retireReplacedSandboxWorkload("alpha", "target", source, entry(REPLACEMENT_IMAGE, "target"), {
runtimeProviders: providers(removeImage),
}),
).toEqual({ status: "skipped", reason: "shared-image" });
expect(removeImage).not.toHaveBeenCalled();
});

it("does not remove the source image before replacement registration is proven", () => {
const removeImage = vi.fn(() => ({ status: 0 }));
const { lifecycleLiveIdentityFingerprint: _identity, ...replacement } = entry(
REPLACEMENT_IMAGE,
"target",
);

expect(
retireReplacedSandboxWorkload("alpha", "target", entry(SOURCE_IMAGE, "source"), replacement, {
runtimeProviders: providers(removeImage),
}),
).toEqual({ status: "skipped", reason: "replacement-unproven" });
expect(removeImage).not.toHaveBeenCalled();
});

it("does not trust a same-name registry row from another replacement generation", () => {
const removeImage = vi.fn(() => ({ status: 0 }));

expect(
retireReplacedSandboxWorkload(
"alpha",
"expected-target",
entry(SOURCE_IMAGE, "source"),
entry(REPLACEMENT_IMAGE, "foreign-target"),
{ runtimeProviders: providers(removeImage) },
),
).toEqual({ status: "skipped", reason: "replacement-unproven" });
expect(removeImage).not.toHaveBeenCalled();
});
});
Loading
Loading