From aa8034e7051d61c03ba2a52d1c71a2a7d8bd1f00 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 9 Oct 2026 08:48:44 +0000 Subject: [PATCH 01/44] fix(inference): release superseded Ollama model on provider switch Signed-off-by: Yimo Jiang --- src/lib/actions/sandbox/gateway-state.ts | 4 +- src/lib/actions/sandbox/stop.test.ts | 1 + src/lib/actions/sandbox/stop.ts | 81 +--- .../inference/ollama/model-ownership.test.ts | 109 ++++++ src/lib/inference/ollama/model-ownership.ts | 194 +++++++++- src/lib/onboard.ts | 2 +- src/lib/onboard/setup-inference.test.ts | 346 ++++++++++++++++++ src/lib/onboard/setup-inference.ts | 136 ++++++- .../onboard-inference-reconciliation.test.ts | 13 +- test/support/setup-inference-test-harness.ts | 7 +- 10 files changed, 778 insertions(+), 115 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 91edad026a4..8227e3996fc 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -215,7 +215,9 @@ function gatewayScopedArgs(args: string[], gatewayName?: string): string[] { } /** Resolve the authoritative gateway for a persisted sibling ownership row. */ -export function resolvePersistedSandboxOwnershipGateway(sandbox: SandboxEntry): string { +export function resolvePersistedSandboxOwnershipGateway( + sandbox: Pick, +): string { return getPersistedSandboxTargetGatewayName(sandbox); } diff --git a/src/lib/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index ee9b381287b..561d86a6847 100644 --- a/src/lib/actions/sandbox/stop.test.ts +++ b/src/lib/actions/sandbox/stop.test.ts @@ -260,6 +260,7 @@ describe("discoverActiveOllamaSandboxNames", () => { ).toEqual({ ok: true, activeSandboxNames: new Set(["active-peer", "transient-peer"]), + activePeers: new Set([activePeer, transientPeer]), gatewayChecks: [ { activeSandboxes: ["active-peer", "transient-peer"], diff --git a/src/lib/actions/sandbox/stop.ts b/src/lib/actions/sandbox/stop.ts index eae1b4a318f..03e191dcffe 100644 --- a/src/lib/actions/sandbox/stop.ts +++ b/src/lib/actions/sandbox/stop.ts @@ -4,10 +4,13 @@ import { CLI_NAME } from "../../cli/branding"; import { decideOllamaModelOwnership, + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, matchingOllamaModelPeers, + type OllamaActiveOwnershipDiscovery, type OllamaHostRoute, } from "../../inference/ollama/model-ownership"; +export type { OllamaActiveOwnershipDiscovery } from "../../inference/ollama/model-ownership"; import type { OllamaUnloadResult } from "../../inference/ollama/proxy"; import { CURRENT_RUNTIME_PROVIDER_BUNDLES, @@ -70,17 +73,6 @@ function defaultUnloadOllamaModels(onlyModels: readonly string[]): OllamaUnloadR return unloadOllamaModels(onlyModels); } -export type OllamaActiveOwnershipDiscovery = - | { - readonly ok: true; - readonly activeSandboxNames: ReadonlySet; - readonly gatewayChecks: readonly { - readonly activeSandboxes: readonly string[]; - readonly gateway: string; - }[]; - } - | { readonly ok: false; readonly message: string }; - type OllamaStopReleaseResult = | { readonly ok: true } | { readonly ok: false; readonly message: string }; @@ -104,70 +96,12 @@ export function discoverActiveOllamaSandboxNames( deps: OllamaOwnershipDiscoveryDeps = {}, ): OllamaActiveOwnershipDiscovery { const capturePhases = deps.captureSandboxOwnershipPhases ?? captureSandboxOwnershipPhases; - const parseEntries = deps.parseLiveSandboxEntries ?? parseLiveSandboxEntries; const resolveGateway = deps.resolvePersistedSandboxOwnershipGateway ?? resolvePersistedSandboxOwnershipGateway; - if (peers.length === 0) { - return { ok: true, activeSandboxNames: new Set(), gatewayChecks: [] }; - } - - const peersByGateway = new Map>(); - try { - for (const peer of peers) { - const gateway = resolveGateway(peer); - const names = peersByGateway.get(gateway) ?? new Set(); - names.add(peer.name); - peersByGateway.set(gateway, names); - } - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - return { ok: false, message: `could not resolve a sibling gateway: ${detail}` }; - } - - const activeSandboxNames = new Set(); - const gatewayChecks: Array<{ activeSandboxes: string[]; gateway: string }> = []; - for (const [gateway, peerNames] of peersByGateway) { - let result; - try { - result = capturePhases(gateway, environment); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - return { ok: false, message: `OpenShell could not list gateway '${gateway}': ${detail}` }; - } - if (result.status !== 0) { - const detail = result.output.trim().replace(/\s+/g, " ").slice(0, 300); - return { - ok: false, - message: `OpenShell could not list sandbox phases on gateway '${gateway}'${ - detail ? `: ${detail}` : "" - }`, - }; - } - const phases = new Map(parseEntries(result.output).map((entry) => [entry.name, entry.phase])); - const activeSandboxes: string[] = []; - for (const peerName of peerNames) { - const phase = phases.get(peerName); - if ( - phase === undefined || - phase === "Stopped" || - phase === "Error" || - phase === "Failed" || - phase === "Evicted" - ) { - continue; - } - if (phase === null || phase === "Unknown") { - return { - ok: false, - message: `OpenShell returned no usable phase for sibling '${peerName}' on gateway '${gateway}'`, - }; - } - activeSandboxNames.add(peerName); - activeSandboxes.push(peerName); - } - gatewayChecks.push({ activeSandboxes, gateway }); - } - return { ok: true, activeSandboxNames, gatewayChecks }; + return discoverOllamaModelOwnership(peers, environment, capturePhases, { + parseLiveSandboxEntries: deps.parseLiveSandboxEntries, + resolvePersistedSandboxOwnershipGateway: resolveGateway, + }); } function releaseStoppedSandboxOllamaModel( @@ -207,6 +141,7 @@ function releaseStoppedSandboxOllamaModel( sandboxes, discovery.activeSandboxNames, selectedHost, + discovery.activePeers, ); if (ownership.kind === "missing-model") { log(" Ollama model release skipped: the sandbox registry has no model."); diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 557df044639..1a65ce67c80 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -9,12 +9,14 @@ import { describe, expect, it } from "vitest"; import { clearPendingOllamaModelCleanup, decideOllamaModelOwnership, + discoverOllamaModelOwnership, exclusivelyHeldOllamaModel, loadPendingOllamaModelCleanup, type OllamaModelHolder, type OllamaModelRoute, persistPendingOllamaModelCleanup, supersededOllamaModel, + supersededOllamaModelWithActivePeers, } from "./model-ownership"; import { isLocalOllamaRouteOwner } from "./model-ownership"; @@ -134,6 +136,113 @@ describe("supersededOllamaModel", () => { }); }); +describe("supersededOllamaModelWithActivePeers", () => { + it("releases a superseded model despite stale or incomplete matching registry rows", () => { + const inactivePeer = holder({ name: "incomplete-reservation" }); + expect( + supersededOllamaModelWithActivePeers( + holder(), + route("qwen2.5:1.5b"), + [inactivePeer], + new Set(), + ), + ).toBe("llama3"); + }); + + it("protects the model while a matching sibling is active", () => { + const activePeer = holder({ name: "active-peer", model: "llama3:latest" }); + expect( + supersededOllamaModelWithActivePeers( + holder(), + route("qwen2.5:1.5b"), + [holder(), activePeer], + new Set(["active-peer"]), + ), + ).toBeNull(); + }); + + it("protects a same-named active peer registered under another gateway", () => { + const previous = holder({ gatewayName: "current-gateway" }); + const peer = holder({ gatewayName: "other-gateway" }); + + expect( + supersededOllamaModelWithActivePeers( + previous, + route("qwen2.5:1.5b"), + [peer], + new Set([peer.name]), + ), + ).toBeNull(); + }); + + it("does not treat a same-named row with incomplete gateway identity as the subject", () => { + const previous = holder(); + const peer = holder({ gatewayName: "other-gateway" }); + + expect( + supersededOllamaModelWithActivePeers( + previous, + route("qwen2.5:1.5b"), + [peer], + new Set([peer.name]), + ), + ).toBeNull(); + }); + + it("preserves an active model selected through the same local daemon", () => { + expect( + supersededOllamaModelWithActivePeers(holder(), route("llama3:latest"), [holder()], new Set()), + ).toBeNull(); + }); +}); + +describe("discoverOllamaModelOwnership", () => { + it("does not leak a live same-name peer across gateway roots", () => { + const stoppedMatchingPeer = holder({ + name: "duplicate-peer", + model: "llama3", + gatewayName: "gateway-stopped", + }); + const activeDifferentModelPeer = holder({ + name: "duplicate-peer", + model: "llama3:8b", + gatewayName: "gateway-live", + }); + const discovery = discoverOllamaModelOwnership( + [stoppedMatchingPeer, activeDifferentModelPeer], + {}, + (gateway) => ({ + status: 0, + output: gateway === "gateway-live" ? "live" : "stopped", + }), + { + parseLiveSandboxEntries: (output) => [ + { + name: "duplicate-peer", + phase: output === "live" ? "Ready" : "Stopped", + }, + ], + resolvePersistedSandboxOwnershipGateway: (peer) => peer.gatewayName ?? "default", + }, + ); + + expect(discovery.ok).toBe(true); + const successfulDiscovery = discovery as Extract; + const activePeers = successfulDiscovery.activePeers as ReadonlySet; + expect(successfulDiscovery.activeSandboxNames).toEqual(new Set(["duplicate-peer"])); + expect(activePeers).toEqual(new Set([activeDifferentModelPeer])); + expect( + decideOllamaModelOwnership( + holder({ name: "alpha", model: "llama3" }), + [stoppedMatchingPeer, activeDifferentModelPeer], + successfulDiscovery.activeSandboxNames, + null, + activePeers, + ), + ).toEqual({ kind: "exclusive", model: "llama3", stalePeers: ["duplicate-peer"] }); + }); +}); + describe("decideOllamaModelOwnership", () => { it("returns the exclusive model and names stopped matching registry rows (#10074)", () => { const stoppedPeer = holder({ name: "stopped-peer" }); diff --git a/src/lib/inference/ollama/model-ownership.ts b/src/lib/inference/ollama/model-ownership.ts index 84a3d69e5f6..a71c04440f9 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -3,7 +3,9 @@ import path from "node:path"; +import { listInferenceRouteOwnersAcrossGatewayRoots } from "../../state/registry/cross-port"; import type { SandboxEntry } from "../../state/registry"; +import { parseLiveSandboxEntries } from "../../runtime-recovery"; import { isLocalOllamaRouteOwner, readLocalAdapterJsonFile, @@ -93,10 +95,42 @@ export function clearPendingOllamaModelCleanup( } /** The registry fields an Ollama GPU-release decision reads. */ -export type OllamaModelHolder = Pick; +export type OllamaModelHolder = Pick< + SandboxEntry, + "name" | "provider" | "model" | "endpointUrl" | "gatewayName" | "gatewayPort" +>; export type OllamaModelRoute = Pick; +export type OllamaActiveOwnershipDiscovery = + | { + readonly ok: true; + /** Names for logs and legacy callers; ownership decisions prefer the rows below. */ + readonly activeSandboxNames: ReadonlySet; + /** Live peer rows retain gateway identity when names collide across roots. */ + readonly activePeers?: ReadonlySet; + readonly gatewayChecks: readonly { + readonly activeSandboxes: readonly string[]; + readonly gateway: string; + }[]; + } + | { readonly ok: false; readonly message: string }; + +export type OllamaActiveOwnershipDiscoveryFn = ( + peers: readonly OllamaModelHolder[], + environment: NodeJS.ProcessEnv, +) => OllamaActiveOwnershipDiscovery; + +export type OllamaOwnershipPhaseCapture = ( + gatewayName: string, + environment: NodeJS.ProcessEnv, +) => { readonly output: string; readonly status: number | null }; + +export type OllamaOwnershipDiscoveryDeps = { + readonly parseLiveSandboxEntries?: typeof parseLiveSandboxEntries; + readonly resolvePersistedSandboxOwnershipGateway?: (sandbox: OllamaModelHolder) => string; +}; + export type OllamaModelOwnershipDecision = | { readonly kind: "missing-model" } | { @@ -115,10 +149,15 @@ export type OllamaModelOwnershipDecision = * Decide whether this sandbox's Ollama model has another active owner. * * Registry rows persist after a sandbox stops and can also contain incomplete - * onboarding reservations. Callers must supply the sandbox names that a live - * runtime probe found in Ready or Running phase. A matching registry row that - * is not in that set is evidence to report, not an owner that blocks release. + * onboarding reservations. Callers should supply the peer rows found in Ready + * or Running phase. A matching row absent from that live set is evidence to + * report, not an owner that blocks release; the names set remains as a legacy + * fallback for callers that do not provide gateway-aware peer rows. */ +export function listOllamaModelOwnershipPeersAcrossGatewayRoots(): SandboxEntry[] { + return listInferenceRouteOwnersAcrossGatewayRoots(); +} + export function matchingOllamaModelPeers( sandbox: OllamaModelHolder, peers: readonly T[], @@ -126,13 +165,33 @@ export function matchingOllamaModelPeers( ): T[] { const model = sandbox.model?.trim(); if (!model) return []; - return peers.filter( - (peer) => - peer.name !== sandbox.name && + return peers.filter((peer) => { + const gatewayPortsKnown = + peer.gatewayPort !== null && + peer.gatewayPort !== undefined && + sandbox.gatewayPort !== null && + sandbox.gatewayPort !== undefined; + const gatewayNamesKnown = + peer.gatewayName !== null && + peer.gatewayName !== undefined && + sandbox.gatewayName !== null && + sandbox.gatewayName !== undefined; + const peerHasGatewayIdentity = peer.gatewayName != null || peer.gatewayPort != null; + const sandboxHasGatewayIdentity = sandbox.gatewayName != null || sandbox.gatewayPort != null; + const sameSandbox = + peer.name === sandbox.name && + (gatewayPortsKnown + ? peer.gatewayPort === sandbox.gatewayPort + : gatewayNamesKnown + ? peer.gatewayName === sandbox.gatewayName + : !peerHasGatewayIdentity && !sandboxHasGatewayIdentity); + return ( + !sameSandbox && isLocalOllamaRouteOwner(peer, selectedHost) && !!peer.model && - ollamaModelRefsMatch(peer.model, model), - ); + ollamaModelRefsMatch(peer.model, model) + ); + }); } export function decideOllamaModelOwnership( @@ -140,22 +199,25 @@ export function decideOllamaModelOwnership( peers: readonly OllamaModelHolder[], activeSandboxNames: ReadonlySet, selectedHost: OllamaHostRoute | null = null, + activePeers?: ReadonlySet, ): OllamaModelOwnershipDecision { const model = sandbox.model?.trim(); if (!model) return { kind: "missing-model" }; const matchingPeers = matchingOllamaModelPeers(sandbox, peers, selectedHost); - const activePeers = matchingPeers - .filter((peer) => activeSandboxNames.has(peer.name)) + const isActive = (peer: OllamaModelHolder): boolean => + activePeers ? activePeers.has(peer) : activeSandboxNames.has(peer.name); + const activePeerNames = matchingPeers + .filter(isActive) .map((peer) => peer.name) .sort(); const stalePeers = matchingPeers - .filter((peer) => !activeSandboxNames.has(peer.name)) + .filter((peer) => !isActive(peer)) .map((peer) => peer.name) .sort(); - return activePeers.length > 0 - ? { kind: "shared-active", model, activePeers, stalePeers } + return activePeerNames.length > 0 + ? { kind: "shared-active", model, activePeers: activePeerNames, stalePeers } : { kind: "exclusive", model, stalePeers }; } @@ -163,6 +225,85 @@ export function decideOllamaModelOwnership( * Conservative compatibility helper for callers that do not probe live state. * Every matching registry peer remains protected on those paths. */ +export function discoverOllamaModelOwnership( + peers: readonly OllamaModelHolder[], + environment: NodeJS.ProcessEnv, + capturePhases: OllamaOwnershipPhaseCapture, + deps: OllamaOwnershipDiscoveryDeps = {}, +): OllamaActiveOwnershipDiscovery { + const parseEntries = deps.parseLiveSandboxEntries ?? parseLiveSandboxEntries; + if (peers.length === 0) { + return { ok: true, activeSandboxNames: new Set(), activePeers: new Set(), gatewayChecks: [] }; + } + const resolveGateway = deps.resolvePersistedSandboxOwnershipGateway; + if (!resolveGateway) { + return { + ok: false, + message: "could not resolve a sibling gateway: gateway binding resolver is unavailable", + }; + } + + const peersByGateway = new Map(); + try { + for (const peer of peers) { + const gateway = resolveGateway(peer); + const gatewayPeers = peersByGateway.get(gateway) ?? []; + gatewayPeers.push(peer); + peersByGateway.set(gateway, gatewayPeers); + } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + return { ok: false, message: `could not resolve a sibling gateway: ${detail}` }; + } + + const activeSandboxNames = new Set(); + const activePeers = new Set(); + const gatewayChecks: Array<{ activeSandboxes: string[]; gateway: string }> = []; + for (const [gateway, gatewayPeers] of peersByGateway) { + let result; + try { + result = capturePhases(gateway, environment); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + return { ok: false, message: `OpenShell could not list gateway '${gateway}': ${detail}` }; + } + if (result.status !== 0) { + const detail = result.output.trim().replace(/\s+/g, " ").slice(0, 300); + return { + ok: false, + message: `OpenShell could not list sandbox phases on gateway '${gateway}'${ + detail ? `: ${detail}` : "" + }`, + }; + } + const phases = new Map(parseEntries(result.output).map((entry) => [entry.name, entry.phase])); + const activeSandboxes: string[] = []; + for (const peer of gatewayPeers) { + const phase = phases.get(peer.name); + if ( + phase === undefined || + phase === "Stopped" || + phase === "Error" || + phase === "Failed" || + phase === "Evicted" + ) { + continue; + } + if (phase === null || phase === "Unknown") { + return { + ok: false, + message: `OpenShell returned no usable phase for sibling '${peer.name}' on gateway '${gateway}'`, + }; + } + activeSandboxNames.add(peer.name); + activePeers.add(peer); + activeSandboxes.push(peer.name); + } + gatewayChecks.push({ activeSandboxes, gateway }); + } + return { ok: true, activeSandboxNames, activePeers, gatewayChecks }; +} + export function exclusivelyHeldOllamaModel( sandbox: OllamaModelHolder, peers: readonly OllamaModelHolder[], @@ -189,6 +330,31 @@ export function exclusivelyHeldOllamaModel( * Comparing model refs is strictly conservative: it can only miss a release, * never evict a model the new route still uses. */ +export function supersededOllamaModelWithActivePeers( + previous: OllamaModelHolder | null, + next: OllamaModelRoute, + peers: readonly OllamaModelHolder[], + activeSandboxNames: ReadonlySet, + selectedHost: OllamaHostRoute | null = null, + activePeers?: ReadonlySet, +): string | null { + if (!previous || !isLocalOllamaRouteOwner(previous, selectedHost)) return null; + const ownership = decideOllamaModelOwnership( + previous, + peers, + activeSandboxNames, + selectedHost, + activePeers, + ); + if (ownership.kind !== "exclusive") return null; + const nextModel = next.model?.trim(); + if (!nextModel) return null; + return isLocalOllamaRouteOwner(next, selectedHost) && + ollamaModelRefsMatch(ownership.model, nextModel) + ? null + : ownership.model; +} + export function supersededOllamaModel( previous: OllamaModelHolder | null, next: OllamaModelRoute, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 6d5e36d3f71..ce70b22feab 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2308,6 +2308,7 @@ function getSetupInferenceDeps(): SetupInferenceDeps { withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, step, getGatewayName: () => GATEWAY_NAME, + resolveOllamaOwnershipGateway: gatewayBinding.resolveSandboxGatewayName, runOpenshell, inferenceRouteMutator, inferenceRouteObserver, @@ -2317,7 +2318,6 @@ function getSetupInferenceDeps(): SetupInferenceDeps { isNonInteractive, updateSandbox: registry.reserveSandboxInferenceRoute, getSandbox: registry.getSandbox, - listSandboxes: registry.listSandboxes, unloadOllamaModels, hermesProviderAuth, getHermesToolGatewayBroker, diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 9a7be3bc9fa..c254e05c320 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -1,13 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import type { OllamaModelHolder } from "../inference/ollama/model-ownership"; +import type { SandboxEntry } from "../state/registry"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { createProviderReviewDeps, createSetupInference, + releaseSupersededOllamaModel, type SetupInferenceDeps, } from "./setup-inference"; @@ -17,6 +24,345 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); +function createOllamaCleanupHarness( + options: { + peers?: readonly SandboxEntry[]; + useProductionPeerSource?: boolean; + useProductionDiscovery?: boolean; + activeSandboxNames?: ReadonlySet; + discovery?: SetupInferenceDeps["discoverActiveOllamaSandboxNames"]; + pendingModels?: readonly string[]; + } = {}, +) { + let pendingModels = [...(options.pendingModels ?? [])]; + const localInference = { + loadPersistedOllamaHost: vi.fn(() => "127.0.0.1"), + loadPendingOllamaModelCleanup: vi.fn(() => pendingModels), + persistPendingOllamaModelCleanup: vi.fn((_name: string, models: readonly string[]) => { + pendingModels = [...new Set([...pendingModels, ...models])]; + }), + clearPendingOllamaModelCleanup: vi.fn((_name: string, models: readonly string[]) => { + pendingModels = pendingModels.filter((model) => !models.includes(model)); + }), + clearPersistedOllamaHostIfUnused: vi.fn(), + }; + const unloadOllamaModels = vi.fn(() => ({ + ok: true, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + })); + const discoverActiveOllamaSandboxNames = vi.fn( + options.discovery ?? + (() => ({ + ok: true as const, + activeSandboxNames: options.activeSandboxNames ?? new Set(), + gatewayChecks: [], + })), + ); + const deps = { + localInference, + ...(options.useProductionPeerSource + ? {} + : { listOllamaModelOwnershipPeers: () => options.peers ?? [] }), + ...(!options.useProductionDiscovery ? { discoverActiveOllamaSandboxNames } : {}), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + } as unknown as SetupInferenceDeps; + return { deps, localInference, unloadOllamaModels, discoverActiveOllamaSandboxNames }; +} + +const previousLocalOllamaRoute: OllamaModelHolder = { + name: "alpha", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434", +}; + +function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): void { + releaseSupersededOllamaModel( + previous, + "nvidia-prod", + "nvidia/test-model", + "https://integrate.api.nvidia.com/v1", + { ok: true }, + deps, + ); +} + +describe("releaseSupersededOllamaModel", () => { + it("unloads a superseded model when matching registry rows are not live", () => { + const staleReservation = { + name: "incomplete-reservation", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: null, + gatewayName: "stale-peer-gateway", + } as unknown as SandboxEntry; + const harness = createOllamaCleanupHarness({ peers: [staleReservation] }); + + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).toHaveBeenCalledExactlyOnceWith( + [], + ); + }); + + it("releases the target model before unrelated gateway discovery for receipt retirement", () => { + const unrelatedPeer = { + name: "unrelated-peer", + provider: "ollama-local", + model: "llama3.2:1b", + endpointUrl: null, + gatewayName: "unavailable-gateway", + } as unknown as SandboxEntry; + const discovery = vi.fn((owners: readonly OllamaModelHolder[]) => + owners.some((owner) => owner.model === "llama3.2:1b") + ? { ok: false as const, message: "unrelated gateway unavailable" } + : { ok: true as const, activeSandboxNames: new Set(), gatewayChecks: [] }, + ); + const harness = createOllamaCleanupHarness({ peers: [unrelatedPeer], discovery }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(discovery).toHaveBeenCalledTimes(2); + expect(discovery.mock.calls[0]?.[0]).toEqual([]); + expect(discovery.mock.calls[1]?.[0]).toEqual([unrelatedPeer]); + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith("alpha", [ + "qwen2.5:1.5b", + ]); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("host route receipt was retained"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("preserves the model and host receipt while a matching live peer owns it", () => { + const activePeer = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: null, + gatewayName: "peer-gateway-port", + } as unknown as SandboxEntry; + const harness = createOllamaCleanupHarness({ + peers: [activePeer], + activeSandboxNames: new Set([activePeer.name]), + }); + + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); + + it("uses Ollama peer records from other gateway roots by default", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-peer-roots-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "active-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + activeSandboxNames: new Set([peer.name]), + }); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); + expect(harness.discoverActiveOllamaSandboxNames.mock.calls[0]?.[0]).toEqual([ + expect.objectContaining({ name: "active-peer", gatewayName: "nemoclaw-32665" }), + ]); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("uses suppressed OpenShell output in the default cross-gateway discovery path", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "active-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + useProductionDiscovery: true, + }); + const runOpenshell = vi.fn(() => ({ + status: 0, + stdout: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", + stderr: "", + })); + const deps = harness.deps as SetupInferenceDeps; + deps.runOpenshell = runOpenshell as unknown as SetupInferenceDeps["runOpenshell"]; + deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName!; + + try { + releaseToNvidia(previousLocalOllamaRoute, deps); + + expect(runOpenshell).toHaveBeenCalledExactlyOnceWith( + ["sandbox", "list", "-g", "nemoclaw-32665"], + expect.objectContaining({ suppressOutput: true }), + ); + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("fails closed and records retry state when default discovery lacks a gateway resolver", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-missing-resolver-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "stale-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "stale-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + useProductionDiscovery: true, + }); + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + (harness.deps as SetupInferenceDeps).runOpenshell = + runOpenshell as unknown as SetupInferenceDeps["runOpenshell"]; + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + "alpha", + ["qwen2.5:1.5b"], + ); + expect(runOpenshell).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); + } finally { + warning.mockRestore(); + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("records a failed ownership probe for retry, then unloads only after a safe retry", () => { + const discovery = vi + .fn>() + .mockReturnValueOnce({ ok: false, message: "gateway unavailable" }) + .mockReturnValueOnce({ ok: true, activeSandboxNames: new Set(), gatewayChecks: [] }); + const harness = createOllamaCleanupHarness({ discovery }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + "alpha", + ["qwen2.5:1.5b"], + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); + + releaseToNvidia({ ...previousLocalOllamaRoute, provider: "nvidia-prod" }, harness.deps); + + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith("alpha", [ + "qwen2.5:1.5b", + ]); + } finally { + warning.mockRestore(); + } + }); + + it("does not probe or warn when the selected route still owns the same Ollama model", () => { + const harness = createOllamaCleanupHarness(); + + releaseSupersededOllamaModel( + previousLocalOllamaRoute, + "ollama-local", + "qwen2.5:1.5b", + "http://127.0.0.1:11434", + { ok: true }, + harness.deps, + ); + + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); + + it("does not probe unrelated routes when there is no Ollama cleanup retry", () => { + const harness = createOllamaCleanupHarness({ + peers: [{ name: "ollama-peer", provider: "ollama-local", model: "qwen2.5:1.5b" }], + }); + + releaseToNvidia( + { name: "alpha", provider: "nvidia-prod", model: "nvidia/model" }, + harness.deps, + ); + + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); +}); + describe("createProviderReviewDeps", () => { it("prepares the Ollama proxy after review acceptance", async () => { const updateSession = vi.fn(); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index bc6d98c1bad..2347bac3d7c 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -31,11 +31,15 @@ import { } from "../inference/native-nvidia"; import { clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, + listOllamaModelOwnershipPeersAcrossGatewayRoots, loadPendingOllamaModelCleanup, + matchingOllamaModelPeers, + type OllamaActiveOwnershipDiscoveryFn, type OllamaModelHolder, persistPendingOllamaModelCleanup, - supersededOllamaModel, + supersededOllamaModelWithActivePeers, } from "../inference/ollama/model-ownership"; import { getOllamaProxyToken, @@ -236,7 +240,10 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // #9110 optional GPU-release seams; omitted by test literals that build deps // by hand, so every read below must stay optional-chained. getSandbox?: typeof import("../state/registry").getSandbox; - listSandboxes?: typeof import("../state/registry").listSandboxes; + listOllamaModelOwnershipPeers?: () => readonly OllamaModelHolder[]; + discoverActiveOllamaSandboxNames?: OllamaActiveOwnershipDiscoveryFn; + resolveOllamaOwnershipGateway?: (peer: OllamaModelHolder) => string; + environment?: NodeJS.ProcessEnv; getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; setNativeNvidiaProviderAuthority?: typeof import("../state/registry").setNativeNvidiaProviderAuthority; unloadOllamaModels?: (onlyModels: readonly string[]) => OllamaUnloadResult | void; @@ -513,7 +520,7 @@ export type SetupInference = ( * the route is committed by this point, so GPU cleanup must never change the * result or the exit code. */ -function releaseSupersededOllamaModel( +export function releaseSupersededOllamaModel( previous: OllamaModelHolder | null, nextProvider: string, nextModel: string, @@ -549,25 +556,100 @@ function releaseSupersededOllamaModel( try { const withOwnershipLock = deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; withOwnershipLock(() => { - const peers = deps.listSandboxes?.().sandboxes ?? []; const selectedHost = deps.localInference.loadPersistedOllamaHost?.() ?? null; const nextRoute = { provider: nextProvider, model: nextModel, endpointUrl: nextEndpointUrl }; - const superseded = supersededOllamaModel(previous, nextRoute, peers, selectedHost); + const previousOwnsOllama = isLocalOllamaRouteOwner(previous, selectedHost); + // This is only a retry candidate. A successful live probe below is still + // required before the model can be unloaded. + const retryCandidate = previousOwnsOllama + ? supersededOllamaModelWithActivePeers(previous, nextRoute, [], new Set(), selectedHost) + : null; + attemptedModels = retryCandidate ? [retryCandidate] : []; const pending = loadPending(previous.name); - const retryablePending = pending.filter((model) => - supersededOllamaModel( - { name: previous.name, provider: "ollama-local", model, endpointUrl: null }, + attemptedModels = [...new Set([...attemptedModels, ...pending])]; + if (!retryCandidate && pending.length === 0) return; + + const peers = ( + deps.listOllamaModelOwnershipPeers ?? listOllamaModelOwnershipPeersAcrossGatewayRoots + )(); + const ollamaRouteCandidates = peers.filter((peer) => + isLocalOllamaRouteOwner(peer, selectedHost), + ); + const environment = deps.environment ?? process.env; + const discoverPeers = (owners: readonly OllamaModelHolder[]) => + deps.discoverActiveOllamaSandboxNames + ? deps.discoverActiveOllamaSandboxNames(owners, environment) + : discoverOllamaModelOwnership( + owners, + environment, + (gateway, env) => { + const result = deps.runOpenshell(["sandbox", "list", "-g", gateway], { + env, + ignoreError: true, + suppressOutput: true, + maxBuffer: 1024 * 1024, + timeout: 10_000, + }); + return { + status: result.status, + output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), + }; + }, + { + resolvePersistedSandboxOwnershipGateway: deps.resolveOllamaOwnershipGateway, + }, + ); + // A different model cannot keep one of the models being released resident. + // Discover only matching owners before unloading so unrelated gateways do + // not delay cleanup; all-route discovery is reserved for receipt retirement. + const modelOwners = [ + ...new Set( + attemptedModels.flatMap((model) => + matchingOllamaModelPeers( + { ...previous, provider: "ollama-local", model, endpointUrl: null }, + ollamaRouteCandidates, + selectedHost, + ), + ), + ), + ]; + const discovery = discoverPeers(modelOwners); + if (!discovery.ok) { + pendingRecordFailure = persistRetry(); + const retryMessage = pendingRecordFailure + ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}.` + : attemptedModels.length > 0 + ? `Re-run onboarding to retry only: ${attemptedModels.join(", ")}.` + : "The Ollama host receipt was left unchanged."; + cleanupWarning = + ` Warning: NemoClaw could not verify Ollama model ownership for '${previous.name}': ` + + `${discovery.message}. No model was unloaded; the new inference route remains active. ${retryMessage}`; + return; + } + const superseded = previousOwnsOllama + ? supersededOllamaModelWithActivePeers( + previous, + nextRoute, + peers, + discovery.activeSandboxNames, + selectedHost, + discovery.activePeers, + ) + : null; + const retryablePending = pending.filter((model) => { + return !!supersededOllamaModelWithActivePeers( + { ...previous, provider: "ollama-local", model, endpointUrl: null }, nextRoute, peers, + discovery.activeSandboxNames, selectedHost, - ), - ); + discovery.activePeers, + ); + }); attemptedModels = [...new Set([...(superseded ? [superseded] : []), ...retryablePending])]; - const retireRoute = - isLocalOllamaRouteOwner(previous, selectedHost) && - !isLocalOllamaRouteOwner(nextRoute, selectedHost) && - !peers.some((peer) => isLocalOllamaRouteOwner(peer, selectedHost)); - if (attemptedModels.length === 0 && !retireRoute) return; + const retireRouteCandidate = + previousOwnsOllama && !isLocalOllamaRouteOwner(nextRoute, selectedHost); + if (attemptedModels.length === 0 && !retireRouteCandidate) return; try { revalidateSandboxIdentity?.("release the superseded Ollama model"); } catch (error) { @@ -615,8 +697,28 @@ function releaseSupersededOllamaModel( } } const pendingAfterCleanup = loadPending(previous.name); - if (retireRoute && !cleanupWarning && pendingAfterCleanup.length === 0) { - deps.localInference.clearPersistedOllamaHostIfUnused?.(peers); + if (retireRouteCandidate && !cleanupWarning && pendingAfterCleanup.length === 0) { + const routeOwnerDiscovery = + modelOwners.length === ollamaRouteCandidates.length + ? discovery + : discoverPeers(ollamaRouteCandidates); + if (!routeOwnerDiscovery.ok) { + cleanupWarning = + ` Warning: Ollama cleanup for '${previous.name}' was scoped to verified model owners, ` + + "but the host route receipt was retained because other Ollama gateway owners could not be verified."; + } else { + const activeOllamaPeerRoutes = peers.filter( + (peer) => + (routeOwnerDiscovery.activePeers + ? routeOwnerDiscovery.activePeers.has(peer) + : routeOwnerDiscovery.activeSandboxNames.has(peer.name)) && + isLocalOllamaRouteOwner(peer, selectedHost), + ); + if (activeOllamaPeerRoutes.length === 0) { + // The live-probed route set is empty; the helper retains its own guard. + deps.localInference.clearPersistedOllamaHostIfUnused?.(activeOllamaPeerRoutes); + } + } } }); } catch (error) { diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 1ca897f922f..523bac0f845 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -1111,11 +1111,8 @@ describe("re-onboard Ollama GPU release (#9110)", () => { persistAndProbeOllamaProxy: async () => {}, applyLocalInferenceRoute: options.applyLocalInferenceRoute, getSandbox: options.getSandbox, - listSandboxes: () => ({ - sandboxes: - typeof options.sandboxes === "function" ? options.sandboxes() : options.sandboxes, - defaultSandbox: null, - }), + listOllamaModelOwnershipPeers: () => + typeof options.sandboxes === "function" ? options.sandboxes() : options.sandboxes, unloadOllamaModels: options.unloadOllamaModels, localInference: { validateOllamaModelWithToolsOverride: () => ({ ok: true }), @@ -1168,7 +1165,7 @@ describe("re-onboard Ollama GPU release (#9110)", () => { { ok: true }, ); - expect(clearReceipt).toHaveBeenCalledWith(finalRoutes); + expect(clearReceipt).toHaveBeenCalledWith([]); expect(loadPersistedOllamaHost(stateRoot)).toBeNull(); } finally { fs.rmSync(stateRoot, { recursive: true, force: true }); @@ -1402,9 +1399,9 @@ describe("re-onboard Ollama GPU release (#9110)", () => { getOllamaProxyToken: () => "proxy-token", persistAndProbeOllamaProxy: async () => {}, getSandbox, - listSandboxes: () => { + listOllamaModelOwnershipPeers: () => { events.push("peer-scan"); - return { sandboxes: [priorEntry], defaultSandbox: null }; + return [priorEntry]; }, unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => { diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 35cf3b6e2a0..9f5327d70a8 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -488,7 +488,12 @@ export function createDirectSetupInferenceHarnessFactory( // the production defaults never read the developer's real registry or // curl a live Ollama daemon. getSandbox: () => null, - listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), + listOllamaModelOwnershipPeers: () => [], + discoverActiveOllamaSandboxNames: (peers) => ({ + ok: true, + activeSandboxNames: new Set(peers.map((peer) => peer.name)), + gatewayChecks: [], + }), unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => operation(), ...options.overrides, From a53b96c4a14de06359143c0c0a85a327211caa1a Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 9 Oct 2026 11:16:50 +0000 Subject: [PATCH 02/44] fix(inference): remove obsolete Ollama ownership path Signed-off-by: Yimo Jiang --- docs/inference/set-up-ollama.mdx | 8 +- .../inference/ollama/model-ownership.test.ts | 112 +++++++++--------- src/lib/inference/ollama/model-ownership.ts | 30 ----- 3 files changed, 58 insertions(+), 92 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 4f981322fcf..ff9fac7684e 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -405,9 +405,11 @@ When you stop a single Ollama-backed sandbox, NemoClaw unloads only that sandbox It leaves the model loaded only when OpenShell reports that another matching Ollama-backed sandbox is active. Stopped or incomplete sibling registry rows do not retain the model. If NemoClaw cannot verify sibling state, it does not unload the model and `stop` exits nonzero. -When you re-onboard an existing Ollama-backed sandbox onto a different model, NemoClaw unloads the model it replaced, with the same sibling protection. -A re-onboard that keeps the same model leaves it loaded, because the new route can still be served by the same Ollama daemon. -This cleanup runs on a best-effort basis and does not delete downloaded model files. +When you re-onboard an Ollama-backed sandbox from the host Ollama route to a different model or provider, NemoClaw checks live ownership before releasing its previous model. +If another active sandbox uses the same local Ollama model, NemoClaw keeps it loaded. +If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model, records it for retry, and leaves the new route active. +If the new route uses the same model through the same local daemon, NemoClaw keeps the model loaded. +This cleanup is best-effort and does not delete downloaded model files. ## Related Topics diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 1a65ce67c80..7fbdb42bf99 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -10,12 +10,11 @@ import { clearPendingOllamaModelCleanup, decideOllamaModelOwnership, discoverOllamaModelOwnership, - exclusivelyHeldOllamaModel, loadPendingOllamaModelCleanup, + type OllamaHostRoute, type OllamaModelHolder, type OllamaModelRoute, persistPendingOllamaModelCleanup, - supersededOllamaModel, supersededOllamaModelWithActivePeers, } from "./model-ownership"; import { isLocalOllamaRouteOwner } from "./model-ownership"; @@ -28,6 +27,23 @@ function route(model: string, overrides: Partial = {}): Ollama return { provider: "ollama-local", model, ...overrides }; } +function releaseCandidate( + previous: OllamaModelHolder | null, + next: OllamaModelRoute, + peers: readonly OllamaModelHolder[], + activePeers: readonly OllamaModelHolder[] = [], + selectedHost: OllamaHostRoute | null = null, +): string | null { + return supersededOllamaModelWithActivePeers( + previous, + next, + peers, + new Set(activePeers.map((peer) => peer.name)), + selectedHost, + new Set(activePeers), + ); +} + describe("isLocalOllamaRouteOwner", () => { it.each([["ollama-local"], ["ollama/qwen3-vl:4b"]])( "recognizes the direct local provider %s", @@ -59,9 +75,10 @@ describe("isLocalOllamaRouteOwner", () => { }); }); -describe("supersededOllamaModel", () => { +describe("supersededOllamaModelWithActivePeers route changes", () => { it("releases the previous model when a re-onboard moves to a different one (#9110)", () => { - expect(supersededOllamaModel(holder(), route("qwen2.5:7b"), [holder()])).toBe("llama3"); + const previous = holder(); + expect(releaseCandidate(previous, route("qwen2.5:7b"), [previous])).toBe("llama3"); }); it.each([ @@ -70,94 +87,93 @@ describe("supersededOllamaModel", () => { ["an explicit latest tag on the previous model", "llama3:latest", "llama3"], ])("keeps the model when the next ref is %s (#9110)", (_label, previousModel, nextModel) => { const previous = holder({ model: previousModel }); - expect(supersededOllamaModel(previous, route(nextModel), [previous])).toBeNull(); + expect(releaseCandidate(previous, route(nextModel), [previous])).toBeNull(); }); it.each([["llama3"], ["llama3:latest"]])( - "keeps a model an Ollama peer records as %s (#9110)", + "keeps a model an active Ollama peer records as %s (#9110)", (peerModel) => { + const previous = holder(); const peer = holder({ model: peerModel, name: "peer" }); - expect(supersededOllamaModel(holder(), route("qwen2.5:7b"), [holder(), peer])).toBeNull(); + expect(releaseCandidate(previous, route("qwen2.5:7b"), [previous, peer], [peer])).toBeNull(); }, ); it("releases the model when peers hold different ones (#9110)", () => { + const previous = holder(); const peer = holder({ model: "llama3:8b", name: "peer" }); - expect(supersededOllamaModel(holder(), route("qwen2.5:7b"), [holder(), peer])).toBe("llama3"); + expect(releaseCandidate(previous, route("qwen2.5:7b"), [previous, peer])).toBe("llama3"); }); it.each([["nvidia-prod"], ["vllm-local"], [undefined]])( "does nothing when the previous provider is %s (#9110)", (provider) => { const previous = holder({ provider }); - expect(supersededOllamaModel(previous, route("qwen2.5:7b"), [previous])).toBeNull(); + expect(releaseCandidate(previous, route("qwen2.5:7b"), [previous])).toBeNull(); }, ); it("does nothing when the previous model is unrecorded (#9110)", () => { const previous = holder({ model: undefined }); - expect(supersededOllamaModel(previous, route("qwen2.5:7b"), [previous])).toBeNull(); + expect(releaseCandidate(previous, route("qwen2.5:7b"), [previous])).toBeNull(); }); it.each([[""], [" "]])("does nothing when the next model is %j (#9110)", (nextModel) => { - expect(supersededOllamaModel(holder(), route(nextModel), [holder()])).toBeNull(); + const previous = holder(); + expect(releaseCandidate(previous, route(nextModel), [previous])).toBeNull(); }); it("does nothing when there is no previous entry (#9110)", () => { - expect(supersededOllamaModel(null, route("qwen2.5:7b"), [])).toBeNull(); + expect(releaseCandidate(null, route("qwen2.5:7b"), [])).toBeNull(); }); it("keeps a model selected through a compatible endpoint at the same local daemon", () => { + const previous = holder(); expect( - supersededOllamaModel( - holder(), + releaseCandidate( + previous, route("llama3:latest", { provider: "compatible-endpoint", endpointUrl: "http://127.0.0.1:11434/v1", }), - [holder()], + [previous], + [], "127.0.0.1", ), ).toBeNull(); }); it("does not mistake a remote compatible endpoint for the local daemon", () => { + const previous = holder(); expect( - supersededOllamaModel( - holder(), + releaseCandidate( + previous, route("llama3", { provider: "compatible-endpoint", endpointUrl: "https://ollama.example.com:11434/v1", }), - [holder()], + [previous], + [], "127.0.0.1", ), ).toBe("llama3"); }); }); -describe("supersededOllamaModelWithActivePeers", () => { +describe("supersededOllamaModelWithActivePeers live ownership rows", () => { it("releases a superseded model despite stale or incomplete matching registry rows", () => { + const previous = holder(); const inactivePeer = holder({ name: "incomplete-reservation" }); - expect( - supersededOllamaModelWithActivePeers( - holder(), - route("qwen2.5:1.5b"), - [inactivePeer], - new Set(), - ), - ).toBe("llama3"); + expect(releaseCandidate(previous, route("qwen2.5:1.5b"), [previous, inactivePeer])).toBe( + "llama3", + ); }); it("protects the model while a matching sibling is active", () => { + const previous = holder(); const activePeer = holder({ name: "active-peer", model: "llama3:latest" }); expect( - supersededOllamaModelWithActivePeers( - holder(), - route("qwen2.5:1.5b"), - [holder(), activePeer], - new Set(["active-peer"]), - ), + releaseCandidate(previous, route("qwen2.5:1.5b"), [previous, activePeer], [activePeer]), ).toBeNull(); }); @@ -165,34 +181,19 @@ describe("supersededOllamaModelWithActivePeers", () => { const previous = holder({ gatewayName: "current-gateway" }); const peer = holder({ gatewayName: "other-gateway" }); - expect( - supersededOllamaModelWithActivePeers( - previous, - route("qwen2.5:1.5b"), - [peer], - new Set([peer.name]), - ), - ).toBeNull(); + expect(releaseCandidate(previous, route("qwen2.5:1.5b"), [peer], [peer])).toBeNull(); }); it("does not treat a same-named row with incomplete gateway identity as the subject", () => { const previous = holder(); const peer = holder({ gatewayName: "other-gateway" }); - expect( - supersededOllamaModelWithActivePeers( - previous, - route("qwen2.5:1.5b"), - [peer], - new Set([peer.name]), - ), - ).toBeNull(); + expect(releaseCandidate(previous, route("qwen2.5:1.5b"), [peer], [peer])).toBeNull(); }); it("preserves an active model selected through the same local daemon", () => { - expect( - supersededOllamaModelWithActivePeers(holder(), route("llama3:latest"), [holder()], new Set()), - ).toBeNull(); + const previous = holder(); + expect(releaseCandidate(previous, route("llama3:latest"), [previous])).toBeNull(); }); }); @@ -319,13 +320,6 @@ describe("decideOllamaModelOwnership", () => { }); }); -describe("exclusivelyHeldOllamaModel", () => { - it("is not blocked by a non-Ollama peer that records the same model (#9110)", () => { - const peer = holder({ name: "peer", provider: "nvidia-prod" }); - expect(exclusivelyHeldOllamaModel(holder(), [holder(), peer])).toBe("llama3"); - }); -}); - describe("pending Ollama model cleanup", () => { it("persists exact sandbox-scoped models until verified release", () => { const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); diff --git a/src/lib/inference/ollama/model-ownership.ts b/src/lib/inference/ollama/model-ownership.ts index a71c04440f9..fb962fd8682 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -304,20 +304,6 @@ export function discoverOllamaModelOwnership( return { ok: true, activeSandboxNames, activePeers, gatewayChecks }; } -export function exclusivelyHeldOllamaModel( - sandbox: OllamaModelHolder, - peers: readonly OllamaModelHolder[], - selectedHost: OllamaHostRoute | null = null, -): string | null { - const decision = decideOllamaModelOwnership( - sandbox, - peers, - new Set(peers.map((peer) => peer.name)), - selectedHost, - ); - return decision.kind === "exclusive" ? decision.model : null; -} - /** * The Ollama model a re-onboard just superseded, or null when nothing is safe * to release (#9110). @@ -354,19 +340,3 @@ export function supersededOllamaModelWithActivePeers( ? null : ownership.model; } - -export function supersededOllamaModel( - previous: OllamaModelHolder | null, - next: OllamaModelRoute, - peers: readonly OllamaModelHolder[], - selectedHost: OllamaHostRoute | null = null, -): string | null { - if (!previous || !isLocalOllamaRouteOwner(previous, selectedHost)) return null; - const nextModel = next.model?.trim(); - if (!nextModel) return null; - const held = exclusivelyHeldOllamaModel(previous, peers, selectedHost); - if (!held) return null; - return isLocalOllamaRouteOwner(next, selectedHost) && ollamaModelRefsMatch(held, nextModel) - ? null - : held; -} From d706ee7cb73721f9115a11099e5eab8b52cdc813 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 9 Oct 2026 13:22:05 +0000 Subject: [PATCH 03/44] fix(inference): protect shared Ollama models during destroy Signed-off-by: Yimo Jiang --- docs/inference/set-up-ollama.mdx | 3 +- src/lib/actions/sandbox/destroy.test.ts | 312 +++++++++++++++++++++++- src/lib/actions/sandbox/destroy.ts | 145 +++++++---- src/lib/inference/ollama/proxy.test.ts | 73 ++++++ src/lib/inference/ollama/proxy.ts | 14 +- src/lib/onboard/setup-inference.test.ts | 51 +++- 6 files changed, 539 insertions(+), 59 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index ff9fac7684e..9f2e4d0c229 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -400,7 +400,7 @@ Windows-host Ollama does not receive this Linux recovery guidance. ## Release GPU Memory -When you destroy an Ollama-backed sandbox or stop host services, NemoClaw asks Ollama to unload each currently loaded model by sending `keep_alive: 0`. +When you destroy a sandbox or stop host services, NemoClaw asks Ollama to unload only that sandbox's current model and any models recorded for cleanup retry. Other models resident on the shared host daemon are left alone. When you stop a single Ollama-backed sandbox, NemoClaw unloads only that sandbox's own model. It leaves the model loaded only when OpenShell reports that another matching Ollama-backed sandbox is active. Stopped or incomplete sibling registry rows do not retain the model. @@ -409,6 +409,7 @@ When you re-onboard an Ollama-backed sandbox from the host Ollama route to a dif If another active sandbox uses the same local Ollama model, NemoClaw keeps it loaded. If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model, records it for retry, and leaves the new route active. If the new route uses the same model through the same local daemon, NemoClaw keeps the model loaded. +If the unload cleanup fails, the new route remains active and NemoClaw keeps the model recorded for cleanup retry; rerun onboarding or run `$$nemoclaw destroy` to retry the recorded cleanup. This cleanup is best-effort and does not delete downloaded model files. ## Related Topics diff --git a/src/lib/actions/sandbox/destroy.test.ts b/src/lib/actions/sandbox/destroy.test.ts index 2eebeb64688..b9ae6fbd1fa 100644 --- a/src/lib/actions/sandbox/destroy.test.ts +++ b/src/lib/actions/sandbox/destroy.test.ts @@ -21,7 +21,6 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { { stopHostServices: false }, { getSandbox: () => null, - listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), withOllamaModelOwnershipLock: (operation) => operation(), loadPersistedOllamaHost: () => "127.0.0.1", loadPendingOllamaModelCleanup: () => [], @@ -122,6 +121,310 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { }); describe("cleanupSandboxServices Ollama ownership", () => { + it("retains a pending model owned by an active sandbox in another gateway root", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const peer = { + name: "peer", + gatewayName: "gateway-b", + gatewayPort: 18081, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const unloadOllamaModels = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + const runOpenshell = vi.fn(() => ({ + status: 0, + stdout: "NAME CREATED PHASE\npeer 2026-01-01 Running", + stderr: "", + })); + + await cleanupSandboxServices( + SANDBOX, + { stopHostServices: false, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own, peer], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => ["old-model"], + clearPendingOllamaModelCleanup, + resolvePersistedSandboxOwnershipGateway: (sandbox) => + sandbox.gatewayName === "gateway-b" ? "gateway-b" : "gateway-a", + migrateLegacyCloudflaredState: vi.fn(() => false), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell, + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ); + + expect(runOpenshell).toHaveBeenCalledWith( + ["sandbox", "list", "-g", "gateway-b"], + expect.objectContaining({ stdio: ["ignore", "pipe", "pipe"] }), + ); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + + it("uses default phase capture output to fail closed on an unreachable gateway", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const peer = { + name: "peer", + gatewayName: "gateway-b", + gatewayPort: 18081, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const unloadOllamaModels = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + const runOpenshell = vi.fn(() => ({ + status: 1, + stdout: "", + stderr: "gateway unreachable", + })); + + await expect( + cleanupSandboxServices( + SANDBOX, + { stopHostServices: false, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own, peer], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => ["old-model"], + clearPendingOllamaModelCleanup, + resolvePersistedSandboxOwnershipGateway: (sandbox) => + sandbox.gatewayName === "gateway-b" ? "gateway-b" : "gateway-a", + migrateLegacyCloudflaredState: vi.fn(() => false), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell, + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ), + ).rejects.toThrow(/gateway unreachable/); + + expect(runOpenshell).toHaveBeenCalledWith( + ["sandbox", "list", "-g", "gateway-b"], + expect.objectContaining({ + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + }), + ); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + + it("preserves pending cleanup and fails closed when cross-gateway ownership is inconclusive", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const peer = { + name: "peer", + gatewayName: "gateway-b", + gatewayPort: 18081, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const unloadOllamaModels = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + + await expect( + cleanupSandboxServices( + SANDBOX, + { stopHostServices: false, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own, peer], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => ["old-model"], + clearPendingOllamaModelCleanup, + captureSandboxOwnershipPhases: () => ({ status: 1, output: "gateway unavailable" }), + resolvePersistedSandboxOwnershipGateway: (sandbox) => + sandbox.gatewayName === "gateway-b" ? "gateway-b" : "gateway-a", + migrateLegacyCloudflaredState: vi.fn(() => false), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell: vi.fn(() => ({ status: 0 })), + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ), + ).rejects.toThrow(/ownership could not be verified/); + + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + + it("scopes host-service model cleanup when another gateway owns a model", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const peer = { + name: "peer", + gatewayName: "gateway-b", + gatewayPort: 18081, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const unloadOllamaModels = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + const stopAll = vi.fn(); + + await cleanupSandboxServices( + SANDBOX, + { stopHostServices: true, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own, peer], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + clearPendingOllamaModelCleanup, + captureSandboxOwnershipPhases: () => ({ + status: 0, + output: "NAME CREATED PHASE\npeer 2026-01-01 Running", + }), + resolvePersistedSandboxOwnershipGateway: (sandbox) => + sandbox.gatewayName === "gateway-b" ? "gateway-b" : "gateway-a", + migrateLegacyCloudflaredState: vi.fn(() => false), + stopAll, + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell: vi.fn(() => ({ status: 0 })), + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ); + + expect(stopAll).toHaveBeenCalledWith( + expect.objectContaining({ cleanupOllamaModels: false, stopCloudflared: false }), + ); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + + it("retains retry state when host-service cleanup cannot verify a peer", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const peer = { + name: "peer", + gatewayName: "gateway-b", + gatewayPort: 18081, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const unloadOllamaModels = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + const stopAll = vi.fn(); + + await expect( + cleanupSandboxServices( + SANDBOX, + { stopHostServices: true, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own, peer], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => ["old-model"], + clearPendingOllamaModelCleanup, + captureSandboxOwnershipPhases: () => ({ + status: 1, + output: "gateway unavailable", + }), + resolvePersistedSandboxOwnershipGateway: (sandbox) => + sandbox.gatewayName === "gateway-b" ? "gateway-b" : "gateway-a", + migrateLegacyCloudflaredState: vi.fn(() => false), + stopAll, + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell: vi.fn(() => ({ status: 0 })), + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ), + ).rejects.toThrow(/Host-service cleanup failed.*ownership could not be verified/); + + expect(stopAll).toHaveBeenCalledWith( + expect.objectContaining({ cleanupOllamaModels: false, stopCloudflared: false }), + ); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + + it("retains pending cleanup when the unload request fails", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const unloadOllamaModels = vi.fn(() => ({ + ok: false, + outcome: "still-resident" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["old-model"], + discoveries: [], + requests: [], + })); + const clearPendingOllamaModelCleanup = vi.fn(); + + await expect( + cleanupSandboxServices( + SANDBOX, + { stopHostServices: false, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => ["old-model"], + clearPendingOllamaModelCleanup, + migrateLegacyCloudflaredState: vi.fn(() => false), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell: vi.fn(() => ({ status: 0 })), + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ), + ).rejects.toThrow(/Ollama model cleanup failed/); + + expect(unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["old-model"]); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + it("keeps a model shared through a compatible endpoint at the same local daemon", async () => { const own = { name: SANDBOX, @@ -141,7 +444,12 @@ describe("cleanupSandboxServices Ollama ownership", () => { { stopHostServices: false }, { getSandbox: () => own, - listSandboxes: () => ({ sandboxes: [own, peer], defaultSandbox: null }), + listOllamaModelOwnershipPeers: () => [own, peer], + captureSandboxOwnershipPhases: () => ({ + status: 0, + output: "NAME CREATED PHASE\npeer 2026-01-01 Running", + }), + resolvePersistedSandboxOwnershipGateway: () => "nemoclaw", loadPersistedOllamaHost: () => "127.0.0.1", migrateLegacyCloudflaredState: vi.fn(() => false), unloadOllamaModels, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index ab80bcd202f..c6fd5acdee6 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -27,8 +27,10 @@ import { readPendingHostLocalVllmRetirement, } from "../../inference/local-model-profile/cleanup"; import { + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, loadPersistedOllamaHost, + matchingOllamaModelPeers, type OllamaUnloadResult, withOllamaModelOwnershipTransaction, } from "../../inference/ollama/proxy"; @@ -205,11 +207,17 @@ export function requireSandboxDestructiveCleanupAuthority( return requireRuntimeProviderDestructiveCleanupAuthority(sandboxName, sandbox, providers); } -type RunOpenshell = (args: string[], opts?: Record) => { status: number | null }; +type RunOpenshell = ( + args: string[], + opts?: Record, +) => { + status: number | null; + stdout?: string; + stderr?: string; +}; export type CleanupSandboxServicesDeps = { getSandbox?: typeof registry.getSandbox; - listSandboxes?: typeof registry.listSandboxes; stopAll?: (opts: { sandboxName: string; channelStopTransport?: RuntimeProviderChannelStopTransport; @@ -229,6 +237,15 @@ export type CleanupSandboxServicesDeps = { ) => void; loadPersistedOllamaHost?: () => "127.0.0.1" | "host.docker.internal" | null; withOllamaModelOwnershipLock?: (operation: () => T) => T; + listOllamaModelOwnershipPeers?: () => readonly registry.SandboxEntry[]; + discoverOllamaModelOwnership?: typeof discoverOllamaModelOwnership; + captureSandboxOwnershipPhases?: ( + gatewayName: string, + environment: NodeJS.ProcessEnv, + ) => { readonly output: string; readonly status: number | null }; + resolvePersistedSandboxOwnershipGateway?: ( + sandbox: Pick, + ) => string; ollamaModelRefsMatch?: (left: string, right: string) => boolean; runOpenshell?: RunOpenshell; rmSync?: typeof fs.rmSync; @@ -309,7 +326,6 @@ export async function cleanupSandboxServices( const validatedSandboxName = validateName(sandboxName, "sandbox name"); const servicesPidDir = path.resolve("/tmp", `nemoclaw-services-${validatedSandboxName}`); const getSandbox = deps.getSandbox ?? registry.getSandbox; - const listSandboxes = deps.listSandboxes ?? registry.listSandboxes; const stopAll = deps.stopAll ?? ((opts: { @@ -440,25 +456,93 @@ export async function cleanupSandboxServices( } let ollamaCleanup: OllamaUnloadResult | void = undefined; + const cleanupScopedOllamaModels = () => { + const sb = getSandbox(validatedSandboxName); + const selectedHost = loadPersistedOllamaHost(); + const pending = loadPendingOllamaModelCleanup(validatedSandboxName); + const currentModel = String(sb?.model ?? "").trim(); + const candidates = [ + ...pending, + ...(sb && isLocalOllamaRouteOwner(sb, selectedHost) && currentModel ? [currentModel] : []), + ].filter( + (model, index, models) => + models.findIndex((candidate) => ollamaModelRefsMatch(candidate, model)) === index, + ); + if (candidates.length === 0) return; + + const owners = deps.listOllamaModelOwnershipPeers ?? listInferenceRouteOwnersAcrossGatewayRoots; + const ownerRows = owners(); + const captureOwnershipPhases = + deps.captureSandboxOwnershipPhases ?? + ((gatewayName, environment) => { + const result = runOpenshell(["sandbox", "list", "-g", gatewayName], { + env: environment, + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + maxBuffer: 1024 * 1024, + timeout: 10_000, + }); + return { + status: result.status, + output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), + }; + }); + const resolveOwnerGateway = + deps.resolvePersistedSandboxOwnershipGateway ?? + ((owner: Pick) => { + if (owner.gatewayName == null && owner.gatewayPort == null) { + throw new Error(`gateway identity is unavailable for sibling sandbox '${owner.name}'`); + } + return resolveSandboxDestroyGatewayName(owner.name, owner as registry.SandboxEntry); + }); + const releasable: string[] = []; + for (const model of candidates) { + const holder = { + name: validatedSandboxName, + gatewayName: sb?.gatewayName ?? null, + gatewayPort: sb?.gatewayPort ?? gatewayPort ?? null, + provider: "ollama-local", + model, + endpointUrl: null, + }; + const matchingPeers = matchingOllamaModelPeers(holder, ownerRows, selectedHost); + const discovery = (deps.discoverOllamaModelOwnership ?? discoverOllamaModelOwnership)( + matchingPeers, + process.env, + captureOwnershipPhases, + { resolvePersistedSandboxOwnershipGateway: resolveOwnerGateway }, + ); + if (!discovery.ok) { + throw new Error( + `Ollama model ownership could not be verified for '${model}': ${discovery.message}. ` + + "No model was unloaded; retry destroy after restoring gateway access.", + ); + } + const activePeers = discovery.activePeers + ? matchingPeers.filter((peer) => discovery.activePeers?.has(peer)) + : matchingPeers.filter((peer) => discovery.activeSandboxNames.has(peer.name)); + if (activePeers.length === 0) releasable.push(model); + } + if (releasable.length === 0) return; + ollamaCleanup = unloadOllamaModels(releasable); + if (!ollamaCleanup || ollamaCleanup.ok) { + clearPendingOllamaModelCleanup(validatedSandboxName, releasable); + } + }; + if (stopHostServices) { - // `stopAll()` owns the host-wide unload when this sandbox has an Ollama - // route or retained cleanup work. The dashboard tunnel has independent - // host lifetime and must survive every sandbox destroy (#11628). + // Stopping host services must not unload models owned by another gateway + // or unrelated models resident on the shared host Ollama daemon. try { ollamaCleanup = withOllamaModelOwnershipLock(() => { - const sandbox = getSandbox(validatedSandboxName); - const pending = loadPendingOllamaModelCleanup(validatedSandboxName); - const selectedHost = loadPersistedOllamaHost(); - const cleanupOllamaModels = Boolean( - (sandbox && isLocalOllamaRouteOwner(sandbox, selectedHost)) || pending.length > 0, - ); - return stopAll({ + const result = stopAll({ sandboxName: validatedSandboxName, ...(channelStopTransport ? { channelStopTransport } : {}), - cleanupOllamaModels, + cleanupOllamaModels: false, stopCloudflared: false, - unloadOllamaModels: () => unloadOllamaModels(), }); + cleanupScopedOllamaModels(); + return ollamaCleanup ?? result; }); } catch (error) { const detail = (error instanceof Error ? error.message : String(error)) @@ -473,35 +557,7 @@ export async function cleanupSandboxServices( ); } } else { - // No global stop, so `stopAll()` did not run; explicitly free Ollama - // models for this sandbox if its provider used Ollama. Without this - // branch a single-sandbox destroy would leave models loaded on the GPU. - withOllamaModelOwnershipLock(() => { - const sb = getSandbox(validatedSandboxName); - const selectedHost = loadPersistedOllamaHost(); - const peers = listSandboxes().sandboxes.filter( - (candidate) => - candidate.name !== validatedSandboxName && - isLocalOllamaRouteOwner(candidate, selectedHost), - ); - const pending = loadPendingOllamaModelCleanup(validatedSandboxName); - const currentModel = String(sb?.model ?? "").trim(); - const candidates = [ - ...pending, - ...(sb && isLocalOllamaRouteOwner(sb, selectedHost) && currentModel ? [currentModel] : []), - ].filter( - (model, index, models) => - models.findIndex((candidate) => ollamaModelRefsMatch(candidate, model)) === index && - !peers.some( - (candidate) => candidate.model && ollamaModelRefsMatch(model, candidate.model), - ), - ); - if (candidates.length === 0) return; - ollamaCleanup = unloadOllamaModels(candidates); - if (!ollamaCleanup || ollamaCleanup.ok) { - clearPendingOllamaModelCleanup(validatedSandboxName, candidates); - } - }); + withOllamaModelOwnershipLock(cleanupScopedOllamaModels); } if (ollamaCleanup && !ollamaCleanup.ok) { const recoveryAction = @@ -1156,7 +1212,6 @@ async function destroySandboxUnlocked( }, { getSandbox: getRegisteredSandbox, - listSandboxes: listRegisteredSandboxes, runOpenshell: cleanupRunOpenshell, }, ); diff --git a/src/lib/inference/ollama/proxy.test.ts b/src/lib/inference/ollama/proxy.test.ts index fe23c4958d0..6c84592b088 100644 --- a/src/lib/inference/ollama/proxy.test.ts +++ b/src/lib/inference/ollama/proxy.test.ts @@ -27,6 +27,13 @@ const CHILD_PROCESS_DIST = require.resolve("node:child_process"); const RUNNER_DIST = require.resolve("../../runner"); const SUBPROCESS_ENV_DIST = require.resolve("../../subprocess-env"); const LIFECYCLE_DIST = require.resolve("../local-adapter-lifecycle"); +const LIFECYCLE_LOCK_DIST = require.resolve("../../state/mcp-lifecycle-lock"); +const LIFECYCLE_LOCK_ACQUISITION_DIST = + require.resolve("../../state/mcp-lifecycle-lock-acquisition"); +const LIFECYCLE_LOCK_STORAGE_DIST = require.resolve("../../state/mcp-lifecycle-lock-storage"); +const STATE_PATHS_DIST = require.resolve("../../state/paths"); +const STATE_ROOT_DIST = require.resolve("../../state/state-root"); +const CORE_PORTS_DIST = require.resolve("../../core/ports"); interface MockSetup { installed: string[] | (() => string[]); @@ -121,6 +128,72 @@ function loadProxyWithMocks(setup: MockSetup): { }; } +describe("Ollama model ownership locks", () => { + it("shares one lock across non-default gateway state roots", async () => { + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); + const originalProxy = require.cache[PROXY_DIST]; + const originalLocal = require.cache[LOCAL_DIST]; + const originalLifecycle = require.cache[LIFECYCLE_DIST]; + const originalLifecycleLock = require.cache[LIFECYCLE_LOCK_DIST]; + const originalLockAcquisition = require.cache[LIFECYCLE_LOCK_ACQUISITION_DIST]; + const originalLockStorage = require.cache[LIFECYCLE_LOCK_STORAGE_DIST]; + const originalStatePaths = require.cache[STATE_PATHS_DIST]; + const originalStateRoot = require.cache[STATE_ROOT_DIST]; + const originalCorePorts = require.cache[CORE_PORTS_DIST]; + delete require.cache[PROXY_DIST]; + delete require.cache[LOCAL_DIST]; + delete require.cache[LIFECYCLE_DIST]; + delete require.cache[LIFECYCLE_LOCK_DIST]; + delete require.cache[LIFECYCLE_LOCK_ACQUISITION_DIST]; + delete require.cache[LIFECYCLE_LOCK_STORAGE_DIST]; + delete require.cache[STATE_PATHS_DIST]; + delete require.cache[STATE_ROOT_DIST]; + delete require.cache[CORE_PORTS_DIST]; + let setup: ReturnType | undefined; + + try { + setup = loadProxyWithMocks({ installed: [], promptValues: [] }); + const lifecycleLock = require( + LIFECYCLE_LOCK_DIST, + ) as typeof import("../../state/mcp-lifecycle-lock"); + const sharedStateDir = path.join( + (require(LIFECYCLE_DIST) as { SHARED_LOCAL_ADAPTER_STATE_DIR: string }) + .SHARED_LOCAL_ADAPTER_STATE_DIR, + "state", + ); + let syncLockIsShared = false; + let asyncLockIsShared = false; + + setup.proxy.withOllamaModelOwnershipLock(() => { + syncLockIsShared = lifecycleLock.isMcpLifecycleLockHeld( + "host-global-ollama-model-ownership", + sharedStateDir, + ); + }); + await setup.proxy.withOllamaModelOwnershipTransaction(async () => { + asyncLockIsShared = lifecycleLock.isMcpLifecycleLockHeld( + "host-global-ollama-model-ownership", + sharedStateDir, + ); + }); + + expect(syncLockIsShared).toBe(true); + expect(asyncLockIsShared).toBe(true); + } finally { + setup?.restore(); + require.cache[PROXY_DIST] = originalProxy; + require.cache[LOCAL_DIST] = originalLocal; + require.cache[LIFECYCLE_DIST] = originalLifecycle; + require.cache[LIFECYCLE_LOCK_DIST] = originalLifecycleLock; + require.cache[LIFECYCLE_LOCK_ACQUISITION_DIST] = originalLockAcquisition; + require.cache[LIFECYCLE_LOCK_STORAGE_DIST] = originalLockStorage; + require.cache[STATE_PATHS_DIST] = originalStatePaths; + require.cache[STATE_ROOT_DIST] = originalStateRoot; + require.cache[CORE_PORTS_DIST] = originalCorePorts; + } + }); +}); + describe("promptOllamaModel installed-model fit filter", () => { let active: { restore: () => void } | null = null; afterEach(() => { diff --git a/src/lib/inference/ollama/proxy.ts b/src/lib/inference/ollama/proxy.ts index 07c470b53a2..c7596fa5566 100644 --- a/src/lib/inference/ollama/proxy.ts +++ b/src/lib/inference/ollama/proxy.ts @@ -32,8 +32,10 @@ const { const { ollamaModelRefsMatch }: typeof import("./model-discovery") = require("./model-discovery"); const { clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, loadPendingOllamaModelCleanup, + matchingOllamaModelPeers, }: typeof import("./model-ownership") = require("./model-ownership"); const { getBootstrapOllamaModelOptions, @@ -133,12 +135,16 @@ function withOllamaProxyLifecycleLock(operation: () => T): T { /** Serialize model-holder checks and GPU release across sandbox commands. */ function withOllamaModelOwnershipLock(operation: () => T): T { - return withMcpLifecycleLockSync(OLLAMA_MODEL_OWNERSHIP_LOCK, operation); + return withMcpLifecycleLockSync(OLLAMA_MODEL_OWNERSHIP_LOCK, operation, { + stateDir: path.join(PROXY_STATE_DIR, "state"), + }); } -/** Serialize async host-route publication with final ownership retirement. */ +/** Serialize async host-route publication with final ownership retirement across gateway roots. */ function withOllamaModelOwnershipTransaction(operation: () => Promise | T): Promise { - return withMcpLifecycleLock(OLLAMA_MODEL_OWNERSHIP_LOCK, operation); + return withMcpLifecycleLock(OLLAMA_MODEL_OWNERSHIP_LOCK, operation, { + stateDir: path.join(PROXY_STATE_DIR, "state"), + }); } function withOllamaProxyLifecycleTransaction(operation: () => Promise | T): Promise { @@ -1834,6 +1840,7 @@ export { buildOllamaAuthProxySpawnEnv, checkOllamaModelToolSupport, clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, ensureOllamaAuthProxy, getOllamaProxyToken, getOllamaPullTimeoutMs, @@ -1843,6 +1850,7 @@ export { killStaleProxyIfUnused, loadPendingOllamaModelCleanup, loadPersistedOllamaHost, + matchingOllamaModelPeers, noAuthProxy, ollamaModelRefsMatch, persistAndProbeOllamaProxy, diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index c254e05c320..78ba98b132b 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -9,6 +9,7 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import type { OllamaModelHolder } from "../inference/ollama/model-ownership"; +import type { OllamaUnloadResult } from "../inference/ollama/proxy"; import type { SandboxEntry } from "../state/registry"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { @@ -32,6 +33,7 @@ function createOllamaCleanupHarness( activeSandboxNames?: ReadonlySet; discovery?: SetupInferenceDeps["discoverActiveOllamaSandboxNames"]; pendingModels?: readonly string[]; + unloadResult?: OllamaUnloadResult; } = {}, ) { let pendingModels = [...(options.pendingModels ?? [])]; @@ -46,14 +48,17 @@ function createOllamaCleanupHarness( }), clearPersistedOllamaHostIfUnused: vi.fn(), }; - const unloadOllamaModels = vi.fn(() => ({ - ok: true, - outcome: "released" as const, - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - })); + const unloadOllamaModels = vi.fn( + () => + options.unloadResult ?? { + ok: true, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }, + ); const discoverActiveOllamaSandboxNames = vi.fn( options.discovery ?? (() => ({ @@ -330,6 +335,36 @@ describe("releaseSupersededOllamaModel", () => { } }); + it("keeps the retry record when unloading the superseded model fails", () => { + const harness = createOllamaCleanupHarness({ + unloadResult: { + ok: false, + outcome: "still-resident", + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }, + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + "alpha", + ["qwen2.5:1.5b"], + ); + expect(harness.localInference.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("Re-run onboarding or destroy 'alpha' to retry only"), + ); + } finally { + warning.mockRestore(); + } + }); + it("does not probe or warn when the selected route still owns the same Ollama model", () => { const harness = createOllamaCleanupHarness(); From 681c18af86b399b5b786a0508538159638898467 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 9 Oct 2026 13:55:17 +0000 Subject: [PATCH 04/44] test(inference): align destroy cleanup ownership harness Signed-off-by: Yimo Jiang --- .../destroy-cleanup-sandbox-services.test.ts | 38 +++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts index 475fe979c25..3dfa13d5714 100644 --- a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts +++ b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts @@ -1,10 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // -// Regression guard for #2717: cleanupSandboxServices must invoke -// `unloadOllamaModels()` exactly once across both branches when the sandbox -// owns Ollama cleanup work, and never for an unrelated provider. This avoids -// both orphaned GPU memory and the original duplicate-call bug. +// Regression guard for #2717 and #12677: destroy cleanup must release each +// exclusively owned Ollama model once, preserve models held by active peers, +// and keep host-service teardown separate from model release. import path from "node:path"; import { describe, expect, it, vi } from "vitest"; @@ -12,7 +11,7 @@ import { describe, expect, it, vi } from "vitest"; import type { CleanupSandboxServicesDeps } from "../../../src/lib/actions/sandbox/destroy.js"; import { cleanupSandboxServices } from "../../../src/lib/actions/sandbox/destroy.js"; import { ollamaModelRefsMatch } from "../../../src/lib/inference/ollama/model-discovery.js"; -import type { OllamaUnloadResult } from "../../../src/lib/inference/ollama/proxy.js"; +import type { OllamaModelHolder } from "../../../src/lib/inference/ollama/model-ownership.js"; import { SANDBOX_PROVIDER_SUFFIXES } from "../../../src/lib/onboard/sandbox-provider-cleanup.js"; type SandboxLike = { name?: string; model?: string | null; provider?: string | null } | null; @@ -20,7 +19,6 @@ type StopAllOptions = { sandboxName: string; cleanupOllamaModels?: boolean; stopCloudflared?: boolean; - unloadOllamaModels?: () => OllamaUnloadResult | void; }; function buildDeps( @@ -31,7 +29,8 @@ function buildDeps( Pick< CleanupSandboxServicesDeps, | "getSandbox" - | "listSandboxes" + | "listOllamaModelOwnershipPeers" + | "discoverOllamaModelOwnership" | "stopAll" | "migrateLegacyCloudflaredState" | "unloadOllamaModels" @@ -63,13 +62,15 @@ function buildDeps( }, deps: { getSandbox: vi.fn(() => target as never), - listSandboxes: vi.fn(() => ({ - sandboxes: [...(target ? [target] : []), ...peers] as never, - defaultSandbox: null, + listOllamaModelOwnershipPeers: vi.fn(() => [...(target ? [target] : []), ...peers] as never), + discoverOllamaModelOwnership: vi.fn((matchingPeers: readonly OllamaModelHolder[]) => ({ + ok: true as const, + activeSandboxNames: new Set(matchingPeers.map((peer) => peer.name)), + activePeers: new Set(matchingPeers), + gatewayChecks: [], })), stopAll: vi.fn((opts: StopAllOptions) => { stopAllCalls.push(opts); - return opts.cleanupOllamaModels === false ? undefined : opts.unloadOllamaModels?.(); }), migrateLegacyCloudflaredState: vi.fn(() => false), unloadOllamaModels: vi.fn((onlyModels?: readonly string[]) => { @@ -88,7 +89,7 @@ function buildDeps( }; } -describe("cleanupSandboxServices Ollama unload (#2717)", () => { +describe("cleanupSandboxServices Ollama unload", () => { const cleanupFailure = { ok: false as const, outcome: "discovery-failed" as const, @@ -99,7 +100,7 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { message: "could not connect", }; - it("delegates GPU unload to stopAll() exactly once when stopHostServices=true", async () => { + it("runs host-service stop and scoped model release separately", async () => { const harness = buildDeps({ provider: "ollama-local" }); await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); @@ -108,16 +109,15 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.stopAllCalls[0]).toEqual( expect.objectContaining({ sandboxName: "regression-2717", - cleanupOllamaModels: true, + cleanupOllamaModels: false, stopCloudflared: false, - unloadOllamaModels: expect.any(Function), }), ); expect(harness.deps.unloadOllamaModels).toHaveBeenCalledOnce(); expect(harness.unloadCalls).toBe(1); }); - it("skips host-wide Ollama discovery for a final sandbox with no Ollama ownership", async () => { + it("skips Ollama discovery for a final sandbox with no Ollama ownership", async () => { const harness = buildDeps({ provider: "nvidia-prod" }); await cleanupSandboxServices("regression-2717", { stopHostServices: true }, harness.deps); @@ -127,13 +127,12 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { sandboxName: "regression-2717", cleanupOllamaModels: false, stopCloudflared: false, - unloadOllamaModels: expect.any(Function), }), ]); expect(harness.deps.unloadOllamaModels).not.toHaveBeenCalled(); }); - it("keeps host-wide Ollama cleanup enabled for retained model recovery", async () => { + it("uses scoped Ollama cleanup for retained model recovery", async () => { const harness = buildDeps({ provider: "nvidia-prod" }); vi.mocked(harness.deps.loadPendingOllamaModelCleanup).mockReturnValue(["old-model"]); @@ -142,9 +141,8 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { expect(harness.stopAllCalls).toEqual([ expect.objectContaining({ sandboxName: "regression-2717", - cleanupOllamaModels: true, + cleanupOllamaModels: false, stopCloudflared: false, - unloadOllamaModels: expect.any(Function), }), ]); expect(harness.deps.unloadOllamaModels).toHaveBeenCalledOnce(); From c7350e03a5c0da8e8c107951485a929077f10fc1 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 03:08:11 +0000 Subject: [PATCH 05/44] refactor: share sandbox phase capture Signed-off-by: Yimo Jiang --- src/lib/actions/sandbox/destroy.test.ts | 38 ++++++++++-------------- src/lib/actions/sandbox/destroy.ts | 16 ++-------- src/lib/actions/sandbox/gateway-state.ts | 21 ++----------- src/lib/adapters/openshell/runtime.ts | 15 ++++++++++ 4 files changed, 34 insertions(+), 56 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.test.ts b/src/lib/actions/sandbox/destroy.test.ts index b9ae6fbd1fa..280414c4f43 100644 --- a/src/lib/actions/sandbox/destroy.test.ts +++ b/src/lib/actions/sandbox/destroy.test.ts @@ -2,12 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as openshellRuntime from "../../adapters/openshell/runtime"; import type { SandboxEntry } from "../../state/registry"; import { SANDBOX_PROVIDER_SUFFIXES } from "../../onboard/sandbox-provider-cleanup"; import { assertUnambiguousDestroyContainerIdentity, cleanupSandboxServices } from "./destroy"; +afterEach(() => vi.restoreAllMocks()); + const SANDBOX = "mybox"; const mainPidDir = path.resolve("/tmp", `nemoclaw-services-${SANDBOX}`); const googlechatPidDir = `${mainPidDir}-googlechat`; @@ -138,11 +141,10 @@ describe("cleanupSandboxServices Ollama ownership", () => { } as SandboxEntry; const unloadOllamaModels = vi.fn(); const clearPendingOllamaModelCleanup = vi.fn(); - const runOpenshell = vi.fn(() => ({ - status: 0, - stdout: "NAME CREATED PHASE\npeer 2026-01-01 Running", - stderr: "", - })); + const captureSandboxOwnershipPhases = vi + .spyOn(openshellRuntime, "captureSandboxPhasesForGateway") + .mockReturnValue({ status: 0, output: "NAME CREATED PHASE\npeer 2026-01-01 Running" }); + const runOpenshell = vi.fn(() => ({ status: 0 })); await cleanupSandboxServices( SANDBOX, @@ -165,15 +167,12 @@ describe("cleanupSandboxServices Ollama ownership", () => { }, ); - expect(runOpenshell).toHaveBeenCalledWith( - ["sandbox", "list", "-g", "gateway-b"], - expect.objectContaining({ stdio: ["ignore", "pipe", "pipe"] }), - ); + expect(captureSandboxOwnershipPhases).toHaveBeenCalledWith("gateway-b", process.env); expect(unloadOllamaModels).not.toHaveBeenCalled(); expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); }); - it("uses default phase capture output to fail closed on an unreachable gateway", async () => { + it("fails closed when shared phase capture reports an unreachable gateway", async () => { const own = { name: SANDBOX, gatewayName: "gateway-a", @@ -190,11 +189,10 @@ describe("cleanupSandboxServices Ollama ownership", () => { } as SandboxEntry; const unloadOllamaModels = vi.fn(); const clearPendingOllamaModelCleanup = vi.fn(); - const runOpenshell = vi.fn(() => ({ - status: 1, - stdout: "", - stderr: "gateway unreachable", - })); + const captureSandboxOwnershipPhases = vi + .spyOn(openshellRuntime, "captureSandboxPhasesForGateway") + .mockReturnValue({ status: 1, output: "gateway unreachable" }); + const runOpenshell = vi.fn(() => ({ status: 0 })); await expect( cleanupSandboxServices( @@ -219,13 +217,7 @@ describe("cleanupSandboxServices Ollama ownership", () => { ), ).rejects.toThrow(/gateway unreachable/); - expect(runOpenshell).toHaveBeenCalledWith( - ["sandbox", "list", "-g", "gateway-b"], - expect.objectContaining({ - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }), - ); + expect(captureSandboxOwnershipPhases).toHaveBeenCalledWith("gateway-b", process.env); expect(unloadOllamaModels).not.toHaveBeenCalled(); expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 6698501cb32..4027df17cda 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -4,6 +4,7 @@ import fs from "node:fs"; import path from "node:path"; +import { captureSandboxPhasesForGateway } from "../../adapters/openshell/runtime"; import { CLI_NAME } from "../../cli/branding"; import { G, R, YW } from "../../cli/terminal-style"; import { prompt as askPrompt } from "../../credentials/store"; @@ -474,20 +475,7 @@ export async function cleanupSandboxServices( const owners = deps.listOllamaModelOwnershipPeers ?? listInferenceRouteOwnersAcrossGatewayRoots; const ownerRows = owners(); const captureOwnershipPhases = - deps.captureSandboxOwnershipPhases ?? - ((gatewayName, environment) => { - const result = runOpenshell(["sandbox", "list", "-g", gatewayName], { - env: environment, - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - maxBuffer: 1024 * 1024, - timeout: 10_000, - }); - return { - status: result.status, - output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), - }; - }); + deps.captureSandboxOwnershipPhases ?? captureSandboxPhasesForGateway; const resolveOwnerGateway = deps.resolvePersistedSandboxOwnershipGateway ?? ((owner: Pick) => { diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 8227e3996fc..4c2bddd9142 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -209,11 +209,6 @@ type SandboxGatewayStateLookup = ( gatewayName?: string, ) => SandboxGatewayState | Promise; -function gatewayScopedArgs(args: string[], gatewayName?: string): string[] { - if (!gatewayName) return args; - return [...args.slice(0, 2), "-g", gatewayName, ...args.slice(2)]; -} - /** Resolve the authoritative gateway for a persisted sibling ownership row. */ export function resolvePersistedSandboxOwnershipGateway( sandbox: Pick, @@ -221,20 +216,8 @@ export function resolvePersistedSandboxOwnershipGateway( return getPersistedSandboxTargetGatewayName(sandbox); } -/** Capture one gateway's live sandbox phases for host-global model ownership. */ -export function captureSandboxOwnershipPhases( - gatewayName: string, - environment: NodeJS.ProcessEnv, -): { readonly output: string; readonly status: number | null } { - const result = captureOpenshell(gatewayScopedArgs(["sandbox", "list"], gatewayName), { - env: environment, - ignoreError: true, - includeStderr: true, - maxBuffer: 1024 * 1024, - timeout: 10_000, - }); - return { output: result.output, status: result.status }; -} +/** Capture sandbox phases from each owning gateway for host-global model ownership. */ +export { captureSandboxPhasesForGateway as captureSandboxOwnershipPhases } from "../../adapters/openshell/runtime"; /** Recover a receipt-bound portable sandbox before the live lookup rejects a stopped container. */ export async function recoverPortableDemoSandboxLifecycleForConnect( sandboxName: string, diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index d2a9991ac7d..c43039cc2f5 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -109,6 +109,21 @@ export function captureOpenshell(args: CommandArgs, opts: RunnerOptions = {}) { }); } +/** Capture one gateway's live sandbox phases. */ +export function captureSandboxPhasesForGateway( + gatewayName: string, + environment: NodeJS.ProcessEnv, +): { readonly output: string; readonly status: number | null } { + const result = captureOpenshell(["sandbox", "list", "-g", gatewayName], { + env: environment, + ignoreError: true, + includeStderr: true, + maxBuffer: 1024 * 1024, + timeout: 10_000, + }); + return { output: result.output, status: result.status }; +} + /** Capture an OpenShell command while treating an unavailable binary as a recoverable error. */ export function captureResolvedOpenshell(args: CommandArgs, opts: RunnerOptions = {}) { const openshell = opts.openshellBinary ?? resolveOpenshellBinaryOrNull(); From 43bf8e3fbd26e384c6f0aab612f1f07b375b570f Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 03:38:33 +0000 Subject: [PATCH 06/44] test: mock shared sandbox phase capture Signed-off-by: Yimo Jiang --- test/helpers/destroy-flow-test-harness.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 4730451ac16..5e6a9cbbe36 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -548,6 +548,17 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr return { status: 0, stdout: "", stderr: "" }; } }); + vi.spyOn(runtime, "captureSandboxPhasesForGateway").mockImplementation(() => { + const result = options.sandboxListResult ?? { + status: 0, + stdout: sandboxListJson(sandboxPresent ? ["alpha"] : []), + stderr: "", + }; + return { + status: result.status, + output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), + }; + }); const captureOpenshellSpy = vi.spyOn(runtime, "captureOpenshell").mockReturnValue({ status: 0, output: options.liveListOutput ?? "", From 0904dfdf066b46ae74254f8c84307b60f2993896 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 03:42:57 +0000 Subject: [PATCH 07/44] test: align ownership capture output fixture Signed-off-by: Yimo Jiang --- test/helpers/destroy-flow-test-harness.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 5e6a9cbbe36..1815a599ba2 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -556,7 +556,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr }; return { status: result.status, - output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), + output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(), }; }); const captureOpenshellSpy = vi.spyOn(runtime, "captureOpenshell").mockReturnValue({ From 776e1176af1da8e2058bccd80d5ad03c7a5a4083 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 05:50:33 +0000 Subject: [PATCH 08/44] fix(inference): serialize Ollama route transitions Signed-off-by: Yimo Jiang --- docs/reference/commands.mdx | 2 +- src/lib/onboard/setup-inference.test.ts | 44 ++++- src/lib/onboard/setup-inference.ts | 46 +++-- .../onboard-inference-gateway-scope.test.ts | 157 ++++++++++++++++++ 4 files changed, 229 insertions(+), 20 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index dc426c134c2..a2518f6d874 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2085,7 +2085,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` ### `$$nemoclaw destroy` -Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. This removes the sandbox from the registry. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. For Ollama-backed sandboxes, `destroy` also asks Ollama to unload currently loaded models and clears stale auth proxy state on a best-effort basis. +Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. This removes the sandbox from the registry. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. For Ollama-backed sandboxes, `destroy` best-effort unloads only that sandbox's current Ollama model and any models recorded for a cleanup retry. It preserves a model still used by an active matching sandbox, and clears stale auth proxy state on a best-effort basis. `destroy` considers retirement of the host-global `nemoclaw-vllm` container for a sandbox with provider `vllm-local`, including Local NIM. It requires confirmed sandbox deletion and no remaining registered `vllm-local` consumer in any gateway state root. diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 78ba98b132b..d5383aa22f2 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -598,7 +598,22 @@ describe("native NVIDIA onboarding", () => { createProvider, } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); - const updateSandbox = vi.fn(() => true); + const events: string[] = []; + const updateSandbox = vi.fn(() => { + events.push("route-published"); + return true; + }); + const unloadOllamaModels = vi.fn(() => { + events.push("unload"); + return { + ok: true as const, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }; + }); const setNativeNvidiaProviderAuthority = vi.fn(() => true); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); @@ -613,7 +628,28 @@ describe("native NVIDIA onboarding", () => { runOpenshell, updateSandbox, setNativeNvidiaProviderAuthority, - getSandbox: () => null, + getSandbox: () => previousLocalOllamaRoute, + localInference: { + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + persistPendingOllamaModelCleanup: vi.fn(), + clearPendingOllamaModelCleanup: vi.fn(), + clearPersistedOllamaHostIfUnused: vi.fn(), + }, + listOllamaModelOwnershipPeers: () => [], + discoverActiveOllamaSandboxNames: () => ({ + ok: true as const, + activeSandboxNames: new Set(), + gatewayChecks: [], + }), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + withOllamaModelOwnershipTransaction: async (operation: () => Promise | T) => { + events.push("ownership-transaction-start"); + const result = await operation(); + events.push("ownership-transaction-end"); + return result; + }, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute, verifyOnboardInferenceSmoke, @@ -678,6 +714,10 @@ describe("native NVIDIA onboarding", () => { }, }), ); + expect(events.indexOf("route-published")).toBeLessThan(events.indexOf("unload")); + expect(events[0]).toBe("ownership-transaction-start"); + expect(events.at(-1)).toBe("ownership-transaction-end"); + expect(unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("onboarding-gateway", { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index fc5496f7dd4..55e52c0d4ef 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -1519,24 +1519,36 @@ export function createSetupInference( } catch { /* An unreadable registry skips GPU release; it must not fail onboarding. */ } - const result = await mutateGatewayRoute(); - releaseSupersededOllamaModel( - previousSandbox, - provider, - model, - endpointUrl, - result, - deps, - revalidateSandboxIdentity, - ); - if (shouldLogSuccessfulRoute && "ok" in result) { - deps.log( - isNativeNvidiaProvider(provider) - ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` - : ` ✓ Inference route set: ${provider} / ${model}`, + // Compatible endpoints can own the same host Ollama daemon as direct Ollama routes. + // Serialize publication with release decisions across gateways to prevent a newly + // published peer route from being missed by concurrent cleanup (#12677). + const participatesInOllamaOwnership = + (previousSandbox !== null && isLocalOllamaRouteOwner(previousSandbox)) || + isLocalOllamaRouteOwner({ provider, endpointUrl }); + const runRouteAndRelease = async (): Promise => { + const result = await mutateGatewayRoute(); + releaseSupersededOllamaModel( + previousSandbox, + provider, + model, + endpointUrl, + result, + deps, + revalidateSandboxIdentity, ); - } - return result; + if (shouldLogSuccessfulRoute && "ok" in result) { + deps.log( + isNativeNvidiaProvider(provider) + ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` + : ` ✓ Inference route set: ${provider} / ${model}`, + ); + } + return result; + }; + if (!participatesInOllamaOwnership) return runRouteAndRelease(); + const withOwnershipTransaction = + deps.withOllamaModelOwnershipTransaction ?? withOllamaModelOwnershipTransaction; + return withOwnershipTransaction(runRouteAndRelease); }; return sandboxName ? deps.withSandboxMutationLock(sandboxName, mutateGatewayRouteAndReleaseSupersededModel) diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 007ac2f0cf7..ddb9fe6fa12 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -3,6 +3,7 @@ import fs from "node:fs"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { OllamaModelHolder } from "../../src/lib/inference/ollama/model-ownership.js"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { createDirectCommandRouter, @@ -226,4 +227,160 @@ describe("onboarding inference gateway scope", () => { }, ); }); + + it("serializes cross-gateway compatible Ollama peer publication before cleanup (#12677)", async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "test-compatible-api-key" }, async () => { + const events: string[] = []; + const registry = new Map([ + [ + "alpha", + { + name: "alpha", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434/v1", + gatewayName: "gateway-alpha", + }, + ], + [ + "beta", + { + name: "beta", + provider: "compatible-endpoint", + model: "previous-model", + endpointUrl: "https://previous.example/v1", + gatewayName: "gateway-beta", + }, + ], + ]); + let signalBetaRouteStarted!: () => void; + let releaseBetaRoute!: () => void; + let signalAlphaQueued!: () => void; + const betaRouteStarted = new Promise((resolve) => { + signalBetaRouteStarted = resolve; + }); + const allowBetaRouteToFinish = new Promise((resolve) => { + releaseBetaRoute = resolve; + }); + const alphaQueuedForTransaction = new Promise((resolve) => { + signalAlphaQueued = resolve; + }); + let transactionTail = Promise.resolve(); + let transactionCalls = 0; + const withOwnershipTransaction: NonNullable< + SetupInferenceDeps["withOllamaModelOwnershipTransaction"] + > = async (operation: () => Promise | T): Promise => { + transactionCalls += 1; + [() => undefined, signalAlphaQueued][transactionCalls - 1]?.(); + const previous = transactionTail; + let release!: () => void; + transactionTail = new Promise((resolve) => { + release = resolve; + }); + await previous; + try { + return await operation(); + } finally { + release(); + } + }; + const waitBeforeRouteMutation: Record Promise> = { + "gateway-beta": async () => { + signalBetaRouteStarted(); + await allowBetaRouteToFinish; + }, + }; + const inferenceRouteMutator: SetupInferenceDeps["inferenceRouteMutator"] = { + setInferenceRoute: async (request) => { + const gateway = request.target.gatewayName; + events.push(`route-start:${gateway}`); + await (waitBeforeRouteMutation[gateway] ?? (() => Promise.resolve()))(); + events.push(`route-finished:${gateway}`); + return { ok: true }; + }, + }; + const updateSandbox: SetupInferenceDeps["updateSandbox"] = (name, route) => { + const previous = registry.get(name); + registry.set(name, { ...previous, ...route, name } as OllamaModelHolder); + events.push(`registry-published:${name}`); + return true; + }; + const unloadOllamaModels = vi.fn(() => ({ + ok: true as const, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + })); + const overrides: Partial = { + inferenceRouteMutator, + updateSandbox, + getSandbox: (name) => registry.get(name) ?? null, + listOllamaModelOwnershipPeers: () => [...registry.values()], + discoverActiveOllamaSandboxNames: (owners) => ({ + ok: true, + activeSandboxNames: new Set(owners.map((owner) => owner.name)), + gatewayChecks: [], + }), + localInference: { + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + persistPendingOllamaModelCleanup: vi.fn(), + clearPendingOllamaModelCleanup: vi.fn(), + clearPersistedOllamaHostIfUnused: vi.fn(), + } as unknown as SetupInferenceDeps["localInference"], + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + withOllamaModelOwnershipTransaction: withOwnershipTransaction, + }; + const makeHarness = () => + createHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" ? { status: 1 } : undefined, + overrides, + }); + const alpha = makeHarness(); + const beta = makeHarness(); + const betaSwitch = beta.setupInference( + "beta", + "qwen2.5:1.5b", + "compatible-endpoint", + "http://127.0.0.1:11434/v1", + "COMPATIBLE_API_KEY", + null, + [], + { + gatewayName: "gateway-beta", + endpointPinnedAddresses: ["127.0.0.1"], + skipHostInferenceSmoke: true, + }, + ); + + await betaRouteStarted; + const alphaSwitch = alpha.setupInference( + "alpha", + "other-model", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { gatewayName: "gateway-alpha", skipHostInferenceSmoke: true }, + ); + await alphaQueuedForTransaction; + expect(events).not.toContain("route-start:gateway-alpha"); + + releaseBetaRoute(); + await expect(Promise.all([alphaSwitch, betaSwitch])).resolves.toEqual([ + { ok: true }, + { ok: true }, + ]); + + expect(events.indexOf("registry-published:beta")).toBeLessThan( + events.indexOf("route-start:gateway-alpha"), + ); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + }); + }, 20_000); }); From 90c5240311fda5142f358fe557d0a65f6f0be09d Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 06:46:11 +0000 Subject: [PATCH 09/44] docs(inference): clarify Ollama retry failures Signed-off-by: Yimo Jiang --- docs/inference/set-up-ollama.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 9f2e4d0c229..6fd87cb1bbb 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -407,9 +407,9 @@ Stopped or incomplete sibling registry rows do not retain the model. If NemoClaw cannot verify sibling state, it does not unload the model and `stop` exits nonzero. When you re-onboard an Ollama-backed sandbox from the host Ollama route to a different model or provider, NemoClaw checks live ownership before releasing its previous model. If another active sandbox uses the same local Ollama model, NemoClaw keeps it loaded. -If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model, records it for retry, and leaves the new route active. +If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model loaded and attempts to record cleanup for retry while leaving the new route active. If it reports that retry state could not be recorded, keep the model loaded and restore gateway access before retrying; do not unload it while ownership remains unverified. If the new route uses the same model through the same local daemon, NemoClaw keeps the model loaded. -If the unload cleanup fails, the new route remains active and NemoClaw keeps the model recorded for cleanup retry; rerun onboarding or run `$$nemoclaw destroy` to retry the recorded cleanup. +If the unload cleanup fails, the new route remains active and NemoClaw attempts to record the model for cleanup retry. Rerun onboarding or run `$$nemoclaw destroy` to retry it; if the warning says the retry state could not be recorded, use its reported manual-release guidance instead. This cleanup is best-effort and does not delete downloaded model files. ## Related Topics From e31627b3cb38be199f76bfee866ce56540d440aa Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 07:48:15 +0000 Subject: [PATCH 10/44] test(onboard): cover concurrent Ollama ownership transitions Signed-off-by: Yimo Jiang --- src/lib/onboard/setup-inference.test.ts | 222 ++++++++++++++++++++++++ 1 file changed, 222 insertions(+) diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index d5383aa22f2..5cd91057955 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -942,3 +942,225 @@ describe("native NVIDIA onboarding", () => { expect(updateSandbox).not.toHaveBeenCalled(); }); }); + +describe("concurrent Ollama ownership transactions", () => { + it("serializes route publication before superseded-model release (#12677)", async () => { + const events: string[] = []; + const registry = new Map([ + [ + "alpha", + { + name: "alpha", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434/v1", + gatewayName: "gateway-alpha", + }, + ], + [ + "beta", + { + name: "beta", + provider: "compatible-endpoint", + model: "previous-model", + endpointUrl: "https://previous.example/v1", + gatewayName: "gateway-beta", + }, + ], + ]); + let signalBetaRouteStarted!: () => void; + let signalAlphaRouteStarted!: () => void; + let releaseBetaRoute!: () => void; + let signalAlphaQueued!: () => void; + const betaRouteStarted = new Promise((resolve) => { + signalBetaRouteStarted = resolve; + }); + const alphaRouteStarted = new Promise((resolve) => { + signalAlphaRouteStarted = resolve; + }); + const allowBetaRouteToFinish = new Promise((resolve) => { + releaseBetaRoute = resolve; + }); + const alphaQueuedForTransaction = new Promise((resolve) => { + signalAlphaQueued = resolve; + }); + const transactionLabels = ["gateway-beta", "gateway-alpha"]; + let transactionTail = Promise.resolve(); + let transactionCalls = 0; + const withOwnershipTransaction: NonNullable< + SetupInferenceDeps["withOllamaModelOwnershipTransaction"] + > = async (operation: () => Promise | T): Promise => { + transactionCalls += 1; + const label = transactionLabels[transactionCalls - 1] ?? "unknown"; + events.push(`transaction-request:${label}`); + [() => undefined, signalAlphaQueued][transactionCalls - 1]?.(); + const previous = transactionTail; + let release!: () => void; + transactionTail = new Promise((resolve) => { + release = resolve; + }); + await previous; + events.push(`transaction-enter:${label}`); + try { + const result = await operation(); + events.push(`transaction-exit:${label}`); + return result; + } finally { + release(); + } + }; + const signalRouteStarted: Record void> = { + "gateway-alpha": signalAlphaRouteStarted, + "gateway-beta": signalBetaRouteStarted, + }; + const inferenceRouteMutator: SetupInferenceDeps["inferenceRouteMutator"] = { + setInferenceRoute: async (request) => { + const gateway = request.target.gatewayName; + events.push(`route-start:${gateway}`); + signalRouteStarted[gateway]?.(); + await (gateway === "gateway-beta" ? allowBetaRouteToFinish : Promise.resolve()); + events.push(`route-finished:${gateway}`); + return { ok: true }; + }, + }; + const updateSandbox: SetupInferenceDeps["updateSandbox"] = (name, route) => { + const previous = registry.get(name); + registry.set(name, { ...previous, ...route, name } as OllamaModelHolder); + events.push(`registry-published:${name}`); + return true; + }; + const listOllamaModelOwnershipPeers = vi.fn(() => { + events.push("peer-discovery"); + return [...registry.values()]; + }); + const unloadOllamaModels = vi.fn(() => { + events.push("unload"); + return { + ok: true as const, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }; + }); + const localInference = { + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + persistPendingOllamaModelCleanup: vi.fn(), + clearPendingOllamaModelCleanup: vi.fn(), + clearPersistedOllamaHostIfUnused: vi.fn(), + }; + const deps = { + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "gateway-default", + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + inferenceRouteMutator, + inferenceRouteObserver: { + observeInferenceRoute: vi.fn(async () => ({ ok: true as const })), + } as unknown as SetupInferenceDeps["inferenceRouteObserver"], + updateSandbox, + getSandbox: (name: string) => registry.get(name) ?? null, + listOllamaModelOwnershipPeers, + discoverActiveOllamaSandboxNames: (owners: readonly OllamaModelHolder[]) => ({ + ok: true as const, + activeSandboxNames: new Set(owners.map((owner) => owner.name)), + gatewayChecks: [], + }), + localInference, + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + withOllamaModelOwnershipTransaction: withOwnershipTransaction, + upsertProvider: vi.fn(async () => ({ ok: true as const })), + bedrockRuntimeOnboard: { + setupBedrockRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + openrouterRuntimeOnboard: { + setupOpenRouterRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + isNonInteractive: () => true, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + hydrateCredentialEnv: vi.fn(() => "test-compatible-api-key"), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + localInferenceTimeoutSecs: 30, + vllmLocalCredentialEnv: "VLLM_API_KEY", + ollamaProxyCredentialEnv: "NEMOCLAW_OLLAMA_PROXY_TOKEN", + isRoutedInferenceProvider: () => false, + } as unknown as SetupInferenceDeps; + const setupAlpha = createSetupInference(deps); + const setupBeta = createSetupInference(deps); + const betaSwitch = setupBeta( + "beta", + "qwen2.5:1.5b", + "compatible-endpoint", + "http://127.0.0.1:11434/v1", + "COMPATIBLE_API_KEY", + null, + [], + { + gatewayName: "gateway-beta", + endpointPinnedAddresses: ["127.0.0.1"], + skipHostInferenceSmoke: true, + }, + ); + + await betaRouteStarted; + const alphaSwitch = setupAlpha( + "alpha", + "other-model", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { + gatewayName: "gateway-alpha", + endpointPinnedAddresses: ["93.184.216.34"], + skipHostInferenceSmoke: true, + }, + ); + const alphaOrder = await Promise.race([ + alphaQueuedForTransaction.then(() => "queued"), + alphaRouteStarted.then(() => "route-started"), + ]); + releaseBetaRoute(); + await expect(Promise.all([alphaSwitch, betaSwitch])).resolves.toEqual([ + { ok: true }, + { ok: true }, + ]); + + expect(alphaOrder).toBe("queued"); + expect(events).toContain("registry-published:beta"); + expect(events).toContain("route-start:gateway-alpha"); + expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( + events.indexOf("route-start:gateway-alpha"), + ); + expect(events.indexOf("registry-published:beta")).toBeLessThan( + events.indexOf("route-start:gateway-alpha"), + ); + expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( + events.indexOf("peer-discovery"), + ); + expect(events.indexOf("registry-published:alpha")).toBeLessThan( + events.indexOf("peer-discovery"), + ); + expect(events.indexOf("peer-discovery")).toBeLessThan( + events.indexOf("transaction-exit:gateway-alpha"), + ); + expect(listOllamaModelOwnershipPeers).toHaveBeenCalledOnce(); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + }, 20_000); +}); From a387aba58ec3f29b2e95a083879564b3ddbb20be Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 09:20:26 +0000 Subject: [PATCH 11/44] fix(ollama): scope cleanup retries to sandbox lifecycle (#12677) Signed-off-by: Yimo Jiang --- ci/e2e-assertion-budget.json | 14 +- docs/reference/commands.mdx | 2 +- src/lib/actions/sandbox/destroy.ts | 31 ++-- .../inference/ollama/model-ownership.test.ts | 117 ++++++++++-- src/lib/inference/ollama/model-ownership.ts | 172 +++++++++++++++--- src/lib/onboard/inference-providers/types.ts | 13 +- src/lib/onboard/setup-inference.test.ts | 101 ++++++++-- src/lib/onboard/setup-inference.ts | 51 +++--- src/lib/tunnel/services.test.ts | 13 +- src/lib/tunnel/services.ts | 13 +- test/e2e/live/gpu-double-onboard.test.ts | 106 ++++++++--- test/e2e/mock-parity.json | 6 +- .../onboard-inference-reconciliation.test.ts | 15 +- .../destroy-cleanup-sandbox-services.test.ts | 30 ++- 14 files changed, 541 insertions(+), 143 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 56136d2d56e..4f50075b217 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1250, - "matcherAssertions": 1229, + "expectCalls": 1249, + "matcherAssertions": 1228, "nodeAssertions": 104, "namedAssertionHelpers": 418, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 168, - "assertionPoints": 1969, + "assertionPoints": 1968, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1673, - "matcherAssertions": 1647, + "expectCalls": 1672, + "matcherAssertions": 1646, "nodeAssertions": 127, "namedAssertionHelpers": 663, "failCalls": 1, "throwGuards": 528, "objectFieldAssertions": 245, - "assertionPoints": 3211, + "assertionPoints": 3210, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -63,7 +63,7 @@ "test/e2e/live/double-onboard.test.ts": [42,47,42,47,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], - "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], + "test/e2e/live/gpu-double-onboard.test.ts": [20,23,20,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [10,22,17,61,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index a2518f6d874..412e86e84d9 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2085,7 +2085,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` ### `$$nemoclaw destroy` -Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. This removes the sandbox from the registry. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. For Ollama-backed sandboxes, `destroy` best-effort unloads only that sandbox's current Ollama model and any models recorded for a cleanup retry. It preserves a model still used by an active matching sandbox, and clears stale auth proxy state on a best-effort basis. +Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. After confirmed deletion, `destroy` removes the sandbox from the registry only when required cleanup and ownership checks succeed. If Ollama cleanup or ownership verification fails, it retains the registry entry; follow the reported recovery action and retry `destroy`. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. For Ollama-backed sandboxes, `destroy` best-effort unloads only that sandbox's current Ollama model and any models recorded for a cleanup retry. It preserves a model still used by an active matching sandbox, and clears stale auth proxy state on a best-effort basis. `destroy` considers retirement of the host-global `nemoclaw-vllm` container for a sandbox with provider `vllm-local`, including Local NIM. It requires confirmed sandbox deletion and no remaining registered `vllm-local` consumer in any gateway state root. diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 4027df17cda..b8efd013ca7 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -35,6 +35,7 @@ import { type OllamaUnloadResult, withOllamaModelOwnershipTransaction, } from "../../inference/ollama/proxy"; +import type { OllamaModelCleanupOwner } from "../../inference/ollama/model-ownership"; import { CURRENT_RUNTIME_PROVIDER_BUNDLES, normalizeRuntimeProviderIdentity, @@ -232,9 +233,9 @@ export type CleanupSandboxServicesDeps = { deps?: { recoverySandboxName?: string }, ) => boolean; unloadOllamaModels?: (onlyModels?: readonly string[]) => OllamaUnloadResult | void; - loadPendingOllamaModelCleanup?: (sandboxName: string) => readonly string[]; + loadPendingOllamaModelCleanup?: (owner: OllamaModelCleanupOwner) => readonly string[]; clearPendingOllamaModelCleanup?: ( - sandboxName: string, + owner: OllamaModelCleanupOwner, releasedModels?: readonly string[], ) => void; loadPersistedOllamaHost?: () => "127.0.0.1" | "host.docker.internal" | null; @@ -312,10 +313,12 @@ export async function cleanupSandboxServices( stopHostServices = false, channelStopTransport, gatewayPort, + sandboxSnapshot, }: { stopHostServices?: boolean; channelStopTransport?: RuntimeProviderChannelStopTransport; gatewayPort?: number; + sandboxSnapshot?: registry.SandboxEntry | null; } = {}, deps: CleanupSandboxServicesDeps = {}, ): Promise { @@ -358,19 +361,22 @@ export async function cleanupSandboxServices( }); const loadPendingOllamaModelCleanup = deps.loadPendingOllamaModelCleanup ?? - ((name: string) => { + ((owner: OllamaModelCleanupOwner) => { const local = require("../../inference/ollama/proxy") as { - loadPendingOllamaModelCleanup(sandboxName: string): readonly string[]; + loadPendingOllamaModelCleanup(owner: OllamaModelCleanupOwner): readonly string[]; }; - return local.loadPendingOllamaModelCleanup(name); + return local.loadPendingOllamaModelCleanup(owner); }); const clearPendingOllamaModelCleanup = deps.clearPendingOllamaModelCleanup ?? - ((name: string, releasedModels?: readonly string[]) => { + ((owner: OllamaModelCleanupOwner, releasedModels?: readonly string[]) => { const local = require("../../inference/ollama/proxy") as { - clearPendingOllamaModelCleanup(sandboxName: string, models?: readonly string[]): void; + clearPendingOllamaModelCleanup( + owner: OllamaModelCleanupOwner, + models?: readonly string[], + ): void; }; - local.clearPendingOllamaModelCleanup(name, releasedModels); + local.clearPendingOllamaModelCleanup(owner, releasedModels); }); const loadPersistedOllamaHost = deps.loadPersistedOllamaHost ?? @@ -459,9 +465,9 @@ export async function cleanupSandboxServices( let ollamaCleanup: OllamaUnloadResult | void = undefined; const cleanupScopedOllamaModels = () => { - const sb = getSandbox(validatedSandboxName); + const sb = sandboxSnapshot !== undefined ? sandboxSnapshot : getSandbox(validatedSandboxName); const selectedHost = loadPersistedOllamaHost(); - const pending = loadPendingOllamaModelCleanup(validatedSandboxName); + const pending = sb ? loadPendingOllamaModelCleanup(sb) : []; const currentModel = String(sb?.model ?? "").trim(); const candidates = [ ...pending, @@ -514,8 +520,8 @@ export async function cleanupSandboxServices( } if (releasable.length === 0) return; ollamaCleanup = unloadOllamaModels(releasable); - if (!ollamaCleanup || ollamaCleanup.ok) { - clearPendingOllamaModelCleanup(validatedSandboxName, releasable); + if ((!ollamaCleanup || ollamaCleanup.ok) && sb) { + clearPendingOllamaModelCleanup(sb, releasable); } }; @@ -1219,6 +1225,7 @@ async function destroySandboxUnlocked( ? (retainedRecoveryAuthority?.gatewayPort ?? registryAuthority.gatewayPort) : registryAuthority.gatewayPort, stopHostServices: shouldStopHostServices, + sandboxSnapshot: sandbox, ...(destroyChannelStopTransport ? { channelStopTransport: destroyChannelStopTransport } : {}), diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 7fbdb42bf99..00ad0d30f6a 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { mkdtempSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { clearPendingOllamaModelCleanup, @@ -12,6 +12,7 @@ import { discoverOllamaModelOwnership, loadPendingOllamaModelCleanup, type OllamaHostRoute, + type OllamaModelCleanupOwner, type OllamaModelHolder, type OllamaModelRoute, persistPendingOllamaModelCleanup, @@ -23,6 +24,17 @@ function holder(overrides: Partial = {}): OllamaModelHolder { return { name: "test-box", provider: "ollama-local", model: "llama3", ...overrides }; } +function cleanupOwner(overrides: Partial = {}): OllamaModelCleanupOwner { + return { + name: "test-box", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-a", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + ...overrides, + }; +} + function route(model: string, overrides: Partial = {}): OllamaModelRoute { return { provider: "ollama-local", model, ...overrides }; } @@ -321,27 +333,106 @@ describe("decideOllamaModelOwnership", () => { }); describe("pending Ollama model cleanup", () => { - it("persists exact sandbox-scoped models until verified release", () => { + it("persists models until verified release for the exact sandbox lifecycle", () => { const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); + const owner = cleanupOwner(); try { - persistPendingOllamaModelCleanup("test-box", ["llama3", "llama3:latest"], stateRoot); - persistPendingOllamaModelCleanup("test-box", ["qwen3.5:9b"], stateRoot); + persistPendingOllamaModelCleanup(owner, ["llama3", "llama3:latest"], stateRoot); + persistPendingOllamaModelCleanup(owner, ["qwen3.5:9b"], stateRoot); + + expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual(["llama3", "qwen3.5:9b"]); + clearPendingOllamaModelCleanup(owner, ["llama3:latest"], stateRoot); + expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual(["qwen3.5:9b"]); + clearPendingOllamaModelCleanup(owner, undefined, stateRoot); + expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual([]); + } finally { + rmSync(stateRoot, { recursive: true, force: true }); + } + }); - expect(loadPendingOllamaModelCleanup("test-box", stateRoot)).toEqual([ - "llama3", - "qwen3.5:9b", + it("isolates same-named cleanup receipts across gateways and lifecycle generations", () => { + const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); + const gatewayOwner = cleanupOwner(); + const otherGatewayOwner = cleanupOwner({ + gatewayName: "nemoclaw-32678", + gatewayPort: 32678, + lifecycleGeneration: "generation-b", + lifecycleLiveIdentityFingerprint: "b".repeat(64), + }); + const recreatedOwner = cleanupOwner({ + lifecycleGeneration: "generation-c", + lifecycleLiveIdentityFingerprint: "c".repeat(64), + }); + try { + persistPendingOllamaModelCleanup(gatewayOwner, ["gateway-a-model"], stateRoot); + persistPendingOllamaModelCleanup(otherGatewayOwner, ["gateway-b-model"], stateRoot); + persistPendingOllamaModelCleanup(recreatedOwner, ["recreated-model"], stateRoot); + + expect(loadPendingOllamaModelCleanup(gatewayOwner, stateRoot)).toEqual(["gateway-a-model"]); + expect(loadPendingOllamaModelCleanup(otherGatewayOwner, stateRoot)).toEqual([ + "gateway-b-model", + ]); + expect(loadPendingOllamaModelCleanup(recreatedOwner, stateRoot)).toEqual(["recreated-model"]); + + clearPendingOllamaModelCleanup(gatewayOwner, undefined, stateRoot); + expect(loadPendingOllamaModelCleanup(gatewayOwner, stateRoot)).toEqual([]); + expect(loadPendingOllamaModelCleanup(otherGatewayOwner, stateRoot)).toEqual([ + "gateway-b-model", ]); - clearPendingOllamaModelCleanup("test-box", ["llama3:latest"], stateRoot); - expect(loadPendingOllamaModelCleanup("test-box", stateRoot)).toEqual(["qwen3.5:9b"]); - clearPendingOllamaModelCleanup("test-box", undefined, stateRoot); - expect(loadPendingOllamaModelCleanup("test-box", stateRoot)).toEqual([]); + expect(loadPendingOllamaModelCleanup(recreatedOwner, stateRoot)).toEqual(["recreated-model"]); + } finally { + rmSync(stateRoot, { recursive: true, force: true }); + } + }); + + it("does not replay or clear a legacy receipt without gateway and lifecycle identity", () => { + const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); + const owner = cleanupOwner(); + const legacyPath = join(stateRoot, "ollama-pending-model-cleanup", `${owner.name}.json`); + mkdirSync(join(stateRoot, "ollama-pending-model-cleanup"), { recursive: true, mode: 0o700 }); + writeFileSync( + legacyPath, + JSON.stringify({ schemaVersion: 1, sandboxName: owner.name, models: ["llama3"] }), + { mode: 0o600 }, + ); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual([]); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("has no gateway/lifecycle identity"), + ); + + clearPendingOllamaModelCleanup(owner, undefined, stateRoot); + expect(existsSync(legacyPath)).toBe(true); + } finally { + warning.mockRestore(); + rmSync(stateRoot, { recursive: true, force: true }); + } + }); + + it("fails closed when cleanup receipt lifecycle identity is incomplete", () => { + const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); + const owner = cleanupOwner(); + const incompleteOwner = cleanupOwner({ + lifecycleGeneration: undefined, + lifecycleLiveIdentityFingerprint: undefined, + }); + try { + persistPendingOllamaModelCleanup(owner, ["llama3"], stateRoot); + + expect(loadPendingOllamaModelCleanup(incompleteOwner, stateRoot)).toEqual([]); + clearPendingOllamaModelCleanup(incompleteOwner, undefined, stateRoot); + expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual(["llama3"]); + expect(() => persistPendingOllamaModelCleanup(incompleteOwner, ["qwen3"], stateRoot)).toThrow( + "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", + ); } finally { rmSync(stateRoot, { recursive: true, force: true }); } }); it("rejects an unsafe sandbox name before state access", () => { - expect(() => loadPendingOllamaModelCleanup("../peer")).toThrow( + expect(() => loadPendingOllamaModelCleanup(cleanupOwner({ name: "../peer" }))).toThrow( "Invalid sandbox name for pending Ollama cleanup", ); }); diff --git a/src/lib/inference/ollama/model-ownership.ts b/src/lib/inference/ollama/model-ownership.ts index fb962fd8682..bbfa39c581d 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { createHash } from "node:crypto"; import path from "node:path"; import { listInferenceRouteOwnersAcrossGatewayRoots } from "../../state/registry/cross-port"; @@ -21,11 +22,80 @@ export type { OllamaHostRoute, OllamaRouteHolder } from "../local-adapter-lifecy const PENDING_CLEANUP_DIRECTORY = "ollama-pending-model-cleanup"; const SAFE_SANDBOX_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u; +const SANDBOX_IDENTITY_FINGERPRINT = /^[a-f0-9]{64}$/u; -function pendingCleanupPath(sandboxName: string, stateRoot: string): string { - if (!SAFE_SANDBOX_NAME.test(sandboxName)) { - throw new Error(`Invalid sandbox name for pending Ollama cleanup: ${sandboxName}`); +type PendingCleanupOwner = { + readonly sandboxName: string; + readonly gatewayName: string; + readonly gatewayPort: number; + readonly lifecycleGeneration: string; + readonly lifecycleLiveIdentityFingerprint: string; +}; + +/** Durable identity required to read or mutate pending cleanup receipts. */ +export type OllamaModelCleanupOwner = Pick< + SandboxEntry, + | "name" + | "gatewayName" + | "gatewayPort" + | "lifecycleGeneration" + | "lifecycleLiveIdentityFingerprint" +>; + +/** The registry fields an Ollama GPU-release decision reads. */ +export type OllamaModelHolder = Pick< + SandboxEntry, + | "name" + | "provider" + | "model" + | "endpointUrl" + | "gatewayName" + | "gatewayPort" + | "lifecycleGeneration" + | "lifecycleLiveIdentityFingerprint" +>; + +function pendingCleanupOwner(owner: OllamaModelCleanupOwner): PendingCleanupOwner | null { + if (!owner || typeof owner.name !== "string" || !SAFE_SANDBOX_NAME.test(owner.name)) { + throw new Error(`Invalid sandbox name for pending Ollama cleanup: ${String(owner?.name)}`); + } + const gatewayName = typeof owner.gatewayName === "string" ? owner.gatewayName.trim() : ""; + const gatewayPort = owner.gatewayPort; + const lifecycleGeneration = + typeof owner.lifecycleGeneration === "string" ? owner.lifecycleGeneration.trim() : ""; + const lifecycleLiveIdentityFingerprint = + typeof owner.lifecycleLiveIdentityFingerprint === "string" + ? owner.lifecycleLiveIdentityFingerprint.trim() + : ""; + if ( + !gatewayName || + !Number.isInteger(gatewayPort) || + gatewayPort === null || + gatewayPort === undefined || + gatewayPort < 1 || + gatewayPort > 65_535 || + !lifecycleGeneration || + lifecycleGeneration.length > 256 || + !lifecycleLiveIdentityFingerprint || + !SANDBOX_IDENTITY_FINGERPRINT.test(lifecycleLiveIdentityFingerprint) + ) { + return null; } + return { + sandboxName: owner.name, + gatewayName, + gatewayPort, + lifecycleGeneration, + lifecycleLiveIdentityFingerprint, + }; +} + +function pendingCleanupPath(owner: PendingCleanupOwner, stateRoot: string): string { + const identity = createHash("sha256").update(JSON.stringify(owner)).digest("hex"); + return path.join(stateRoot, PENDING_CLEANUP_DIRECTORY, `${identity}.json`); +} + +function legacyPendingCleanupPath(sandboxName: string, stateRoot: string): string { return path.join(stateRoot, PENDING_CLEANUP_DIRECTORY, `${sandboxName}.json`); } @@ -39,22 +109,70 @@ function validPendingModel(value: unknown): value is string { ); } +function pendingRecordMatchesOwner( + record: Record | null, + owner: PendingCleanupOwner, +): record is Record & { models: unknown[] } { + const recordedOwner = record?.owner; + return ( + record?.schemaVersion === 2 && + record.sandboxName === owner.sandboxName && + typeof recordedOwner === "object" && + recordedOwner !== null && + !Array.isArray(recordedOwner) && + (recordedOwner as PendingCleanupOwner).sandboxName === owner.sandboxName && + (recordedOwner as PendingCleanupOwner).gatewayName === owner.gatewayName && + (recordedOwner as PendingCleanupOwner).gatewayPort === owner.gatewayPort && + (recordedOwner as PendingCleanupOwner).lifecycleGeneration === owner.lifecycleGeneration && + (recordedOwner as PendingCleanupOwner).lifecycleLiveIdentityFingerprint === + owner.lifecycleLiveIdentityFingerprint && + Array.isArray(record.models) + ); +} + export function loadPendingOllamaModelCleanup( - sandboxName: string, + owner: OllamaModelCleanupOwner, stateRoot: string = resolveSharedLocalAdapterStateRoot(), ): readonly string[] { - const record = readLocalAdapterJsonFile(pendingCleanupPath(sandboxName, stateRoot)); - return record?.schemaVersion === 1 && Array.isArray(record.models) - ? record.models.filter(validPendingModel) - : []; + const identity = pendingCleanupOwner(owner); + const legacyRecord = readLocalAdapterJsonFile(legacyPendingCleanupPath(owner.name, stateRoot)); + const legacyModels = + legacyRecord?.schemaVersion === 1 && + legacyRecord.sandboxName === owner.name && + Array.isArray(legacyRecord.models) + ? legacyRecord.models.filter(validPendingModel) + : []; + if (legacyModels.length > 0) { + console.warn( + ` Warning: legacy pending Ollama cleanup for '${owner.name}' (${legacyModels.join(", ")}) has no gateway/lifecycle identity. NemoClaw left it untouched; verify active owners before manually releasing any listed model.`, + ); + } + if (!identity) return []; + const record = readLocalAdapterJsonFile(pendingCleanupPath(identity, stateRoot)); + return pendingRecordMatchesOwner(record, identity) ? record.models.filter(validPendingModel) : []; } export function persistPendingOllamaModelCleanup( - sandboxName: string, + owner: OllamaModelCleanupOwner, models: readonly string[], stateRoot: string = resolveSharedLocalAdapterStateRoot(), ): void { - const pending = [...loadPendingOllamaModelCleanup(sandboxName, stateRoot)]; + const identity = pendingCleanupOwner(owner); + if (!identity) { + throw new Error( + "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", + ); + } + const receiptPath = pendingCleanupPath(identity, stateRoot); + const record = readLocalAdapterJsonFile(receiptPath); + if (record && !pendingRecordMatchesOwner(record, identity)) { + throw new Error( + "Refusing to replace a pending Ollama cleanup receipt with a different owner identity", + ); + } + const pending = pendingRecordMatchesOwner(record, identity) + ? [...record.models.filter(validPendingModel)] + : []; for (const model of models) { const normalized = model.trim(); if (!validPendingModel(normalized)) continue; @@ -63,43 +181,45 @@ export function persistPendingOllamaModelCleanup( } } if (pending.length === 0) return; - writeLocalAdapterJsonFile(pendingCleanupPath(sandboxName, stateRoot), { - schemaVersion: 1, - sandboxName, + writeLocalAdapterJsonFile(receiptPath, { + schemaVersion: 2, + sandboxName: identity.sandboxName, + owner: identity, models: pending, }); } export function clearPendingOllamaModelCleanup( - sandboxName: string, + owner: OllamaModelCleanupOwner, releasedModels?: readonly string[], stateRoot: string = resolveSharedLocalAdapterStateRoot(), ): void { - const receiptPath = pendingCleanupPath(sandboxName, stateRoot); + const identity = pendingCleanupOwner(owner); + if (!identity) return; + const receiptPath = pendingCleanupPath(identity, stateRoot); + const record = readLocalAdapterJsonFile(receiptPath); + if (!pendingRecordMatchesOwner(record, identity)) return; if (!releasedModels) { removeLocalAdapterFile(receiptPath); return; } - const remaining = loadPendingOllamaModelCleanup(sandboxName, stateRoot).filter( - (pending) => !releasedModels.some((released) => ollamaModelRefsMatch(pending, released)), - ); + const remaining = record.models + .filter(validPendingModel) + .filter( + (pending) => !releasedModels.some((released) => ollamaModelRefsMatch(pending, released)), + ); if (remaining.length === 0) { removeLocalAdapterFile(receiptPath); return; } writeLocalAdapterJsonFile(receiptPath, { - schemaVersion: 1, - sandboxName, + schemaVersion: 2, + sandboxName: identity.sandboxName, + owner: identity, models: remaining, }); } -/** The registry fields an Ollama GPU-release decision reads. */ -export type OllamaModelHolder = Pick< - SandboxEntry, - "name" | "provider" | "model" | "endpointUrl" | "gatewayName" | "gatewayPort" ->; - export type OllamaModelRoute = Pick; export type OllamaActiveOwnershipDiscovery = diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 3ab824a4ae0..c16a6661d0a 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -21,6 +21,7 @@ import type { TrustedPrivateEndpointCapability } from "../../inference/endpoint- import type { OpenShellInferenceRouteMutator } from "../../adapters/openshell/inference-route"; import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; import type { HermesAuthMethod } from "../hermes-auth"; +import type { OllamaModelCleanupOwner } from "../../inference/ollama/model-ownership"; import type { OnboardInferenceCapabilityCache } from "../inference-capability-cache"; export type SetupInferenceResult = @@ -284,9 +285,15 @@ export type OllamaDeps = CommonDeps & { ): { ok: boolean; message?: string }; validateSandboxFacingOllamaModel(model: string): { ok: boolean; message?: string }; runOllamaWarmup(model: string, runImpl: RunFn): void; - loadPendingOllamaModelCleanup?(sandboxName: string): readonly string[]; - persistPendingOllamaModelCleanup?(sandboxName: string, models: readonly string[]): void; - clearPendingOllamaModelCleanup?(sandboxName: string, releasedModels?: readonly string[]): void; + loadPendingOllamaModelCleanup?(owner: OllamaModelCleanupOwner): readonly string[]; + persistPendingOllamaModelCleanup?( + owner: OllamaModelCleanupOwner, + models: readonly string[], + ): void; + clearPendingOllamaModelCleanup?( + owner: OllamaModelCleanupOwner, + releasedModels?: readonly string[], + ): void; persistResolvedOllamaHost(): () => void; loadPersistedOllamaHost?(): "127.0.0.1" | "host.docker.internal" | null; clearPersistedOllamaHostIfUnused?( diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 5cd91057955..8974fdd9622 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -8,7 +8,10 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; -import type { OllamaModelHolder } from "../inference/ollama/model-ownership"; +import type { + OllamaModelCleanupOwner, + OllamaModelHolder, +} from "../inference/ollama/model-ownership"; import type { OllamaUnloadResult } from "../inference/ollama/proxy"; import type { SandboxEntry } from "../state/registry"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; @@ -39,13 +42,17 @@ function createOllamaCleanupHarness( let pendingModels = [...(options.pendingModels ?? [])]; const localInference = { loadPersistedOllamaHost: vi.fn(() => "127.0.0.1"), - loadPendingOllamaModelCleanup: vi.fn(() => pendingModels), - persistPendingOllamaModelCleanup: vi.fn((_name: string, models: readonly string[]) => { - pendingModels = [...new Set([...pendingModels, ...models])]; - }), - clearPendingOllamaModelCleanup: vi.fn((_name: string, models: readonly string[]) => { - pendingModels = pendingModels.filter((model) => !models.includes(model)); - }), + loadPendingOllamaModelCleanup: vi.fn((_owner: OllamaModelCleanupOwner) => pendingModels), + persistPendingOllamaModelCleanup: vi.fn( + (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { + pendingModels = [...new Set([...pendingModels, ...models])]; + }, + ), + clearPendingOllamaModelCleanup: vi.fn( + (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { + pendingModels = pendingModels.filter((model) => !models.includes(model)); + }, + ), clearPersistedOllamaHostIfUnused: vi.fn(), }; const unloadOllamaModels = vi.fn( @@ -84,6 +91,10 @@ const previousLocalOllamaRoute: OllamaModelHolder = { provider: "ollama-local", model: "qwen2.5:1.5b", endpointUrl: "http://127.0.0.1:11434", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-alpha", + lifecycleLiveIdentityFingerprint: "a".repeat(64), }; function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): void { @@ -140,9 +151,10 @@ describe("releaseSupersededOllamaModel", () => { expect(discovery.mock.calls[0]?.[0]).toEqual([]); expect(discovery.mock.calls[1]?.[0]).toEqual([unrelatedPeer]); expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith("alpha", [ - "qwen2.5:1.5b", - ]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); expect(warning).toHaveBeenCalledWith( expect.stringContaining("host route receipt was retained"), @@ -250,7 +262,14 @@ describe("releaseSupersededOllamaModel", () => { expect(runOpenshell).toHaveBeenCalledExactlyOnceWith( ["sandbox", "list", "-g", "nemoclaw-32665"], - expect.objectContaining({ suppressOutput: true }), + expect.objectContaining({ + env: process.env, + ignoreError: true, + maxBuffer: 1024 * 1024, + stdio: "pipe", + suppressOutput: true, + timeout: 10_000, + }), ); expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); @@ -295,7 +314,7 @@ describe("releaseSupersededOllamaModel", () => { expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - "alpha", + previousLocalOllamaRoute, ["qwen2.5:1.5b"], ); expect(runOpenshell).not.toHaveBeenCalled(); @@ -319,7 +338,7 @@ describe("releaseSupersededOllamaModel", () => { releaseToNvidia(previousLocalOllamaRoute, harness.deps); expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - "alpha", + previousLocalOllamaRoute, ["qwen2.5:1.5b"], ); expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); @@ -327,9 +346,52 @@ describe("releaseSupersededOllamaModel", () => { releaseToNvidia({ ...previousLocalOllamaRoute, provider: "nvidia-prod" }, harness.deps); expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith("alpha", [ - "qwen2.5:1.5b", - ]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + expect.objectContaining({ + name: "alpha", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-alpha", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + }), + ["qwen2.5:1.5b"], + ); + } finally { + warning.mockRestore(); + } + }); + + it("requires manual recovery when ownership failure cannot be recorded for retry", () => { + const discovery = vi.fn>( + () => ({ ok: false, message: "gateway unavailable" }), + ); + const harness = createOllamaCleanupHarness({ discovery }); + harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { + throw new Error( + "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", + ); + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia( + { + ...previousLocalOllamaRoute, + lifecycleGeneration: undefined, + lifecycleLiveIdentityFingerprint: undefined, + }, + harness.deps, + ); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining( + "Manually verify that no active matching sandbox owns the model before releasing only qwen2.5:1.5b", + ), + ); + expect(warning).not.toHaveBeenCalledWith( + expect.stringContaining("Re-run onboarding to retry only"), + ); } finally { warning.mockRestore(); } @@ -353,7 +415,7 @@ describe("releaseSupersededOllamaModel", () => { expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - "alpha", + previousLocalOllamaRoute, ["qwen2.5:1.5b"], ); expect(harness.localInference.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); @@ -1145,6 +1207,9 @@ describe("concurrent Ollama ownership transactions", () => { expect(alphaOrder).toBe("queued"); expect(events).toContain("registry-published:beta"); expect(events).toContain("route-start:gateway-alpha"); + expect(events).toContain("transaction-exit:gateway-beta"); + expect(events).toContain("transaction-exit:gateway-alpha"); + expect(events).toContain("peer-discovery"); expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( events.indexOf("route-start:gateway-alpha"), ); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 55e52c0d4ef..f713124e06b 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -46,6 +46,7 @@ import { matchingOllamaModelPeers, type OllamaActiveOwnershipDiscoveryFn, type OllamaModelHolder, + type OllamaOwnershipPhaseCapture, persistPendingOllamaModelCleanup, supersededOllamaModelWithActivePeers, } from "../inference/ollama/model-ownership"; @@ -250,6 +251,7 @@ export type SetupInferenceDeps = ProviderBranchDeps & { getSandbox?: typeof import("../state/registry").getSandbox; listOllamaModelOwnershipPeers?: () => readonly OllamaModelHolder[]; discoverActiveOllamaSandboxNames?: OllamaActiveOwnershipDiscoveryFn; + captureOllamaOwnershipPhases?: OllamaOwnershipPhaseCapture; resolveOllamaOwnershipGateway?: (peer: OllamaModelHolder) => string; environment?: NodeJS.ProcessEnv; listSandboxes?: typeof import("../state/registry").listSandboxes; @@ -556,7 +558,7 @@ export function releaseSupersededOllamaModel( const persistRetry = (): string | null => { if (attemptedModels.length === 0) return null; try { - persistPending(previous.name, attemptedModels); + persistPending(previous, attemptedModels); return null; } catch (error) { return (error instanceof Error ? error.message : String(error)) @@ -576,7 +578,7 @@ export function releaseSupersededOllamaModel( ? supersededOllamaModelWithActivePeers(previous, nextRoute, [], new Set(), selectedHost) : null; attemptedModels = retryCandidate ? [retryCandidate] : []; - const pending = loadPending(previous.name); + const pending = loadPending(previous); attemptedModels = [...new Set([...attemptedModels, ...pending])]; if (!retryCandidate && pending.length === 0) return; @@ -587,29 +589,28 @@ export function releaseSupersededOllamaModel( isLocalOllamaRouteOwner(peer, selectedHost), ); const environment = deps.environment ?? process.env; + const captureOwnershipPhases: OllamaOwnershipPhaseCapture = + deps.captureOllamaOwnershipPhases ?? + ((gatewayName, captureEnvironment) => { + const result = deps.runOpenshell(["sandbox", "list", "-g", gatewayName], { + env: captureEnvironment, + ignoreError: true, + maxBuffer: 1024 * 1024, + stdio: "pipe", + suppressOutput: true, + timeout: 10_000, + }); + return { + status: result.status, + output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), + }; + }); const discoverPeers = (owners: readonly OllamaModelHolder[]) => deps.discoverActiveOllamaSandboxNames ? deps.discoverActiveOllamaSandboxNames(owners, environment) - : discoverOllamaModelOwnership( - owners, - environment, - (gateway, env) => { - const result = deps.runOpenshell(["sandbox", "list", "-g", gateway], { - env, - ignoreError: true, - suppressOutput: true, - maxBuffer: 1024 * 1024, - timeout: 10_000, - }); - return { - status: result.status, - output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), - }; - }, - { - resolvePersistedSandboxOwnershipGateway: deps.resolveOllamaOwnershipGateway, - }, - ); + : discoverOllamaModelOwnership(owners, environment, captureOwnershipPhases, { + resolvePersistedSandboxOwnershipGateway: deps.resolveOllamaOwnershipGateway, + }); // A different model cannot keep one of the models being released resident. // Discover only matching owners before unloading so unrelated gateways do // not delay cleanup; all-route discovery is reserved for receipt retirement. @@ -628,7 +629,7 @@ export function releaseSupersededOllamaModel( if (!discovery.ok) { pendingRecordFailure = persistRetry(); const retryMessage = pendingRecordFailure - ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}.` + ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}. Manually verify that no active matching sandbox owns the model before releasing only ${attemptedModels.join(", ")} from the local Ollama host.` : attemptedModels.length > 0 ? `Re-run onboarding to retry only: ${attemptedModels.join(", ")}.` : "The Ollama host receipt was left unchanged."; @@ -692,7 +693,7 @@ export function releaseSupersededOllamaModel( ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}. Manually release only ${attemptedModels.join(", ")} at ${cleanup.endpoint}.` : `Re-run onboarding or destroy '${previous.name}' to retry only: ${attemptedModels.join(", ")}.`); } else { - clearPending(previous.name, attemptedModels); + clearPending(previous, attemptedModels); } } catch (error) { if (pendingRecordFailure) pendingRecordFailure = persistRetry(); @@ -707,7 +708,7 @@ export function releaseSupersededOllamaModel( : `Re-run onboarding or destroy '${previous.name}' to retry only the recorded models: ${attemptedModels.join(", ")}.`); } } - const pendingAfterCleanup = loadPending(previous.name); + const pendingAfterCleanup = loadPending(previous); if (retireRouteCandidate && !cleanupWarning && pendingAfterCleanup.length === 0) { const routeOwnerDiscovery = modelOwners.length === ollamaRouteCandidates.length diff --git a/src/lib/tunnel/services.test.ts b/src/lib/tunnel/services.test.ts index 9edddc8b0d4..4d6840a80b4 100644 --- a/src/lib/tunnel/services.test.ts +++ b/src/lib/tunnel/services.test.ts @@ -1276,25 +1276,32 @@ describe("stopAll", () => { expect(output).toContain("All services stopped"); logSpy.mockRestore(); }); - it("runs injected Ollama cleanup before reporting services stopped", () => { const cleanup = vi.fn(); const clearPendingOllamaModelCleanup = vi.fn(); + const ollamaCleanupOwner = { + name: "test-box", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-test-box", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + }; const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); stopAll({ pidDir, sandboxName: "test-box", + ollamaCleanupOwner, unloadOllamaModels: cleanup, clearPendingOllamaModelCleanup, + unmanagedCloudflaredPids: () => [], }); const stoppedCallIndex = logSpy.mock.calls.findIndex(([message]) => String(message).includes("All services stopped"), ); const stoppedCallOrder = logSpy.mock.invocationCallOrder[stoppedCallIndex]; logSpy.mockRestore(); - expect(cleanup).toHaveBeenCalledOnce(); - expect(clearPendingOllamaModelCleanup).toHaveBeenCalledWith("test-box"); + expect(clearPendingOllamaModelCleanup).toHaveBeenCalledWith(ollamaCleanupOwner); expect(cleanup.mock.invocationCallOrder[0]).toBeLessThan(stoppedCallOrder ?? 0); }); diff --git a/src/lib/tunnel/services.ts b/src/lib/tunnel/services.ts index 640a9c4c5b8..97f77ef5216 100644 --- a/src/lib/tunnel/services.ts +++ b/src/lib/tunnel/services.ts @@ -27,6 +27,7 @@ import { unloadOllamaModels as unloadDefaultOllamaModels, type OllamaUnloadResult, } from "../inference/ollama/proxy"; +import type { OllamaModelCleanupOwner } from "../inference/ollama/model-ownership"; import type { RuntimeProviderChannelStopTransport } from "../onboard/runtime-provider/access"; import { listGatewayStateRoots, resolveHome } from "../state/gateway-registry"; import { resolveNemoclawStateDir } from "../state/paths"; @@ -77,8 +78,10 @@ export interface ServiceOptions { cleanupOllamaModels?: boolean; /** Provider-owned transport for stopping the sandbox's native gateway. */ channelStopTransport?: RuntimeProviderChannelStopTransport; + /** Exact sandbox identity whose pending Ollama cleanup may be cleared. */ + ollamaCleanupOwner?: OllamaModelCleanupOwner; /** Clears pending Ollama cleanup recovery after this sandbox's models unload. */ - clearPendingOllamaModelCleanup?: (sandboxName: string) => void; + clearPendingOllamaModelCleanup?: (owner: OllamaModelCleanupOwner) => void; /** Cloudflare named tunnel token. Falls back to CLOUDFLARE_TUNNEL_TOKEN. */ cloudflareTunnelToken?: string; /** Also release the managed host gateway port (legacy full-stop only). */ @@ -1379,7 +1382,13 @@ function stopAllLocked(opts: ServiceOptions = {}): OllamaUnloadResult | void { }, then retry this command.`, ); } else if (sandboxName) { - (opts.clearPendingOllamaModelCleanup ?? clearDefaultPendingOllamaModelCleanup)(sandboxName); + const cleanupOwner = + opts.ollamaCleanupOwner ?? findSandboxAcrossGatewayRoots(sandboxName)?.entry; + if (cleanupOwner) { + (opts.clearPendingOllamaModelCleanup ?? clearDefaultPendingOllamaModelCleanup)( + cleanupOwner, + ); + } } } catch (error) { ollamaCleanupIncomplete = true; diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 03777ab4a0e..30ac53a9832 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -17,6 +17,11 @@ import { type SandboxClient, validateSandboxName } from "../fixtures/clients/san import { expect, test } from "../fixtures/e2e-test.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { + PUBLIC_NVIDIA_SWITCH_MODEL, + PUBLIC_NVIDIA_SWITCH_PROVIDER, + requirePublicNvidiaSwitchKey, +} from "./public-nvidia-switch-provider.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-gpu-double"; const PROXY_PORT = process.env.NEMOCLAW_OLLAMA_PROXY_PORT ?? "11435"; @@ -49,10 +54,12 @@ async function nemoclaw( artifactName: string, extraEnv: NodeJS.ProcessEnv = {}, timeoutMs = 20 * 60_000, + redactionValues: string[] = [], ): Promise { return await host.command(process.execPath, [CLI_ENTRYPOINT, ...args], { artifactName, env: env(extraEnv), + redactionValues, timeoutMs, }); } @@ -118,10 +125,6 @@ function parseReplyCommand(): string { return String.raw`python3 -c 'import json,sys; d=json.load(sys.stdin); m=d["choices"][0]["message"]; print((m.get("content") or m.get("reasoning_content") or m.get("reasoning") or "").strip())'`; } -function fileMode(pathname: string): string { - return (fs.statSync(pathname).mode & 0o777).toString(8).padStart(3, "0"); -} - function chatRequest(model: string): string { return JSON.stringify({ model, @@ -135,12 +138,12 @@ function chatRequest(model: string): string { }); } -async function expectSandboxInference42( +async function querySandboxForAnswer( sandbox: SandboxClient, model: string, artifactName: string, -): Promise { - const response = await sandbox.exec( +): Promise { + return await sandbox.exec( SANDBOX_NAME, [ "sh", @@ -153,12 +156,20 @@ async function expectSandboxInference42( timeoutMs: 150_000, }, ); +} + +async function expectSandboxInference42( + sandbox: SandboxClient, + model: string, + artifactName: string, +): Promise { + const response = await querySandboxForAnswer(sandbox, model, artifactName); expect(response.exitCode, resultText(response)).toBe(0); expect(containsAnswer(response.stdout, "42"), resultText(response)).toBe(true); } test( - "gpu double onboard keeps Ollama auth proxy token consistent after re-onboard", + "gpu double onboard preserves proxy auth and unloads Ollama on provider switch", { timeout: LIVE_TIMEOUT_MS, meta: { @@ -169,6 +180,9 @@ test( "validate first proxy token and inference", "re-onboard GPU sandbox", "validate persisted proxy auth and inference", + "verify the Ollama model is active before switching providers", + "switch inference to a non-Ollama provider", + "verify new-provider inference and confirm Ollama unloaded the old model", "remove GPU double-onboard sandbox", ], }, @@ -180,6 +194,7 @@ test( progress, runtimeProvider, sandbox, + secrets, skip, }) => { await artifacts.target.declare({ @@ -189,13 +204,17 @@ test( contracts: [ "GPU and runtime prerequisites are present", "install.sh onboards with the Ollama provider", - "the persisted Ollama auth-proxy token works after first onboard", + "sandbox inference.local reaches Ollama after first onboard", "nemoclaw onboard --non-interactive --yes recreates the sandbox", "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", "sandbox inference.local reaches Ollama after re-onboard", + "Ollama reports the selected model as active before the provider switch", + "nemoclaw inference set switches the sandbox to the public NVIDIA provider", + "sandbox inference succeeds through the new provider and host ollama ps no longer reports the superseded model", ], }); + const publicApiKey = requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")); await runtimeProvider.requireAvailable({ artifactName: "phase-0-runtime-info", scenarioLabel: "GPU double-onboard", @@ -330,23 +349,10 @@ exit "$status"`, expect(first.exitCode, resultText(first)).toBe(0); progress.phase("validate first proxy token and inference"); - const list = await nemoclaw(host, ["list"], "phase-3-nemoclaw-list"); - expect(list.exitCode, resultText(list)).toBe(0); - expect(list.stdout).toContain(SANDBOX_NAME); - expect(fs.existsSync(TOKEN_FILE), `${TOKEN_FILE} missing`).toBe(true); const tokenAfterFirst = fs.readFileSync(TOKEN_FILE, "utf8").trim(); expect(tokenAfterFirst.length).toBeGreaterThan(10); - expect(fileMode(TOKEN_FILE)).toBe("600"); const model = GPU_E2E_MODEL; - - const firstTokenStatus = await httpStatus( - host, - `http://127.0.0.1:${PROXY_PORT}/v1/models`, - "phase-3-proxy-token-status", - tokenAfterFirst, - ); - expect(firstTokenStatus.stdout.trim(), resultText(firstTokenStatus)).toBe("200"); await expectSandboxInference42(sandbox, model, "phase-3-sandbox-inference-first-onboard"); progress.phase("re-onboard GPU sandbox"); @@ -358,10 +364,7 @@ exit "$status"`, execTimeout(30 * 60_000), ); expect(reonboard.exitCode, resultText(reonboard)).toBe(0); - expect(fs.existsSync(TOKEN_FILE), `${TOKEN_FILE} missing after re-onboard`).toBe(true); const tokenAfterSecond = fs.readFileSync(TOKEN_FILE, "utf8").trim(); - expect(tokenAfterSecond.length).toBeGreaterThan(10); - expect(fileMode(TOKEN_FILE)).toBe("600"); expect(tokenAfterSecond).toBe(tokenAfterFirst); progress.phase("validate persisted proxy auth and inference"); @@ -397,6 +400,53 @@ exit "$status"`, await expectSandboxInference42(sandbox, model, "phase-6-sandbox-inference-after-reonboard"); + progress.phase("verify the Ollama model is active before switching providers"); + const activeModelsBeforeSwitch = await host.command("ollama", ["ps"], { + artifactName: "phase-7-ollama-ps-before-provider-switch", + env: env(), + timeoutMs: 30_000, + }); + expect(activeModelsBeforeSwitch.exitCode, resultText(activeModelsBeforeSwitch)).toBe(0); + expect(activeModelsBeforeSwitch.stdout).toContain(model); + + progress.phase("switch inference to a non-Ollama provider"); + const providerSwitch = await nemoclaw( + host, + [ + "inference", + "set", + "--provider", + PUBLIC_NVIDIA_SWITCH_PROVIDER, + "--model", + PUBLIC_NVIDIA_SWITCH_MODEL, + "--sandbox", + SANDBOX_NAME, + ], + "phase-8-inference-set-away-from-ollama", + { NVIDIA_INFERENCE_API_KEY: publicApiKey }, + execTimeout(5 * 60_000), + [publicApiKey], + ); + expect(providerSwitch.exitCode, resultText(providerSwitch)).toBe(0); + + progress.phase("verify new-provider inference and confirm Ollama unloaded the old model"); + const switchedInference = await querySandboxForAnswer( + sandbox, + PUBLIC_NVIDIA_SWITCH_MODEL, + "phase-9-sandbox-inference-after-provider-switch", + ); + expect(switchedInference.exitCode, resultText(switchedInference)).toBe(0); + expect(containsAnswer(switchedInference.stdout, "42"), resultText(switchedInference)).toBe( + true, + ); + const activeModelsAfterSwitch = await host.command("ollama", ["ps"], { + artifactName: "phase-9-ollama-ps-after-provider-switch", + env: env(), + timeoutMs: 30_000, + }); + expect(activeModelsAfterSwitch.exitCode, resultText(activeModelsAfterSwitch)).toBe(0); + expect(activeModelsAfterSwitch.stdout).not.toContain(model); + progress.phase("remove GPU double-onboard sandbox"); await host.cleanupSandbox(SANDBOX_NAME, { artifactName: "verify-cleanup-nemoclaw-destroy", @@ -409,6 +459,12 @@ exit "$status"`, await artifacts.target.complete({ id: "gpu-double-onboard", status: "passed", + assertions: { + ollamaModelActiveBeforeProviderSwitch: true, + inferenceSetCompleted: providerSwitch.exitCode === 0, + switchedProviderInferenceReturned42: true, + supersededOllamaModelAbsentAfterSwitch: true, + }, }); }, ); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 6090a528614..33425a26a54 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -581,9 +581,13 @@ { "live": "test/e2e/live/gpu-double-onboard.test.ts", "fast": [ + "src/lib/inference/ollama/model-ownership.test.ts", + "src/lib/onboard/setup-inference.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/helpers/e2e-answer-assertions.test.ts" + "test/helpers/e2e-answer-assertions.test.ts", + "test/onboarding/onboard-inference-reconciliation.test.ts", + "test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts" ] }, { diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 3de33c7bf64..084d863a23b 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -13,6 +13,7 @@ import { loadPersistedOllamaHost, persistResolvedOllamaHost, } from "../../src/lib/inference/local.js"; +import type { OllamaModelCleanupOwner } from "../../src/lib/inference/ollama/model-ownership.js"; import { createLocalInferenceRouteApplier } from "../../src/lib/onboard/local-inference-route.js"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { writeOkOpenshell } from "../helpers/onboard-openshell-fixture"; @@ -1080,10 +1081,13 @@ describe("re-onboard Ollama GPU release (#9110)", () => { applyLocalInferenceRoute?: () => Promise; loadPersistedOllamaHost?: () => "127.0.0.1" | "host.docker.internal" | null; clearPersistedOllamaHostIfUnused?: SetupInferenceDeps["localInference"]["clearPersistedOllamaHostIfUnused"]; - loadPendingOllamaModelCleanup?: (sandboxName: string) => readonly string[]; - persistPendingOllamaModelCleanup?: (sandboxName: string, models: readonly string[]) => void; + loadPendingOllamaModelCleanup?: (owner: OllamaModelCleanupOwner) => readonly string[]; + persistPendingOllamaModelCleanup?: ( + owner: OllamaModelCleanupOwner, + models: readonly string[], + ) => void; clearPendingOllamaModelCleanup?: ( - sandboxName: string, + owner: OllamaModelCleanupOwner, releasedModels?: readonly string[], ) => void; }) { @@ -1260,7 +1264,10 @@ describe("re-onboard Ollama GPU release (#9110)", () => { expect(unloadOllamaModels).toHaveBeenNthCalledWith(1, ["llama3"]); expect(unloadOllamaModels).toHaveBeenNthCalledWith(2, ["llama3"]); - expect(clearPendingOllamaModelCleanup).toHaveBeenCalledWith("test-box", ["llama3"]); + expect(clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + expect.objectContaining({ name: "test-box" }), + ["llama3"], + ); expect(pending).toEqual([]); }); diff --git a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts index 3dfa13d5714..0546b1b2996 100644 --- a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts +++ b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts @@ -12,6 +12,7 @@ import type { CleanupSandboxServicesDeps } from "../../../src/lib/actions/sandbo import { cleanupSandboxServices } from "../../../src/lib/actions/sandbox/destroy.js"; import { ollamaModelRefsMatch } from "../../../src/lib/inference/ollama/model-discovery.js"; import type { OllamaModelHolder } from "../../../src/lib/inference/ollama/model-ownership.js"; +import type { SandboxEntry } from "../../../src/lib/state/registry.js"; import { SANDBOX_PROVIDER_SUFFIXES } from "../../../src/lib/onboard/sandbox-provider-cleanup.js"; type SandboxLike = { name?: string; model?: string | null; provider?: string | null } | null; @@ -181,6 +182,28 @@ describe("cleanupSandboxServices Ollama unload", () => { expect(harness.unloadCalls).toBe(1); }); + it("uses the verified pre-destroy route if the registry row is already absent", async () => { + const harness = buildDeps(null); + const sandboxSnapshot = { + name: "regression-2717", + provider: "ollama-local", + model: "target-model:latest", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + } as SandboxEntry; + + await cleanupSandboxServices( + "regression-2717", + { stopHostServices: false, sandboxSnapshot }, + harness.deps, + ); + + expect(harness.deps.getSandbox).not.toHaveBeenCalled(); + expect(harness.deps.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith([ + "target-model:latest", + ]); + }); + it("releases only the destroyed sandbox model when another Ollama sandbox uses a different model", async () => { const harness = buildDeps({ provider: "ollama-local", model: "target-model:latest" }, [ { name: "peer", provider: "ollama-local", model: "peer-model:latest" }, @@ -208,9 +231,10 @@ describe("cleanupSandboxServices Ollama unload", () => { await cleanupSandboxServices("regression-2717", { stopHostServices: false }, harness.deps); expect(harness.unloadArgs).toEqual([["old-model"]]); - expect(harness.deps.clearPendingOllamaModelCleanup).toHaveBeenCalledWith("regression-2717", [ - "old-model", - ]); + expect(harness.deps.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + expect.objectContaining({ name: "regression-2717" }), + ["old-model"], + ); }); it("keeps a pending superseded model that an Ollama peer shares", async () => { From e7531244b7d5823ab800b11f295498605c408eb9 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 10:10:09 +0000 Subject: [PATCH 12/44] test: match connect timeout message case-insensitively (#12677) Signed-off-by: Yimo Jiang --- test/runtime/sandbox/sandbox-stuck-recovery.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/runtime/sandbox/sandbox-stuck-recovery.test.ts b/test/runtime/sandbox/sandbox-stuck-recovery.test.ts index 9785bca6509..518a6bb70fa 100644 --- a/test/runtime/sandbox/sandbox-stuck-recovery.test.ts +++ b/test/runtime/sandbox/sandbox-stuck-recovery.test.ts @@ -164,7 +164,7 @@ describe("sandbox stuck in non-Ready phase (#2016)", () => { const combined = (result.stdout || "") + (result.stderr || ""); expect(combined).toContain(`Waiting for sandbox '${sandboxName}' to be ready`); - expect(combined).toContain("Timed out"); + expect(combined).toMatch(/timed out/iu); expect(combined).toContain("NEMOCLAW_CONNECT_TIMEOUT"); }, ); From 1fbe1b5760ad5dfe50656daba82941a735eb976c Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 11:14:40 +0000 Subject: [PATCH 13/44] fix(ollama): guide legacy cleanup recovery (#12677) Signed-off-by: Yimo Jiang --- docs/inference/set-up-ollama.mdx | 18 ++++++++++++++++ .../inference/ollama/model-ownership.test.ts | 13 +++++++++++- src/lib/inference/ollama/model-ownership.ts | 2 +- ...standard-profile-workflow-boundary.test.ts | 5 +++++ test/e2e/support/workflow-plan.test.ts | 21 ++++++++++++++++--- tools/e2e/target-catalogue.mts | 6 +++--- 6 files changed, 57 insertions(+), 8 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 6fd87cb1bbb..216a2654c30 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -412,6 +412,24 @@ If the new route uses the same model through the same local daemon, NemoClaw kee If the unload cleanup fails, the new route remains active and NemoClaw attempts to record the model for cleanup retry. Rerun onboarding or run `$$nemoclaw destroy` to retry it; if the warning says the retry state could not be recorded, use its reported manual-release guidance instead. This cleanup is best-effort and does not delete downloaded model files. +### Recover a legacy pending Ollama cleanup + +A legacy cleanup receipt may list model names without recording the gateway and sandbox lifecycle that owned them. NemoClaw does not replay or clear those receipts because a reused sandbox name cannot establish ownership. The warning names the receipt's sandbox and each listed model; no model is unloaded automatically. + +Before manually releasing a listed model, verify that no active sandbox on this host still uses it: + +1. Run `openshell gateway list` and identify every NemoClaw gateway on the host. Do not assume the selected gateway is the only one. +2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. +3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. +4. Only after every gateway and sandbox was checked successfully and no active sandbox uses the listed model, confirm the model appears in `ollama ps`. Run these commands against the same host Ollama daemon NemoClaw uses. Stop only the exact listed model, then verify that it is absent: + + ```bash + ollama stop '' + ollama ps + ``` + +Do not delete or edit the legacy receipt to force an automatic retry. Keep the model loaded whenever ownership cannot be verified. + ## Related Topics - [Choose a Local Inference Server](choose-local-inference-server) to compare local options. diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 00ad0d30f6a..7a76304cda2 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -399,8 +399,19 @@ describe("pending Ollama model cleanup", () => { try { expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual([]); expect(warning).toHaveBeenCalledWith( - expect.stringContaining("has no gateway/lifecycle identity"), + expect.stringContaining( + "legacy pending Ollama cleanup for 'test-box' lists llama3 but has no gateway/lifecycle identity", + ), ); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("no active sandbox on any gateway"), + ); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("Recover a legacy pending Ollama cleanup"), + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("ollama stop ")); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("ollama ps")); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("NemoClaw left it untouched")); clearPendingOllamaModelCleanup(owner, undefined, stateRoot); expect(existsSync(legacyPath)).toBe(true); diff --git a/src/lib/inference/ollama/model-ownership.ts b/src/lib/inference/ollama/model-ownership.ts index bbfa39c581d..07af23eb963 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -144,7 +144,7 @@ export function loadPendingOllamaModelCleanup( : []; if (legacyModels.length > 0) { console.warn( - ` Warning: legacy pending Ollama cleanup for '${owner.name}' (${legacyModels.join(", ")}) has no gateway/lifecycle identity. NemoClaw left it untouched; verify active owners before manually releasing any listed model.`, + ` Warning: legacy pending Ollama cleanup for '${owner.name}' lists ${legacyModels.join(", ")} but has no gateway/lifecycle identity. NemoClaw left it untouched. Verify no active sandbox on any gateway uses a listed model before release; see "Recover a legacy pending Ollama cleanup" in the Set Up Ollama guide for the ownership checks, 'ollama stop ', and 'ollama ps' verification.`, ); } if (!identity) return []; diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index f01f1d47642..1081848be07 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -26,6 +26,11 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); + it("routes the GPU provider-switch target through guarded NVIDIA API credentials", () => { + expect(catalogueTarget("gpu-double-onboard").profile).toBe("nvidia-api"); + expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); + }); + it("reserves the standard full-E2E setup, test, and artifact envelope", () => { // The original 70-minute path now includes native configuration and plugin lifecycle work. expect(FULL_E2E_TEST_TIMEOUT_MINUTES).toBeGreaterThanOrEqual(100); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 13c830e8649..7caf8f4835a 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -247,6 +247,16 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-inference"]); }); + it("routes the GPU Ollama provider-switch target through the guarded NVIDIA API profile", () => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({ targets: targetId }); + + expect(catalogueTarget(targetId).profile).toBe("nvidia-api"); + expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toEqual([targetId]); + expect(plan.catalogueMatrices.standard).toEqual([]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); + }); + it("routes Pi lifecycle qualification through the AMD64 NVIDIA API key profile (#7926)", () => { const targetId = "pi-agent-qualification-amd64"; const plan = buildE2eWorkflowPlan({ targets: targetId }); @@ -662,18 +672,23 @@ describe("E2E workflow plan", () => { }); }); - it("routes homogeneous GPU targets through the standard workflow matrix", () => { + it("routes GPU targets through their profile-specific workflow matrices", () => { const targetIds = ["gpu-double-onboard", "gpu-e2e", "llama-cpp-generic-gpu"]; const expectedRunner = "linux-amd64-gpu-rtxpro6000-latest-1"; const plan = buildE2eWorkflowPlan({ jobs: targetIds.join(",") }); expect(plan.catalogueMatrices.standard).toEqual( - targetIds.map((id) => expect.objectContaining({ id, runner: expectedRunner })), + ["gpu-e2e", "llama-cpp-generic-gpu"].map((id) => + expect.objectContaining({ id, runner: expectedRunner }), + ), ); + expect(plan.catalogueMatrices["nvidia-api"]).toEqual([ + expect.objectContaining({ id: "gpu-double-onboard", runner: expectedRunner }), + ]); expect(plan.catalogueMatrices.standard.find((row) => row.id === "gpu-e2e")).not.toHaveProperty( "selector", ); - expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard"]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api", "catalogue-standard"]); }); it("selects the complete GPU reply target when its Hermes helper changes", () => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 04c9436baa6..daf33396b2e 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -804,10 +804,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }), ), managedRuntimeTarget("gpu-double-onboard", { - displayName: "Onboarding: preserves Ollama authentication after GPU re-onboarding", + displayName: "Onboarding: preserves Ollama auth after GPU re-onboarding and provider switch", agentRuntime: "openclaw", - environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama", - profile: "standard", + environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama and NVIDIA API inference", + profile: "nvidia-api", runner: "linux-amd64-gpu-rtxpro6000-latest-1", podmanHostPackages: NATIVE_PODMAN_HOST_PACKAGES, timeoutMinutes: 100, From 6a52cb92993f03354eddf15e8695d6202f833518 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 12:36:14 +0000 Subject: [PATCH 14/44] fix(ollama): harden ownership cleanup recovery (#12677) Signed-off-by: Yimo Jiang --- ci/source-architecture-budget.json | 2 +- docs/inference/set-up-ollama.mdx | 8 ++- src/lib/actions/sandbox/destroy-flow.test.ts | 11 ++++ src/lib/actions/sandbox/destroy.ts | 59 ++++++++++--------- src/lib/adapters/openshell/runtime.ts | 5 ++ .../inference/ollama/model-ownership.test.ts | 24 ++++++++ src/lib/onboard/setup-inference.test.ts | 22 +++---- src/lib/onboard/setup-inference.ts | 19 +----- 8 files changed, 90 insertions(+), 60 deletions(-) diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index d903a85ea49..394e911ec71 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -9,7 +9,7 @@ "src/lib/adapters/openshell/client.ts": 18, "src/lib/adapters/openshell/command-argv.ts": 17, "src/lib/adapters/openshell/resolve.ts": 22, - "src/lib/adapters/openshell/runtime.ts": 41, + "src/lib/adapters/openshell/runtime.ts": 42, "src/lib/adapters/openshell/sandbox-observer-cli.ts": 21, "src/lib/adapters/openshell/sandbox-observer.ts": 35, "src/lib/adapters/openshell/timeouts.ts": 23, diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 216a2654c30..e081e01f39d 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -428,7 +428,13 @@ Before manually releasing a listed model, verify that no active sandbox on this ollama ps ``` -Do not delete or edit the legacy receipt to force an automatic retry. Keep the model loaded whenever ownership cannot be verified. +5. After the ownership checks succeed and every listed model is confirmed absent from `ollama ps`, acknowledge the completed manual recovery by removing only that sandbox's legacy receipt: + + ```bash + rm -- "$HOME/.nemoclaw/ollama-pending-model-cleanup/.json" + ``` + + Replace `` with the exact sandbox name printed in the warning. This only retires the obsolete warning receipt; it does not trigger cleanup. If any ownership check is incomplete or a listed model remains active, keep the receipt and do not stop a model owned by an active sandbox. Do not delete or edit the receipt to force an automatic retry. ## Related Topics diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index 638d3e77051..2d992006fce 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -1355,6 +1355,17 @@ describe("destroySandbox flow", () => { expect(exitSpy).not.toHaveBeenCalled(); }); + it("preserves host resources when --force cannot confirm sandbox deletion", async () => { + const harness = createDestroyHarness({ deleteStatus: 1, deleteOutput: "connection refused" }); + await expect(harness.destroySandbox("alpha", { force: true })).resolves.toBeUndefined(); + expect(harness.unloadOllamaModelsSpy).not.toHaveBeenCalled(); + expect(harness.stopAllSpy).not.toHaveBeenCalled(); + expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["provider", "delete"]), + expect.anything(), + ); + }); + it("fails closed and restores MCP state when --force cannot confirm sandbox deletion", async () => { const harness = createDestroyHarness({ deleteStatus: 1, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 5588f32416e..a4424a9bd57 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -1240,33 +1240,38 @@ async function destroySandboxUnlocked( } } } - try { - const shouldStopHostServices = shouldStopHostServicesAfterDestroy({ - deleteSucceededOrAlreadyGone, - registeredSandboxCount: listRegisteredSandboxes().sandboxes.length, - sandboxStillRegistered: !!getRegisteredSandbox(sandboxName), - }); - await cleanupSandboxServices( - sandboxName, - { - gatewayPort: - registeredSandbox === null - ? (retainedRecoveryAuthority?.gatewayPort ?? registryAuthority.gatewayPort) - : registryAuthority.gatewayPort, - stopHostServices: shouldStopHostServices, - sandboxSnapshot: sandbox, - ...(destroyChannelStopTransport - ? { channelStopTransport: destroyChannelStopTransport } - : {}), - }, - { - getSandbox: getRegisteredSandbox, - runOpenshell: cleanupRunOpenshell, - }, - ); - } catch (error) { - preparedManagedLlamaCppCleanup?.abort(); - throw error; + // stopHostServices=false protects shared daemons but cleanupSandboxServices also + // releases sandbox-scoped models and providers. Do not run any of it until the + // gateway confirms deletion or absence; --force cannot establish that proof. + if (deleteSucceededOrAlreadyGone) { + try { + const shouldStopHostServices = shouldStopHostServicesAfterDestroy({ + deleteSucceededOrAlreadyGone, + registeredSandboxCount: listRegisteredSandboxes().sandboxes.length, + sandboxStillRegistered: !!getRegisteredSandbox(sandboxName), + }); + await cleanupSandboxServices( + sandboxName, + { + gatewayPort: + registeredSandbox === null + ? (retainedRecoveryAuthority?.gatewayPort ?? registryAuthority.gatewayPort) + : registryAuthority.gatewayPort, + stopHostServices: shouldStopHostServices, + sandboxSnapshot: sandbox, + ...(destroyChannelStopTransport + ? { channelStopTransport: destroyChannelStopTransport } + : {}), + }, + { + getSandbox: getRegisteredSandbox, + runOpenshell: cleanupRunOpenshell, + }, + ); + } catch (error) { + preparedManagedLlamaCppCleanup?.abort(); + throw error; + } } if (deleteSucceededOrAlreadyGone && commonLlamaCppAuthorityRetired === true) { preparedManagedLlamaCppCleanup?.abort(); diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index c43039cc2f5..ecb9f9816dd 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -32,6 +32,11 @@ export { export { buildOpenShellSubprocessEnv, OPENSHELL_OPERATION_TIMEOUT_MS, OPENSHELL_PROBE_TIMEOUT_MS }; export { classifyManagedGatewayEndpointBinding } from "./command-execution"; +export { + assertNoOpenShellGatewayEndpointOverride, + scopeGatewayOpenshellArgs, + type OpenShellGatewayEndpointEnvironment, +} from "./gateway-scope"; export { runCaptureEx } from "../../runner"; type RunnerOptions = { diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 7a76304cda2..c97f48ba37a 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -421,6 +421,30 @@ describe("pending Ollama model cleanup", () => { } }); + it("stops warning after a legacy receipt is manually retired following recovery", () => { + const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); + const owner = cleanupOwner(); + const legacyPath = join(stateRoot, "ollama-pending-model-cleanup", `${owner.name}.json`); + mkdirSync(join(stateRoot, "ollama-pending-model-cleanup"), { recursive: true, mode: 0o700 }); + writeFileSync( + legacyPath, + JSON.stringify({ schemaVersion: 1, sandboxName: owner.name, models: ["llama3"] }), + { mode: 0o600 }, + ); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + // The operator removes this receipt only after the documented cross-gateway + // ownership checks and manual Ollama release have succeeded. + rmSync(legacyPath); + + expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual([]); + expect(warning).not.toHaveBeenCalled(); + } finally { + warning.mockRestore(); + rmSync(stateRoot, { recursive: true, force: true }); + } + }); + it("fails closed when cleanup receipt lifecycle identity is incomplete", () => { const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); const owner = cleanupOwner(); diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 8974fdd9622..4986da6b879 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -223,7 +223,7 @@ describe("releaseSupersededOllamaModel", () => { } }); - it("uses suppressed OpenShell output in the default cross-gateway discovery path", () => { + it("uses the injected phase capture for cross-gateway discovery", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); vi.stubEnv("HOME", home); const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); @@ -248,28 +248,20 @@ describe("releaseSupersededOllamaModel", () => { useProductionPeerSource: true, useProductionDiscovery: true, }); - const runOpenshell = vi.fn(() => ({ + const captureOllamaOwnershipPhases = vi.fn(() => ({ status: 0, - stdout: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", - stderr: "", + output: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", })); const deps = harness.deps as SetupInferenceDeps; - deps.runOpenshell = runOpenshell as unknown as SetupInferenceDeps["runOpenshell"]; + deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName!; try { releaseToNvidia(previousLocalOllamaRoute, deps); - expect(runOpenshell).toHaveBeenCalledExactlyOnceWith( - ["sandbox", "list", "-g", "nemoclaw-32665"], - expect.objectContaining({ - env: process.env, - ignoreError: true, - maxBuffer: 1024 * 1024, - stdio: "pipe", - suppressOutput: true, - timeout: 10_000, - }), + expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( + "nemoclaw-32665", + process.env, ); expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index f713124e06b..50e8c52d22d 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -60,9 +60,10 @@ import { } from "../inference/ollama/proxy"; import { assertNoOpenShellGatewayEndpointOverride, + captureSandboxPhasesForGateway, scopeGatewayOpenshellArgs, type OpenShellGatewayEndpointEnvironment, -} from "../adapters/openshell/gateway-scope"; +} from "../adapters/openshell/runtime"; import type { withSandboxMutationLock } from "../state/mcp-lifecycle-lock"; import type { Session } from "../state/onboard-session"; import { createSandboxHostLocalInferenceProvenance } from "../state/registry/host-local-inference"; @@ -590,21 +591,7 @@ export function releaseSupersededOllamaModel( ); const environment = deps.environment ?? process.env; const captureOwnershipPhases: OllamaOwnershipPhaseCapture = - deps.captureOllamaOwnershipPhases ?? - ((gatewayName, captureEnvironment) => { - const result = deps.runOpenshell(["sandbox", "list", "-g", gatewayName], { - env: captureEnvironment, - ignoreError: true, - maxBuffer: 1024 * 1024, - stdio: "pipe", - suppressOutput: true, - timeout: 10_000, - }); - return { - status: result.status, - output: [result.stdout ?? "", result.stderr ?? ""].join("\n"), - }; - }); + deps.captureOllamaOwnershipPhases ?? captureSandboxPhasesForGateway; const discoverPeers = (owners: readonly OllamaModelHolder[]) => deps.discoverActiveOllamaSandboxNames ? deps.discoverActiveOllamaSandboxNames(owners, environment) From 81b527137d3ba2b01843e076e9c952cb360fdded Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 13:54:15 +0000 Subject: [PATCH 15/44] fix: fail closed on incomplete Ollama inventory Signed-off-by: Yimo Jiang --- docs/inference/set-up-ollama.mdx | 4 +-- src/lib/actions/sandbox/stop.test.ts | 28 ++++++++++------ .../inference/ollama/model-ownership.test.ts | 32 +++++++++++++++++++ src/lib/inference/ollama/model-ownership.ts | 24 +++++++------- src/lib/onboard/setup-inference.test.ts | 19 +++++++---- test/e2e/support/workflow-plan.test.ts | 14 ++++++++ tools/e2e/target-catalogue.mts | 4 +++ 7 files changed, 95 insertions(+), 30 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index e081e01f39d..ac4b22c1bb9 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -419,8 +419,8 @@ A legacy cleanup receipt may list model names without recording the gateway and Before manually releasing a listed model, verify that no active sandbox on this host still uses it: 1. Run `openshell gateway list` and identify every NemoClaw gateway on the host. Do not assume the selected gateway is the only one. -2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. -3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. +2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. +3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= $$nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. 4. Only after every gateway and sandbox was checked successfully and no active sandbox uses the listed model, confirm the model appears in `ollama ps`. Run these commands against the same host Ollama daemon NemoClaw uses. Stop only the exact listed model, then verify that it is absent: ```bash diff --git a/src/lib/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index 561d86a6847..816ef1cf691 100644 --- a/src/lib/actions/sandbox/stop.test.ts +++ b/src/lib/actions/sandbox/stop.test.ts @@ -235,7 +235,7 @@ describe("discoverActiveOllamaSandboxNames", () => { const activePeer = sandbox({ name: "active-peer" }); const stoppedPeer = sandbox({ name: "stopped-peer" }); - it("groups peers by gateway and distinguishes active phases from stopped or absent rows (#10074)", async () => { + it("groups peers by gateway and distinguishes active, transient, and terminal phases (#10074)", async () => { const captureSandboxOwnershipPhases = vi.fn(() => ({ status: 0, output: [ @@ -246,17 +246,12 @@ describe("discoverActiveOllamaSandboxNames", () => { ].join("\n"), })); const transientPeer = sandbox({ name: "transient-peer" }); - const missingPeer = sandbox({ name: "missing-peer" }); expect( - discoverActiveOllamaSandboxNames( - [activePeer, transientPeer, stoppedPeer, missingPeer], - environment, - { - captureSandboxOwnershipPhases, - resolvePersistedSandboxOwnershipGateway: () => "nemoclaw", - }, - ), + discoverActiveOllamaSandboxNames([activePeer, transientPeer, stoppedPeer], environment, { + captureSandboxOwnershipPhases, + resolvePersistedSandboxOwnershipGateway: () => "nemoclaw", + }), ).toEqual({ ok: true, activeSandboxNames: new Set(["active-peer", "transient-peer"]), @@ -271,6 +266,19 @@ describe("discoverActiveOllamaSandboxNames", () => { expect(captureSandboxOwnershipPhases).toHaveBeenCalledExactlyOnceWith("nemoclaw", environment); }); + it("fails closed when a listed sibling is omitted from a successful phase inventory (#10074)", async () => { + const omittedResult = discoverActiveOllamaSandboxNames([activePeer], environment, { + captureSandboxOwnershipPhases: () => ({ status: 0, output: "NAME CREATED PHASE" }), + resolvePersistedSandboxOwnershipGateway: () => "nemoclaw", + }); + + expect(omittedResult).toEqual({ + ok: false, + message: + "OpenShell omitted sibling 'active-peer' from the sandbox phase inventory on gateway 'nemoclaw'", + }); + }); + it("fails closed when a listed sibling has no usable phase (#10074)", async () => { const result = discoverActiveOllamaSandboxNames([activePeer], environment, { captureSandboxOwnershipPhases: () => ({ diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index c97f48ba37a..39faf8b2031 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -254,6 +254,38 @@ describe("discoverOllamaModelOwnership", () => { ), ).toEqual({ kind: "exclusive", model: "llama3", stalePeers: ["duplicate-peer"] }); }); + + it("fails closed when sibling gateway identity cannot be resolved", () => { + const peer = holder({ name: "unbound-peer" }); + const discovery = discoverOllamaModelOwnership([peer], {}, () => ({ + status: 0, + output: "NAME CREATED PHASE", + })); + + expect(discovery).toEqual({ + ok: false, + message: "could not resolve a sibling gateway: gateway binding resolver is unavailable", + }); + }); + + it("fails closed when a successful gateway inventory omits a requested peer", () => { + const peer = holder({ name: "missing-peer", gatewayName: "gateway-a" }); + const discovery = discoverOllamaModelOwnership( + [peer], + {}, + () => ({ status: 0, output: "NAME CREATED PHASE" }), + { + parseLiveSandboxEntries: () => [], + resolvePersistedSandboxOwnershipGateway: () => "gateway-a", + }, + ); + + expect(discovery).toEqual({ + ok: false, + message: + "OpenShell omitted sibling 'missing-peer' from the sandbox phase inventory on gateway 'gateway-a'", + }); + }); }); describe("decideOllamaModelOwnership", () => { diff --git a/src/lib/inference/ollama/model-ownership.ts b/src/lib/inference/ollama/model-ownership.ts index 07af23eb963..97cf0a068fe 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -268,11 +268,11 @@ export type OllamaModelOwnershipDecision = /** * Decide whether this sandbox's Ollama model has another active owner. * - * Registry rows persist after a sandbox stops and can also contain incomplete - * onboarding reservations. Callers should supply the peer rows found in Ready - * or Running phase. A matching row absent from that live set is evidence to - * report, not an owner that blocks release; the names set remains as a legacy - * fallback for callers that do not provide gateway-aware peer rows. + * Registry rows can outlive stopped sandboxes and include incomplete + * onboarding reservations. Live discovery must account for every requested + * peer: a matching peer omitted from a successful gateway inventory makes + * ownership inconclusive and must not authorize release. The names set remains + * a legacy fallback for callers that do not provide gateway-aware peer rows. */ export function listOllamaModelOwnershipPeersAcrossGatewayRoots(): SandboxEntry[] { return listInferenceRouteOwnersAcrossGatewayRoots(); @@ -400,13 +400,13 @@ export function discoverOllamaModelOwnership( const activeSandboxes: string[] = []; for (const peer of gatewayPeers) { const phase = phases.get(peer.name); - if ( - phase === undefined || - phase === "Stopped" || - phase === "Error" || - phase === "Failed" || - phase === "Evicted" - ) { + if (phase === undefined) { + return { + ok: false, + message: `OpenShell omitted sibling '${peer.name}' from the sandbox phase inventory on gateway '${gateway}'`, + }; + } + if (phase === "Stopped" || phase === "Error" || phase === "Failed" || phase === "Evicted") { continue; } if (phase === null || phase === "Unknown") { diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 4986da6b879..e2f1a082590 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -271,8 +271,8 @@ describe("releaseSupersededOllamaModel", () => { } }); - it("fails closed and records retry state when default discovery lacks a gateway resolver", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-missing-resolver-")); + it("fails closed and records retry state when a successful inventory omits a matching peer", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-omitted-inventory-")); vi.stubEnv("HOME", home); const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); fs.mkdirSync(gatewayRoot, { recursive: true }); @@ -296,9 +296,13 @@ describe("releaseSupersededOllamaModel", () => { useProductionPeerSource: true, useProductionDiscovery: true, }); - const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); - (harness.deps as SetupInferenceDeps).runOpenshell = - runOpenshell as unknown as SetupInferenceDeps["runOpenshell"]; + const captureOllamaOwnershipPhases = vi.fn(() => ({ + status: 0, + output: "NAME CREATED PHASE", + })); + const deps = harness.deps as SetupInferenceDeps; + deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; + deps.resolveOllamaOwnershipGateway = () => "nemoclaw-32677"; const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); try { @@ -309,7 +313,10 @@ describe("releaseSupersededOllamaModel", () => { previousLocalOllamaRoute, ["qwen2.5:1.5b"], ); - expect(runOpenshell).not.toHaveBeenCalled(); + expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( + "nemoclaw-32677", + process.env, + ); expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); } finally { warning.mockRestore(); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 7caf8f4835a..dc541be7c9f 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -257,6 +257,20 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); }); + it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( + "selects the GPU provider-switch target for a source-only %s change", + (changedFile) => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); + + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + targetId, + ); + expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toContain(targetId); + expect(selectedWorkflowJobs(plan)).toContain("catalogue-nvidia-api"); + }, + ); + it("routes Pi lifecycle qualification through the AMD64 NVIDIA API key profile (#7926)", () => { const targetId = "pi-agent-qualification-amd64"; const plan = buildE2eWorkflowPlan({ targets: targetId }); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index daf33396b2e..8b83cd5a1f2 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -814,6 +814,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ installMode: "authenticated", restoreCli: true, exposeCliBin: true, + owningPaths: [ + "src/lib/inference/ollama/model-ownership.ts", + "src/lib/onboard/setup-inference.ts", + ], environment: { ...nonInteractive, NEMOCLAW_MODEL: "qwen3.5:9b", From 43b1758f3fc81b44fb6056b61efedf446069dcda Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 14:00:17 +0000 Subject: [PATCH 16/44] test: resolve Ollama peers to recorded gateway Signed-off-by: Yimo Jiang --- src/lib/onboard/setup-inference.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index e2f1a082590..e9969f1abf5 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -302,7 +302,7 @@ describe("releaseSupersededOllamaModel", () => { })); const deps = harness.deps as SetupInferenceDeps; deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; - deps.resolveOllamaOwnershipGateway = () => "nemoclaw-32677"; + deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName ?? "default"; const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); try { @@ -314,7 +314,7 @@ describe("releaseSupersededOllamaModel", () => { ["qwen2.5:1.5b"], ); expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( - "nemoclaw-32677", + "nemoclaw-32665", process.env, ); expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); From d08def1dbc3ac2513c7b4bf8f477c1876b89ec97 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Mon, 12 Oct 2026 14:29:50 +0000 Subject: [PATCH 17/44] test: include active peer in destroy inventory Signed-off-by: Yimo Jiang --- src/lib/actions/sandbox/destroy-cross-root.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/sandbox/destroy-cross-root.test.ts b/src/lib/actions/sandbox/destroy-cross-root.test.ts index 9c9cba8a7a8..7cb24b702f7 100644 --- a/src/lib/actions/sandbox/destroy-cross-root.test.ts +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -100,7 +100,13 @@ describe("destroySandbox cross-root registry authority", () => { }, }), ); - const harness = createDestroyHarness(); + const harness = createDestroyHarness({ + sandboxListResult: { + status: 0, + stdout: "NAME PHASE\nalpha Ready\nbeta Ready", + stderr: "", + }, + }); await expect( harness.destroySandbox("alpha", { yes: true, cleanupGateway: true }), @@ -111,6 +117,7 @@ describe("destroySandbox cross-root registry authority", () => { sandboxes: { beta: { name: "beta" } }, }); expect(harness.cleanupGatewaySpy).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModelsSpy).not.toHaveBeenCalled(); expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); }); }); From 7ab029cadc0d3c39859f78d09c886aca24c1f4c6 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Tue, 13 Oct 2026 05:00:35 +0000 Subject: [PATCH 18/44] fix(inference): retain host receipt for stopped peers Signed-off-by: Yimo Jiang --- src/lib/onboard/setup-inference.test.ts | 15 ++++++++------- src/lib/onboard/setup-inference.ts | 4 ++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index e9969f1abf5..103482af51a 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -109,22 +109,23 @@ function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): } describe("releaseSupersededOllamaModel", () => { - it("unloads a superseded model when matching registry rows are not live", () => { - const staleReservation = { - name: "incomplete-reservation", + it("preserves the host target for a stopped peer after releasing its model", () => { + const stoppedPeer = { + name: "stopped-peer", provider: "ollama-local", model: "qwen2.5:1.5b", - endpointUrl: null, - gatewayName: "stale-peer-gateway", + endpointUrl: "http://127.0.0.1:11434", + gatewayName: "nemoclaw-32678", + gatewayPort: 32678, } as unknown as SandboxEntry; - const harness = createOllamaCleanupHarness({ peers: [staleReservation] }); + const harness = createOllamaCleanupHarness({ peers: [stoppedPeer] }); releaseToNvidia(previousLocalOllamaRoute, harness.deps); expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); expect(harness.localInference.clearPersistedOllamaHostIfUnused).toHaveBeenCalledExactlyOnceWith( - [], + [stoppedPeer], ); }); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 50e8c52d22d..b955fd0286d 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -714,8 +714,8 @@ export function releaseSupersededOllamaModel( isLocalOllamaRouteOwner(peer, selectedHost), ); if (activeOllamaPeerRoutes.length === 0) { - // The live-probed route set is empty; the helper retains its own guard. - deps.localInference.clearPersistedOllamaHostIfUnused?.(activeOllamaPeerRoutes); + // Stopped registry owners still need the shared host target if they restart. + deps.localInference.clearPersistedOllamaHostIfUnused?.(ollamaRouteCandidates); } } } From c46836036b53ccad228054261cf3fae69de57f39 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Mon, 26 Oct 2026 12:12:17 -0700 Subject: [PATCH 19/44] chore(inference): align conflict files with main for branch update Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-budget.json | 68 +- src/lib/onboard.ts | 183 ++- src/lib/onboard/setup-inference.test.ts | 915 ++++----------- src/lib/onboard/setup-inference.ts | 1055 +++++++++++++----- test/e2e/live/gpu-double-onboard.test.ts | 119 +- test/e2e/mock-parity.json | 106 +- test/support/setup-inference-test-harness.ts | 67 +- tools/e2e/target-catalogue.mts | 141 ++- 8 files changed, 1378 insertions(+), 1276 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 7fe861b3b4f..c15695e5515 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial no-growth baseline for issue #10934 and Epic #10920. The epic reference remains fixed at fe18b2f004e2304c52db33cf7bb5895828197f9a. Current main is lower because #10722 removed the live Shields assertion suites before this ratchet landed. PR #10341 adds the accepted public deferred-install and same-home credential continuation boundary for Hermes and Deep Agents Code; existing per-file budgets remain unchanged.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial no-growth baseline for issue #10934 and Epic #10920. The epic reference remains fixed at fe18b2f004e2304c52db33cf7bb5895828197f9a. Current main is lower because #10722 removed the live Shields assertion suites before this ratchet landed. PR #10341 adds the accepted public deferred-install and same-home credential continuation boundary for Hermes and Deep Agents Code; existing per-file budgets remain unchanged. PR #13055 adds five explicitly approved assertions for the native Deep Agents Code OpenRouter request in the existing hosted OpenRouter target. PR #13293 consolidates native-local cases into the existing OpenClaw switching owner. Removing duplicated deterministic metadata and direct mock requests lowers suite totals while retaining real authenticated and sentinel agent turns, lifecycle, model switching, credential isolation and sibling denial. Per-file transitive counts include existing imported helpers; no live files or suite assertion points are added.\n\nPR #13596 adds four assertions to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds.", "schemaVersion": 1, "issue": 10934, "epic": 10920, @@ -13,30 +13,30 @@ }, "limits": { "testFileCount": 77, - "liveFileCount": 186, + "liveFileCount": 187, "direct": { - "expectCalls": 1249, - "matcherAssertions": 1228, - "nodeAssertions": 104, - "namedAssertionHelpers": 417, + "expectCalls": 1270, + "matcherAssertions": 1250, + "nodeAssertions": 108, + "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, - "objectFieldAssertions": 168, - "assertionPoints": 1967, - "generatedProbeBlocks": 87, - "generatedProbeConditions": 216 + "objectFieldAssertions": 184, + "assertionPoints": 2014, + "generatedProbeBlocks": 84, + "generatedProbeConditions": 206 }, "unique": { - "expectCalls": 1672, - "matcherAssertions": 1646, - "nodeAssertions": 127, - "namedAssertionHelpers": 662, + "expectCalls": 1698, + "matcherAssertions": 1673, + "nodeAssertions": 131, + "namedAssertionHelpers": 668, "failCalls": 1, - "throwGuards": 526, - "objectFieldAssertions": 245, - "assertionPoints": 3207, - "generatedProbeBlocks": 209, - "generatedProbeConditions": 721 + "throwGuards": 531, + "objectFieldAssertions": 266, + "assertionPoints": 3270, + "generatedProbeBlocks": 208, + "generatedProbeConditions": 713 }, "fileMetricOrder": [ "directExpectCalls", @@ -48,7 +48,7 @@ "files": { "test/e2e/live/agent-turn-latency.test.ts": [15,15,15,26,1], "test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts": [11,33,12,55,4], - "test/e2e/live/bootstrap-install-smoke.test.ts": [0,0,14,29,3], + "test/e2e/live/bootstrap-install-smoke.test.ts": [0,0,14,28,3], "test/e2e/live/brave-search.test.ts": [5,10,5,10,1], "test/e2e/live/brev-workspace-cleanup.test.ts": [0,0,0,1,0], "test/e2e/live/channels-add-remove.test.ts": [40,90,40,92,0], @@ -60,30 +60,30 @@ "test/e2e/live/dashboard-remote-bind.test.ts": [16,14,16,16,3], "test/e2e/live/deferred-onboarding.test.ts": [12,14,12,14,0], "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], - "test/e2e/live/double-onboard.test.ts": [42,47,42,47,0], + "test/e2e/live/double-onboard.test.ts": [46,51,46,51,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], - "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], - "test/e2e/live/gpu-double-onboard.test.ts": [20,23,20,23,0], + "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], + "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], - "test/e2e/live/hermes-discord.test.ts": [10,22,17,61,14], + "test/e2e/live/hermes-discord.test.ts": [9,19,16,58,12], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,76,1], + "test/e2e/live/hermes-inference-switch.test.ts": [40,48,58,87,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], - "test/e2e/live/inference-routing-provider-smoke.test.ts": [18,22,29,41,2], - "test/e2e/live/inference-routing.test.ts": [36,51,48,89,15], + "test/e2e/live/inference-routing-provider-smoke.test.ts": [27,40,38,59,1], + "test/e2e/live/inference-routing.test.ts": [48,70,60,108,15], "test/e2e/live/issue-4434-tui-unreachable-inference.test.ts": [28,32,28,32,0], "test/e2e/live/issue-4462-scope-upgrade-approval.test.ts": [8,18,8,18,0], "test/e2e/live/issue-9880-staging-launchable.test.ts": [0,0,0,0,0], "test/e2e/live/jetson-nvmap-gpu.test.ts": [37,50,37,50,4], "test/e2e/live/launch-readiness-lease-acceptance.test.ts": [6,6,6,10,6], - "test/e2e/live/launchable-smoke.test.ts": [14,29,14,29,3], + "test/e2e/live/launchable-smoke.test.ts": [14,28,14,28,3], "test/e2e/live/llama-cpp-generic-gpu.test.ts": [17,35,33,61,2], - "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,13,28,0], + "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,12,25,0], "test/e2e/live/managed-image-multiarch-startup.test.ts": [1,1,1,7,0], - "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,40,77,15], + "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,39,81,16], "test/e2e/live/mcp-bridge.test.ts": [39,138,193,518,46], "test/e2e/live/messaging-compatible-endpoint.test.ts": [13,19,13,28,2], "test/e2e/live/messaging-providers.test.ts": [0,11,6,51,11], @@ -92,21 +92,21 @@ "test/e2e/live/network-policy.test.ts": [18,19,18,19,1], "test/e2e/live/ollama-auth-proxy.test.ts": [21,29,21,29,0], "test/e2e/live/onboard-policy-preset-sequencing.test.ts": [7,7,7,7,1], - "test/e2e/live/onboard-repair.test.ts": [21,25,21,25,0], + "test/e2e/live/onboard-repair.test.ts": [22,26,22,26,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], - "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,51,1], + "test/e2e/live/openclaw-inference-switch.test.ts": [35,48,62,93,3], "test/e2e/live/openclaw-skill-cli.test.ts": [10,14,10,14,1], "test/e2e/live/openclaw-slack-pairing.test.ts": [11,18,26,84,10], "test/e2e/live/openshell-credential-generation-window.test.ts": [42,92,43,112,18], "test/e2e/live/openshell-gateway-auth-source-contract.test.ts": [0,0,16,28,2], "test/e2e/live/openshell-gateway-upgrade.test.ts": [6,15,6,26,6], "test/e2e/live/overlayfs-autofix.test.ts": [22,25,22,28,2], - "test/e2e/live/pi-agent-qualification.test.ts": [29,36,29,52,4], + "test/e2e/live/pi-agent-qualification.test.ts": [39,46,39,62,4], "test/e2e/live/podman-cpu-lifecycle.test.ts": [35,57,48,92,1], "test/e2e/live/podman-portable-uninstall.test.ts": [37,36,50,71,3], "test/e2e/live/portable-cpu-delegation-proof.test.ts": [0,22,0,22,0], - "test/e2e/live/portable-profile-rootless-linux.test.ts": [0,72,0,78,2], + "test/e2e/live/portable-profile-rootless-linux.test.ts": [0,76,0,82,2], "test/e2e/live/rebuild-hermes.test.ts": [2,8,9,47,6], "test/e2e/live/rebuild-openclaw.test.ts": [2,7,2,26,1], "test/e2e/live/registry-targets.test.ts": [2,4,5,24,0], diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index ed72b443852..d368b18c70b 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -22,7 +22,7 @@ const { createInferenceSelectionValidationHelpers, }: typeof import("./onboard/inference-selection-validation") = require("./onboard/inference-selection-validation"); const { - applyCloudFallbackSelection, + abortFailedNimStartup, clearNimContainerBeforeRetry, createNvidiaFeaturedModelSession, createRemoteModelValidator, @@ -62,7 +62,7 @@ const { ensureOllamaLoopbackSystemdOverride, }: typeof import("./onboard/ollama-systemd") = require("./onboard/ollama-systemd"); const { - createCompatibleEndpointSmoke, + createCompatibleEndpointSmoke: createSmoke, buildCompatibleEndpointSandboxSmokeCommand, buildCompatibleEndpointSandboxSmokeScript, verifyCompatibleEndpointSandboxSmoke, @@ -673,7 +673,7 @@ const { }); const sandboxExec = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); -const compatibleSmoke = createCompatibleEndpointSmoke(runOpenshell, sandboxExec, redact); +const compatibleSmoke = createSmoke(runOpenshell, sandboxExec, redact, registry.getSandbox); const { isSandboxReady, parseSandboxStatus, getSandboxStateFromOutputs } = gatewayState; const waitForSandboxReady = sandboxReadinessTracing.createCliSandboxReadyWaiter({ @@ -1671,10 +1671,7 @@ async function handleNimLocalSelection( const localGpu = requireValue(gpu, "GPU details are required for local NIM model selection"); const { models, usableMemoryMB } = nim.getNimModelOptions(localGpu); if (models.length === 0) { - console.log(` No NIM model fits ${usableMemoryMB} MB. Falling back to cloud API.`); - applyCloudFallbackSelection(state, REMOTE_PROVIDER_CONFIG.build); - state.assertRouteCompatible?.(); - return "selected"; + throw new Error(`No Local NVIDIA NIM model fits ${usableMemoryMB} MB of usable GPU memory.`); } let sel; @@ -1769,17 +1766,14 @@ async function handleNimLocalSelection( console.log(" Starting NIM container..."); const nimContainerNameLocal = nim.containerName(GATEWAY_NAME); assertSelectionMutationAuthority(state, "start the local NIM runtime"); - state.nimContainer = nim.startNimContainerByName(nimContainerNameLocal, catalogModel, undefined, { + const startedNim = nim.startNimContainerByName(nimContainerNameLocal, catalogModel, undefined, { ngcApiKey: ngcApiKey ?? undefined, }); + state.nimContainer = startedNim.name; console.log(" Waiting for NIM to become healthy..."); if (!nim.waitForNimHealth(undefined, undefined, { container: nimContainerNameLocal })) { - nim.stopNimContainerByNameOrThrow(nimContainerNameLocal); - console.error(" NIM failed to start. Falling back to cloud API."); - applyCloudFallbackSelection(state, REMOTE_PROVIDER_CONFIG.build); - state.assertRouteCompatible?.(); - return "selected"; + abortFailedNimStartup(state, startedNim, nim.stopNimContainerByIdOrThrow); } state.model = nim.adoptServedModelId(catalogModel); @@ -1792,11 +1786,11 @@ async function handleNimLocalSelection( null, ); if (validation.retry === "selection" || validation.retry === "model") { - clearNimContainerBeforeRetry(state); + clearNimContainerBeforeRetry(state, nim.stopNimContainerByNameOrThrow); return "retry-selection"; } if (!validation.ok) { - clearNimContainerBeforeRetry(state); + clearNimContainerBeforeRetry(state, nim.stopNimContainerByNameOrThrow); return "retry-selection"; } if (validation.api !== "openai-completions") { @@ -2029,8 +2023,7 @@ async function handleRemoteProviderSelection( log: (message) => console.log(message), }); if (bedrockSelection.action === "retry-selection") { - console.log(" Returning to provider selection."); - console.log(""); + console.log(" Returning to provider selection.\n"); return "retry-selection"; } if (bedrockSelection.action === "selected") { @@ -2058,6 +2051,7 @@ async function handleRemoteProviderSelection( }, { resolveProviderCredential, + getSandbox: registry.getSandbox, readRecordedInferenceRoute: (name) => readRecordedInferenceRoute(name, args.recoverySessionId), readRecordedProviderEndpoints, @@ -2272,72 +2266,70 @@ function getSetupNimDeps(): SetupNimDeps { } const setupNim = setupNimFlow.createSetupNim(getSetupNimDeps()); // ── Step 4: Inference provider ─────────────────────────────────── -function getSetupInferenceDeps(): SetupInferenceDeps { - return { - checkGatewayRouteCompatibility, - withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, - withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, - step, - getGatewayName: () => GATEWAY_NAME, - resolveOllamaOwnershipGateway: gatewayBinding.resolveSandboxGatewayName, - runOpenshell, - inferenceRouteMutator, - inferenceRouteObserver, - upsertProvider, - verifyInferenceRoute, - verifyOnboardInferenceSmoke, - isNonInteractive, - updateSandbox: registry.reserveSandboxInferenceRoute, - getSandbox: registry.getSandbox, - unloadOllamaModels, - hermesProviderAuth, - getHermesToolGatewayBroker, - ...onboardProviders.setupInferenceProviderDeps(runOpenshell), - normalizeHermesAuthMethod, - resolveHermesNousApiKey, - checkHermesProviderStoreReachable, - hermesAuthMethodLabel, - hermesConstants: { - HERMES_NOUS_API_KEY_CREDENTIAL_ENV, - HERMES_AUTH_METHOD_API_KEY, - HERMES_AUTH_METHOD_OAUTH, - }, - requireValue, - redact, - compactText, - REMOTE_PROVIDER_CONFIG, - hydrateCredentialEnv, - promptValidationRecovery, - classifyApplyFailure, - localInferenceTimeoutSecs: LOCAL_INFERENCE_TIMEOUT_SECS, - bedrockRuntimeOnboard, - openrouterRuntimeOnboard, - validateLocalProvider, - getLocalProviderHealthCheck, - getLocalProviderBaseUrl, - run, - vllmLocalCredentialEnv: VLLM_LOCAL_CREDENTIAL_ENV, - shouldFrontOllamaWithProxy, - ensureOllamaAuthProxy, - isProxyHealthy, - getOllamaProxyToken, - persistAndProbeOllamaProxy, - localInference, - ollamaProxyCredentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, - isRoutedInferenceProvider, - reconcileModelRouter, - routedInference, - log: (message: string) => console.log(message), - error: (message: string) => console.error(message), - exitProcess: (code: number): never => process.exit(code), - }; -} +const getSetupInferenceDeps = (): SetupInferenceDeps => ({ + checkGatewayRouteCompatibility, + withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, + withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, + step, + getGatewayName: () => GATEWAY_NAME, + runOpenshell, + inferenceRouteMutator, + inferenceRouteObserver, + upsertProvider, + recordMigratedProviderCredential: registration.recordMigratedProviderCredential, + verifyInferenceRoute, + verifyOnboardInferenceSmoke, + isNonInteractive, + updateSandbox: registry.reserveSandboxInferenceRoute, + getSandbox: registry.getSandbox, + listSandboxes: registry.listSandboxes, + unloadOllamaModels, + hermesProviderAuth, + getHermesToolGatewayBroker, + ...onboardProviders.setupInferenceProviderDeps(runOpenshell), + normalizeHermesAuthMethod, + resolveHermesNousApiKey, + checkHermesProviderStoreReachable, + hermesAuthMethodLabel, + hermesConstants: { + HERMES_NOUS_API_KEY_CREDENTIAL_ENV, + HERMES_AUTH_METHOD_API_KEY, + HERMES_AUTH_METHOD_OAUTH, + }, + requireValue, + redact, + compactText, + REMOTE_PROVIDER_CONFIG, + hydrateCredentialEnv, + promptValidationRecovery, + classifyApplyFailure, + localInferenceTimeoutSecs: LOCAL_INFERENCE_TIMEOUT_SECS, + bedrockRuntimeOnboard, + openrouterRuntimeOnboard, + validateLocalProvider, + getLocalProviderHealthCheck, + getLocalProviderBaseUrl, + run, + vllmLocalCredentialEnv: VLLM_LOCAL_CREDENTIAL_ENV, + shouldFrontOllamaWithProxy, + ensureOllamaAuthProxy, + isProxyHealthy, + getOllamaProxyToken, + persistAndProbeOllamaProxy, + localInference, + ollamaProxyCredentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, + isRoutedInferenceProvider, + reconcileModelRouter, + routedInference, + log: (message: string) => console.log(message), + error: (message: string) => console.error(message), + exitProcess: (code: number): never => process.exit(code), +}); export type SetupInferenceDeps = import("./onboard/setup-inference").SetupInferenceDeps; export type SetupInference = import("./onboard/setup-inference").SetupInference; function createSetupInference(overrides: Partial = {}): SetupInference { return setupInferenceFactory.createSetupInference(getSetupInferenceDeps(), overrides); } -const setupInference = createSetupInference(); const MESSAGING_CHANNELS = listChannels(); const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxCreateIntentResolver< AgentDefinition | null, @@ -2408,15 +2400,15 @@ const setupMessagingChannels = messagingChannelSetup.createSetupMessagingChannel prompt, }); const configSyncDeps = { getProviderSelectionConfig, sandboxCommandExecutor: sandboxExec }; -const syncNemoClawConfigInSandbox = createNemoClawConfigSync(configSyncDeps); const configureOpenclawSandbox = openclawSetup.createConfigureOpenclawSandbox({ - syncNemoClawConfigInSandbox, + syncNemoClawConfigInSandbox: createNemoClawConfigSync(configSyncDeps), }); const setupOpenclaw = openclawSetup.createOpenclawSetup({ step, agentProductName, configureOpenclawSandbox, restartNativeGateway: restartNativeGatewayForInitialSetup, + waitForGatewayStartup: finalizationHandlerDeps.waitForStartedOpenclawGatewayProcess, shouldRestartNativeGateway: isRoutedInferenceProvider, }); const { @@ -2460,6 +2452,7 @@ const { mergePolicyMessagingChannels, preparePolicyPresetResumeSelection, presetsCheckboxSelector, + resetPolicyTierSelection, resolveSandboxBaselinePolicy, selectPolicyTier, selectTierPresetsAndAccess, @@ -2480,8 +2473,9 @@ const { waitForSandboxControlPlaneReady: finalizationHandlerDeps.waitForSandboxControlPlaneReady, parsePolicyPresetEnv, env: process.env, + pendingSelection: onboardSession.createPendingPolicySelectionStore(registry.getSandbox), }); - +const setupInference = createSetupInference({ resolvePolicyTier: selectPolicyTier }); const startRecordedStep = onboardRuntimeBoundary.startRecordedStep.bind(onboardRuntimeBoundary); const recordStepComplete = onboardRuntimeBoundary.recordStepComplete.bind(onboardRuntimeBoundary); const recordStepRejected = onboardRuntimeBoundary.recordStepRejected.bind(onboardRuntimeBoundary); @@ -2489,7 +2483,6 @@ const recordStepSkipped = onboardRuntimeBoundary.recordStepSkipped.bind(onboardR const recordStepFailed = onboardRuntimeBoundary.recordStepFailed.bind(onboardRuntimeBoundary); const recordStateSkipped = onboardRuntimeBoundary.recordStateSkipped.bind(onboardRuntimeBoundary); const recordRepairEvent = onboardRuntimeBoundary.recordRepairEvent.bind(onboardRuntimeBoundary); -/** Run readiness gates while the authoritative rebuild target is still intact. */ async function preflightAuthoritativeRebuildTarget( opts: import("./onboard/authoritative-rebuild-target").AuthoritativeRebuildPreflightOptions, ): Promise { @@ -2541,7 +2534,6 @@ async function preflightAuthoritativeRebuildTarget( _preflightDashboardPort = previous.dashboardPort; } } - const wrappedOnboard = onboardEntryOptions.wrapOnboard(runOnboard, onboardSession); const onboard = onboardSessionBootstrap.wrapOnboardDeferredExit(wrappedOnboard); async function runOnboard(opts: OnboardOptions = {}): Promise { @@ -2921,6 +2913,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { import("./resources-cmd").ResourceProfile >({ resumeProvider: { + getSandbox: registry.getSandbox, isNonInteractive, isRoutedInferenceProvider, providerExistsInGateway, @@ -3151,11 +3144,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recordStepFailed, skippedStepMessage, }), - ensureAgentDashboardForward: (name, selectedAgent) => + ensureAgentDashboardForward: (name, selectedAgent, revalidateIdentity) => ensureFinalizationAgentDashboardForward( name, selectedAgent, - undefined, + revalidateIdentity, hermesApiPortReservationScope, ), persistDashboardPort: (name, port) => @@ -3206,8 +3199,14 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { getChatUiUrl: () => process.env.CHAT_UI_URL || `http://127.0.0.1:${DASHBOARD_PORT}`, buildVerifyChain: (chatUiUrl, name) => buildAgentVerifyChain(chatUiUrl, name, agent), verifyDeployment: async (name, chain) => { - const recordedSandbox = registry.getSandbox(name); const verifyDeploymentModule: typeof import("./verify-deployment") = require("./verify-deployment"); + const inference = verifyDeploymentModule.onboardInferenceVerificationContext( + name, + GATEWAY_NAME, + agent?.name ?? "openclaw", + liveFinalFlowContext, + registry.getSandbox(name), + ); return verifyDeploymentModule.verifyDeployment( name, chain, @@ -3219,13 +3218,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { providerExistsInGateway: (providerName: string) => providerExistsInGateway(providerName), probeInferenceInvocation: () => - verifyDeploymentModule.probeOnboardInferenceInvocation({ - ...recordedSandbox, - ...liveFinalFlowContext, - sandboxName: name, - gatewayName: GATEWAY_NAME, - agentName: agent?.name, - }), + verifyDeploymentModule.probeOnboardInferenceInvocation(inference.invocation), }, { diagnoseCustomOpenClawRuntime: @@ -3233,7 +3226,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { liveFinalFlowContext.fromDockerfile, agent?.name, ), - inferenceRouteContext: recordedSandbox ?? liveFinalFlowContext, + inferenceRouteContext: inference.route, }, ); }, @@ -3271,6 +3264,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { onboardSessionBootstrap.shouldPreserveIncompleteOnboardSession(error); throw error; } finally { + resetPolicyTierSelection(); const telemetryGatewayName = GATEWAY_NAME; try { await hermesApiPortReservationScope.release(); @@ -3382,6 +3376,7 @@ module.exports = { MESSAGING_CHANNELS, selectOnboardAgent, setupNim, + handleNimLocalSelection, providerNameToOptionKey: providerKey, readRecordedProvider, readRecordedModel, diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 103482af51a..f318be8b6d0 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -1,24 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; -import type { - OllamaModelCleanupOwner, - OllamaModelHolder, -} from "../inference/ollama/model-ownership"; -import type { OllamaUnloadResult } from "../inference/ollama/proxy"; -import type { SandboxEntry } from "../state/registry"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { createProviderReviewDeps, createSetupInference, - releaseSupersededOllamaModel, type SetupInferenceDeps, } from "./setup-inference"; @@ -28,435 +17,36 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); -function createOllamaCleanupHarness( - options: { - peers?: readonly SandboxEntry[]; - useProductionPeerSource?: boolean; - useProductionDiscovery?: boolean; - activeSandboxNames?: ReadonlySet; - discovery?: SetupInferenceDeps["discoverActiveOllamaSandboxNames"]; - pendingModels?: readonly string[]; - unloadResult?: OllamaUnloadResult; - } = {}, -) { - let pendingModels = [...(options.pendingModels ?? [])]; - const localInference = { - loadPersistedOllamaHost: vi.fn(() => "127.0.0.1"), - loadPendingOllamaModelCleanup: vi.fn((_owner: OllamaModelCleanupOwner) => pendingModels), - persistPendingOllamaModelCleanup: vi.fn( - (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { - pendingModels = [...new Set([...pendingModels, ...models])]; - }, - ), - clearPendingOllamaModelCleanup: vi.fn( - (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { - pendingModels = pendingModels.filter((model) => !models.includes(model)); - }, - ), - clearPersistedOllamaHostIfUnused: vi.fn(), - }; - const unloadOllamaModels = vi.fn( - () => - options.unloadResult ?? { - ok: true, - outcome: "released" as const, - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - }, - ); - const discoverActiveOllamaSandboxNames = vi.fn( - options.discovery ?? - (() => ({ - ok: true as const, - activeSandboxNames: options.activeSandboxNames ?? new Set(), - gatewayChecks: [], - })), - ); - const deps = { - localInference, - ...(options.useProductionPeerSource - ? {} - : { listOllamaModelOwnershipPeers: () => options.peers ?? [] }), - ...(!options.useProductionDiscovery ? { discoverActiveOllamaSandboxNames } : {}), - unloadOllamaModels, - withOllamaModelOwnershipLock: (operation: () => void) => operation(), - } as unknown as SetupInferenceDeps; - return { deps, localInference, unloadOllamaModels, discoverActiveOllamaSandboxNames }; -} - -const previousLocalOllamaRoute: OllamaModelHolder = { - name: "alpha", - provider: "ollama-local", - model: "qwen2.5:1.5b", - endpointUrl: "http://127.0.0.1:11434", - gatewayName: "nemoclaw-32677", - gatewayPort: 32677, - lifecycleGeneration: "generation-alpha", - lifecycleLiveIdentityFingerprint: "a".repeat(64), -}; - -function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): void { - releaseSupersededOllamaModel( - previous, - "nvidia-prod", - "nvidia/test-model", - "https://integrate.api.nvidia.com/v1", - { ok: true }, - deps, - ); -} - -describe("releaseSupersededOllamaModel", () => { - it("preserves the host target for a stopped peer after releasing its model", () => { - const stoppedPeer = { - name: "stopped-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - endpointUrl: "http://127.0.0.1:11434", - gatewayName: "nemoclaw-32678", - gatewayPort: 32678, - } as unknown as SandboxEntry; - const harness = createOllamaCleanupHarness({ peers: [stoppedPeer] }); - - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).toHaveBeenCalledExactlyOnceWith( - [stoppedPeer], - ); - }); - - it("releases the target model before unrelated gateway discovery for receipt retirement", () => { - const unrelatedPeer = { - name: "unrelated-peer", - provider: "ollama-local", - model: "llama3.2:1b", - endpointUrl: null, - gatewayName: "unavailable-gateway", - } as unknown as SandboxEntry; - const discovery = vi.fn((owners: readonly OllamaModelHolder[]) => - owners.some((owner) => owner.model === "llama3.2:1b") - ? { ok: false as const, message: "unrelated gateway unavailable" } - : { ok: true as const, activeSandboxNames: new Set(), gatewayChecks: [] }, - ); - const harness = createOllamaCleanupHarness({ peers: [unrelatedPeer], discovery }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(discovery).toHaveBeenCalledTimes(2); - expect(discovery.mock.calls[0]?.[0]).toEqual([]); - expect(discovery.mock.calls[1]?.[0]).toEqual([unrelatedPeer]); - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining("host route receipt was retained"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("preserves the model and host receipt while a matching live peer owns it", () => { - const activePeer = { - name: "active-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - endpointUrl: null, - gatewayName: "peer-gateway-port", - } as unknown as SandboxEntry; - const harness = createOllamaCleanupHarness({ - peers: [activePeer], - activeSandboxNames: new Set([activePeer.name]), - }); - - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - }); - - it("uses Ollama peer records from other gateway roots by default", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-peer-roots-")); - vi.stubEnv("HOME", home); - const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(gatewayRoot, { recursive: true }); - const peer: SandboxEntry = { - name: "active-peer", +describe("recorded Pi local inference route", () => { + it("rejects a changed selection before invoking a provider or gateway", async () => { + const getSandbox = vi.fn(() => ({ + agent: "pi", provider: "ollama-local", - model: "qwen2.5:1.5b", - gatewayName: "nemoclaw-32665", - gatewayPort: 32665, - endpointUrl: "http://127.0.0.1:11434", - }; - fs.writeFileSync( - path.join(gatewayRoot, "sandboxes.json"), - JSON.stringify({ - defaultSandbox: null, - defaultSelectionRevision: 1, - sandboxes: { "active-peer": peer }, - }), - ); - const harness = createOllamaCleanupHarness({ - useProductionPeerSource: true, - activeSandboxNames: new Set([peer.name]), - }); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); - expect(harness.discoverActiveOllamaSandboxNames.mock.calls[0]?.[0]).toEqual([ - expect.objectContaining({ name: "active-peer", gatewayName: "nemoclaw-32665" }), - ]); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - } finally { - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("uses the injected phase capture for cross-gateway discovery", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); - vi.stubEnv("HOME", home); - const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(gatewayRoot, { recursive: true }); - const peer: SandboxEntry = { - name: "active-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - gatewayName: "nemoclaw-32665", - gatewayPort: 32665, - endpointUrl: "http://127.0.0.1:11434", - }; - fs.writeFileSync( - path.join(gatewayRoot, "sandboxes.json"), - JSON.stringify({ - defaultSandbox: null, - defaultSelectionRevision: 1, - sandboxes: { "active-peer": peer }, - }), - ); - const harness = createOllamaCleanupHarness({ - useProductionPeerSource: true, - useProductionDiscovery: true, - }); - const captureOllamaOwnershipPhases = vi.fn(() => ({ - status: 0, - output: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", + model: "qwen3:8b", + endpointUrl: "http://host.openshell.internal:11435/v1", + createdAt: "2026-09-01T00:00:00Z", })); - const deps = harness.deps as SetupInferenceDeps; - deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; - deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName!; - - try { - releaseToNvidia(previousLocalOllamaRoute, deps); - - expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( - "nemoclaw-32665", - process.env, - ); - expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - } finally { - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("fails closed and records retry state when a successful inventory omits a matching peer", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-omitted-inventory-")); - vi.stubEnv("HOME", home); - const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(gatewayRoot, { recursive: true }); - const peer: SandboxEntry = { - name: "stale-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - gatewayName: "nemoclaw-32665", - gatewayPort: 32665, - endpointUrl: "http://127.0.0.1:11434", - }; - fs.writeFileSync( - path.join(gatewayRoot, "sandboxes.json"), - JSON.stringify({ - defaultSandbox: null, - defaultSelectionRevision: 1, - sandboxes: { "stale-peer": peer }, - }), - ); - const harness = createOllamaCleanupHarness({ - useProductionPeerSource: true, - useProductionDiscovery: true, - }); - const captureOllamaOwnershipPhases = vi.fn(() => ({ - status: 0, - output: "NAME CREATED PHASE", - })); - const deps = harness.deps as SetupInferenceDeps; - deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; - deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName ?? "default"; - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( - "nemoclaw-32665", - process.env, - ); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); - } finally { - warning.mockRestore(); - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("records a failed ownership probe for retry, then unloads only after a safe retry", () => { - const discovery = vi - .fn>() - .mockReturnValueOnce({ ok: false, message: "gateway unavailable" }) - .mockReturnValueOnce({ ok: true, activeSandboxNames: new Set(), gatewayChecks: [] }); - const harness = createOllamaCleanupHarness({ discovery }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); - - releaseToNvidia({ ...previousLocalOllamaRoute, provider: "nvidia-prod" }, harness.deps); - - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( - expect.objectContaining({ - name: "alpha", - gatewayName: "nemoclaw-32677", - gatewayPort: 32677, - lifecycleGeneration: "generation-alpha", - lifecycleLiveIdentityFingerprint: "a".repeat(64), - }), - ["qwen2.5:1.5b"], - ); - } finally { - warning.mockRestore(); - } - }); - - it("requires manual recovery when ownership failure cannot be recorded for retry", () => { - const discovery = vi.fn>( - () => ({ ok: false, message: "gateway unavailable" }), - ); - const harness = createOllamaCleanupHarness({ discovery }); - harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { - throw new Error( - "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", - ); - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia( - { - ...previousLocalOllamaRoute, - lifecycleGeneration: undefined, - lifecycleLiveIdentityFingerprint: undefined, - }, - harness.deps, - ); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining( - "Manually verify that no active matching sandbox owns the model before releasing only qwen2.5:1.5b", - ), - ); - expect(warning).not.toHaveBeenCalledWith( - expect.stringContaining("Re-run onboarding to retry only"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("keeps the retry record when unloading the superseded model fails", () => { - const harness = createOllamaCleanupHarness({ - unloadResult: { - ok: false, - outcome: "still-resident", - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - }, - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(harness.localInference.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining("Re-run onboarding or destroy 'alpha' to retry only"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("does not probe or warn when the selected route still owns the same Ollama model", () => { - const harness = createOllamaCleanupHarness(); - - releaseSupersededOllamaModel( - previousLocalOllamaRoute, - "ollama-local", - "qwen2.5:1.5b", - "http://127.0.0.1:11434", - { ok: true }, - harness.deps, - ); - - expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - }); - - it("does not probe unrelated routes when there is no Ollama cleanup retry", () => { - const harness = createOllamaCleanupHarness({ - peers: [{ name: "ollama-peer", provider: "ollama-local", model: "qwen2.5:1.5b" }], - }); - - releaseToNvidia( - { name: "alpha", provider: "nvidia-prod", model: "nvidia/model" }, - harness.deps, - ); + const requireNativeProviderPolicy = vi.fn(); + const setup = createSetupInference({ + getGatewayName: () => "nemoclaw", + getSandbox, + withSandboxMutationLock: (_name: string, operation: () => unknown) => operation(), + requireNativeProviderPolicy, + } as unknown as SetupInferenceDeps); - expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + await expect( + setup( + "alpha", + "different-model", + "ollama-local", + "http://host.openshell.internal:11435/v1", + null, + null, + [], + { agentName: "pi", preserveLegacyPiSharedLocalRoute: true }, + ), + ).rejects.toThrow("Recorded Pi shared local inference route changed before setup"); + expect(requireNativeProviderPolicy).not.toHaveBeenCalled(); }); }); @@ -631,6 +221,99 @@ describe("createProviderReviewDeps", () => { }); }); +describe("Personal custom endpoint onboarding", () => { + it("resolves Personal before provider setup and keeps the shared route", async () => { + const events: string[] = []; + const createProvider = vi.fn(); + const attachProvider = vi.fn(); + const upsertProvider = vi.fn(async () => { + events.push("shared-provider"); + return { ok: true }; + }); + const inferenceRouteMutator = { + setInferenceRoute: vi.fn(async () => ({ ok: true as const })), + }; + const setup = createSetupInference({ + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => { + events.push("sandbox-lock"); + return await operation(); + }, + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => { + events.push("gateway-lock"); + return await operation(); + }, + step: vi.fn(), + getGatewayName: () => "nemoclaw", + getSandbox: () => null, + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + inferenceRouteMutator, + inferenceRouteObserver: { + observeInferenceRoute: vi.fn(async () => ({ + ok: true as const, + value: { state: "unconfigured" as const }, + })), + }, + updateSandbox: vi.fn(() => true), + upsertProvider, + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke: vi.fn(), + resolveEndpointHost: vi.fn(async () => [{ address: "93.184.216.34", family: 4 as const }]), + resolvePolicyTier: async () => { + events.push("policy-tier"); + return "personal"; + }, + bedrockRuntimeOnboard: { + setupBedrockRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + openrouterRuntimeOnboard: { + setupOpenRouterRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + isNonInteractive: () => false, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + providerAdapter: { createProvider, attachProvider } as unknown as OpenShellProviderAdapter, + REMOTE_PROVIDER_CONFIG: { + custom: { + label: "Compatible endpoint", + providerName: "compatible-endpoint", + providerType: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + endpointUrl: "https://api.example/v1", + helpUrl: null, + modelMode: "input", + defaultModel: "model-a", + }, + }, + hydrateCredentialEnv: vi.fn(() => "secret"), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + } as unknown as SetupInferenceDeps); + + await expect( + setup( + "alpha", + "model-a", + "compatible-endpoint", + "https://api.example/v1", + "COMPATIBLE_API_KEY", + null, + [], + { skipHostInferenceSmoke: true }, + ), + ).resolves.toEqual({ ok: true }); + + expect(events).toEqual(["policy-tier", "sandbox-lock", "gateway-lock", "shared-provider"]); + expect(createProvider).not.toHaveBeenCalled(); + expect(attachProvider).not.toHaveBeenCalled(); + expect(inferenceRouteMutator.setInferenceRoute).toHaveBeenCalledOnce(); + }); +}); + describe("native NVIDIA onboarding", () => { it("reserves the logical route with an attached-provider receipt and no shared route mutation", async () => { const importProviderProfile = vi.fn(async () => ({ ok: true as const })); @@ -660,22 +343,7 @@ describe("native NVIDIA onboarding", () => { createProvider, } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); - const events: string[] = []; - const updateSandbox = vi.fn(() => { - events.push("route-published"); - return true; - }); - const unloadOllamaModels = vi.fn(() => { - events.push("unload"); - return { - ok: true as const, - outcome: "released" as const, - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - }; - }); + const updateSandbox = vi.fn(() => true); const setNativeNvidiaProviderAuthority = vi.fn(() => true); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); @@ -690,28 +358,7 @@ describe("native NVIDIA onboarding", () => { runOpenshell, updateSandbox, setNativeNvidiaProviderAuthority, - getSandbox: () => previousLocalOllamaRoute, - localInference: { - loadPersistedOllamaHost: () => "127.0.0.1", - loadPendingOllamaModelCleanup: () => [], - persistPendingOllamaModelCleanup: vi.fn(), - clearPendingOllamaModelCleanup: vi.fn(), - clearPersistedOllamaHostIfUnused: vi.fn(), - }, - listOllamaModelOwnershipPeers: () => [], - discoverActiveOllamaSandboxNames: () => ({ - ok: true as const, - activeSandboxNames: new Set(), - gatewayChecks: [], - }), - unloadOllamaModels, - withOllamaModelOwnershipLock: (operation: () => void) => operation(), - withOllamaModelOwnershipTransaction: async (operation: () => Promise | T) => { - events.push("ownership-transaction-start"); - const result = await operation(); - events.push("ownership-transaction-end"); - return result; - }, + getSandbox: () => null, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute, verifyOnboardInferenceSmoke, @@ -776,10 +423,6 @@ describe("native NVIDIA onboarding", () => { }, }), ); - expect(events.indexOf("route-published")).toBeLessThan(events.indexOf("unload")); - expect(events[0]).toBe("ownership-transaction-start"); - expect(events.at(-1)).toBe("ownership-transaction-end"); - expect(unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("onboarding-gateway", { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", @@ -875,7 +518,13 @@ describe("native NVIDIA onboarding", () => { expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); }); - it("reuses a gateway-owned provider for a fresh second sandbox", async () => { + it.each(["fresh", "recorded"])("reuses native NVIDIA without a host key (%s)", async (state) => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "provider-id", + }; const importProviderProfile = vi.fn(async () => ({ ok: true as const })); const getProvider = vi.fn(async () => ({ ok: true, @@ -890,6 +539,7 @@ describe("native NVIDIA onboarding", () => { const createProvider = vi.fn(); const updateProvider = vi.fn(); const updateSandbox = vi.fn(() => true); + const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); const setupInference = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => @@ -900,16 +550,18 @@ describe("native NVIDIA onboarding", () => { getGatewayName: () => "onboarding-gateway", runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), updateSandbox, - getSandbox: () => null, - getNativeNvidiaProviderAuthority: () => ({ - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "provider-id", - }), + getSandbox: () => + state === "recorded" + ? { + name: "second", + provider: "nvidia-prod", + nativeNvidiaProviderAttachment: receipt, + } + : null, + getNativeNvidiaProviderAuthority: () => receipt, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), - verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + verifyOnboardInferenceSmoke, isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, providerAdapter: { @@ -920,6 +572,7 @@ describe("native NVIDIA onboarding", () => { updateProvider, } as unknown as OpenShellProviderAdapter, hydrateCredentialEnv: vi.fn(() => null), + localInference: {}, redact: (value: string) => value, compactText: (value: string) => value, log: vi.fn(), @@ -940,13 +593,14 @@ describe("native NVIDIA onboarding", () => { [], { revalidateSandboxIdentity: () => undefined, - reuseGatewayCredentialWithoutLocalKey: true, + reuseGatewayCredentialWithoutLocalKey: state === "fresh", }, ), ).resolves.toEqual({ ok: true }); expect(createProvider).not.toHaveBeenCalled(); expect(updateProvider).not.toHaveBeenCalled(); + expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); expect(updateSandbox).toHaveBeenCalledWith( "second", expect.objectContaining({ @@ -955,14 +609,21 @@ describe("native NVIDIA onboarding", () => { ); }); - it("requires recreation instead of recording a receipt for a legacy NVIDIA sandbox", async () => { - const providerAdapter = { - ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true, value: undefined })), - importProviderProfile: vi.fn(), - getProvider: vi.fn(), - updateProvider: vi.fn(), - } as unknown as OpenShellProviderAdapter; - const updateSandbox = vi.fn(() => true); + it.each([ + [ + "only the registry records ownership", + false, + /only the NemoClaw registry record for sandbox 'alpha'.*'nemoclaw alpha destroy'/su, + ], + ["the gateway records ownership", true, /complete uninstall without --keep-openshell/u], + ])("explains a missing NVIDIA provider when %s", async (_case, gatewayOwned, message) => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + } as const; + const createProvider = vi.fn(); const setupInference = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => @@ -970,16 +631,29 @@ describe("native NVIDIA onboarding", () => { withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), step: vi.fn(), - getGatewayName: () => "nemoclaw", + getGatewayName: () => "onboarding-gateway", runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), - updateSandbox, - getSandbox: () => ({ name: "alpha", provider: "nvidia-prod" }) as never, + updateSandbox: vi.fn(() => true), + getSandbox: () => ({ + name: "alpha", + provider: "nvidia-prod", + nativeNvidiaProviderAttachment: receipt, + }), + getNativeNvidiaProviderAuthority: () => (gatewayOwned ? receipt : undefined), upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(async () => undefined), isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, - providerAdapter, + providerAdapter: { + ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true, value: undefined })), + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + })), + createProvider, + } as unknown as OpenShellProviderAdapter, hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), redact: (value: string) => value, compactText: (value: string) => value, @@ -997,159 +671,40 @@ describe("native NVIDIA onboarding", () => { "nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY", + null, + [], + { revalidateSandboxIdentity: () => undefined }, ), - ).rejects.toThrow(/Recreate this beta sandbox.*does not migrate existing beta sandboxes/u); - - expect(providerAdapter.importProviderProfile).not.toHaveBeenCalled(); - expect(updateSandbox).not.toHaveBeenCalled(); + ).rejects.toThrow(message); + expect(createProvider).not.toHaveBeenCalled(); }); -}); -describe("concurrent Ollama ownership transactions", () => { - it("serializes route publication before superseded-model release (#12677)", async () => { - const events: string[] = []; - const registry = new Map([ - [ - "alpha", - { - name: "alpha", - provider: "ollama-local", - model: "qwen2.5:1.5b", - endpointUrl: "http://127.0.0.1:11434/v1", - gatewayName: "gateway-alpha", - }, - ], - [ - "beta", - { - name: "beta", - provider: "compatible-endpoint", - model: "previous-model", - endpointUrl: "https://previous.example/v1", - gatewayName: "gateway-beta", - }, - ], - ]); - let signalBetaRouteStarted!: () => void; - let signalAlphaRouteStarted!: () => void; - let releaseBetaRoute!: () => void; - let signalAlphaQueued!: () => void; - const betaRouteStarted = new Promise((resolve) => { - signalBetaRouteStarted = resolve; - }); - const alphaRouteStarted = new Promise((resolve) => { - signalAlphaRouteStarted = resolve; - }); - const allowBetaRouteToFinish = new Promise((resolve) => { - releaseBetaRoute = resolve; - }); - const alphaQueuedForTransaction = new Promise((resolve) => { - signalAlphaQueued = resolve; - }); - const transactionLabels = ["gateway-beta", "gateway-alpha"]; - let transactionTail = Promise.resolve(); - let transactionCalls = 0; - const withOwnershipTransaction: NonNullable< - SetupInferenceDeps["withOllamaModelOwnershipTransaction"] - > = async (operation: () => Promise | T): Promise => { - transactionCalls += 1; - const label = transactionLabels[transactionCalls - 1] ?? "unknown"; - events.push(`transaction-request:${label}`); - [() => undefined, signalAlphaQueued][transactionCalls - 1]?.(); - const previous = transactionTail; - let release!: () => void; - transactionTail = new Promise((resolve) => { - release = resolve; - }); - await previous; - events.push(`transaction-enter:${label}`); - try { - const result = await operation(); - events.push(`transaction-exit:${label}`); - return result; - } finally { - release(); - } - }; - const signalRouteStarted: Record void> = { - "gateway-alpha": signalAlphaRouteStarted, - "gateway-beta": signalBetaRouteStarted, - }; - const inferenceRouteMutator: SetupInferenceDeps["inferenceRouteMutator"] = { - setInferenceRoute: async (request) => { - const gateway = request.target.gatewayName; - events.push(`route-start:${gateway}`); - signalRouteStarted[gateway]?.(); - await (gateway === "gateway-beta" ? allowBetaRouteToFinish : Promise.resolve()); - events.push(`route-finished:${gateway}`); - return { ok: true }; - }, - }; - const updateSandbox: SetupInferenceDeps["updateSandbox"] = (name, route) => { - const previous = registry.get(name); - registry.set(name, { ...previous, ...route, name } as OllamaModelHolder); - events.push(`registry-published:${name}`); - return true; - }; - const listOllamaModelOwnershipPeers = vi.fn(() => { - events.push("peer-discovery"); - return [...registry.values()]; - }); - const unloadOllamaModels = vi.fn(() => { - events.push("unload"); - return { - ok: true as const, - outcome: "released" as const, - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - }; - }); - const localInference = { - loadPersistedOllamaHost: () => "127.0.0.1", - loadPendingOllamaModelCleanup: () => [], - persistPendingOllamaModelCleanup: vi.fn(), - clearPendingOllamaModelCleanup: vi.fn(), - clearPersistedOllamaHostIfUnused: vi.fn(), - }; - const deps = { + it("requires recreation instead of recording a receipt for a legacy NVIDIA sandbox", async () => { + const providerAdapter = { + ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true, value: undefined })), + importProviderProfile: vi.fn(), + getProvider: vi.fn(), + updateProvider: vi.fn(), + } as unknown as OpenShellProviderAdapter; + const updateSandbox = vi.fn(() => true); + const setupInference = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), step: vi.fn(), - getGatewayName: () => "gateway-default", + getGatewayName: () => "nemoclaw", runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), - inferenceRouteMutator, - inferenceRouteObserver: { - observeInferenceRoute: vi.fn(async () => ({ ok: true as const })), - } as unknown as SetupInferenceDeps["inferenceRouteObserver"], updateSandbox, - getSandbox: (name: string) => registry.get(name) ?? null, - listOllamaModelOwnershipPeers, - discoverActiveOllamaSandboxNames: (owners: readonly OllamaModelHolder[]) => ({ - ok: true as const, - activeSandboxNames: new Set(owners.map((owner) => owner.name)), - gatewayChecks: [], - }), - localInference, - unloadOllamaModels, - withOllamaModelOwnershipLock: (operation: () => void) => operation(), - withOllamaModelOwnershipTransaction: withOwnershipTransaction, - upsertProvider: vi.fn(async () => ({ ok: true as const })), - bedrockRuntimeOnboard: { - setupBedrockRuntimeInference: vi.fn(async () => ({ handled: false as const })), - }, - openrouterRuntimeOnboard: { - setupOpenRouterRuntimeInference: vi.fn(async () => ({ handled: false as const })), - }, + getSandbox: () => ({ name: "alpha", provider: "nvidia-prod" }) as never, + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(async () => undefined), isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, - hydrateCredentialEnv: vi.fn(() => "test-compatible-api-key"), + providerAdapter, + hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), redact: (value: string) => value, compactText: (value: string) => value, log: vi.fn(), @@ -1157,75 +712,19 @@ describe("concurrent Ollama ownership transactions", () => { exitProcess: vi.fn((code: number): never => { throw new Error(`exit ${code}`); }), - localInferenceTimeoutSecs: 30, - vllmLocalCredentialEnv: "VLLM_API_KEY", - ollamaProxyCredentialEnv: "NEMOCLAW_OLLAMA_PROXY_TOKEN", - isRoutedInferenceProvider: () => false, - } as unknown as SetupInferenceDeps; - const setupAlpha = createSetupInference(deps); - const setupBeta = createSetupInference(deps); - const betaSwitch = setupBeta( - "beta", - "qwen2.5:1.5b", - "compatible-endpoint", - "http://127.0.0.1:11434/v1", - "COMPATIBLE_API_KEY", - null, - [], - { - gatewayName: "gateway-beta", - endpointPinnedAddresses: ["127.0.0.1"], - skipHostInferenceSmoke: true, - }, - ); + } as unknown as SetupInferenceDeps); - await betaRouteStarted; - const alphaSwitch = setupAlpha( - "alpha", - "other-model", - "compatible-endpoint", - "https://api.example.test/v1", - "COMPATIBLE_API_KEY", - null, - [], - { - gatewayName: "gateway-alpha", - endpointPinnedAddresses: ["93.184.216.34"], - skipHostInferenceSmoke: true, - }, - ); - const alphaOrder = await Promise.race([ - alphaQueuedForTransaction.then(() => "queued"), - alphaRouteStarted.then(() => "route-started"), - ]); - releaseBetaRoute(); - await expect(Promise.all([alphaSwitch, betaSwitch])).resolves.toEqual([ - { ok: true }, - { ok: true }, - ]); + await expect( + setupInference( + "alpha", + "nvidia/nemotron-3-super-120b-a12b", + "nvidia-prod", + "https://integrate.api.nvidia.com/v1", + "NVIDIA_INFERENCE_API_KEY", + ), + ).rejects.toThrow(/Recreate this beta sandbox.*does not migrate existing beta sandboxes/u); - expect(alphaOrder).toBe("queued"); - expect(events).toContain("registry-published:beta"); - expect(events).toContain("route-start:gateway-alpha"); - expect(events).toContain("transaction-exit:gateway-beta"); - expect(events).toContain("transaction-exit:gateway-alpha"); - expect(events).toContain("peer-discovery"); - expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( - events.indexOf("route-start:gateway-alpha"), - ); - expect(events.indexOf("registry-published:beta")).toBeLessThan( - events.indexOf("route-start:gateway-alpha"), - ); - expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( - events.indexOf("peer-discovery"), - ); - expect(events.indexOf("registry-published:alpha")).toBeLessThan( - events.indexOf("peer-discovery"), - ); - expect(events.indexOf("peer-discovery")).toBeLessThan( - events.indexOf("transaction-exit:gateway-alpha"), - ); - expect(listOllamaModelOwnershipPeers).toHaveBeenCalledOnce(); - expect(unloadOllamaModels).not.toHaveBeenCalled(); - }, 20_000); + expect(providerAdapter.importProviderProfile).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index b955fd0286d..93806f2d1a4 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -1,14 +1,34 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { + NativeLocalProvider, + NativeLocalProviderAttachment, +} from "../inference/native-local/contract"; +import { + requireNativeProviderPolicy, + normalizeNativeLocalProviderAttachment, + isPersistedPiSharedLocalInferenceRoute, + usesNativeLocalInference, + usesNativeLocalInferenceForAgent, + prepareNativeLocalSelection, + retireUnreservedNativeLocalProvider, + gatewayReachableCompatibleEndpointUrl, +} from "./inference-providers"; import { hostedNativeProvider, usesNativeHermesEndpoint, + customNativeCredentialEnv, + resolveCustomNativeApi, } from "../inference/native-provider/hosted"; import { requireHostedProviderAttachment } from "../inference/native-provider/hosted-attachment"; -import { prepareHostedNativeProvider } from "../inference/native-provider/setup"; +import { + isHostedCustomEndpoint, + prepareHostedNativeProvider, + prepareCustomNativeProvider, + usesCustomNativeOnboarding, +} from "../inference/native-provider/setup"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; - import type { OpenShellGatewayLifecycle } from "../adapters/openshell/gateway-lifecycle"; import { canonicalEndpoint } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; @@ -39,16 +59,11 @@ import { } from "../inference/native-nvidia"; import { clearPendingOllamaModelCleanup, - discoverOllamaModelOwnership, isLocalOllamaRouteOwner, - listOllamaModelOwnershipPeersAcrossGatewayRoots, loadPendingOllamaModelCleanup, - matchingOllamaModelPeers, - type OllamaActiveOwnershipDiscoveryFn, type OllamaModelHolder, - type OllamaOwnershipPhaseCapture, persistPendingOllamaModelCleanup, - supersededOllamaModelWithActivePeers, + supersededOllamaModel, } from "../inference/ollama/model-ownership"; import { getOllamaProxyToken, @@ -60,12 +75,12 @@ import { } from "../inference/ollama/proxy"; import { assertNoOpenShellGatewayEndpointOverride, - captureSandboxPhasesForGateway, scopeGatewayOpenshellArgs, type OpenShellGatewayEndpointEnvironment, -} from "../adapters/openshell/runtime"; +} from "../adapters/openshell/gateway-scope"; import type { withSandboxMutationLock } from "../state/mcp-lifecycle-lock"; import type { Session } from "../state/onboard-session"; +import type { SandboxEntry } from "../state/registry/types"; import { createSandboxHostLocalInferenceProvenance } from "../state/registry/host-local-inference"; import { withRoutedInferencePortLock, @@ -220,8 +235,17 @@ type ProviderBranchDeps = Pick< Pick; export type SetupInferenceDeps = ProviderBranchDeps & { + recordMigratedProviderCredential?: ( + name: string, + credentialEnv: string, + persistedValue: string, + revalidateSandboxIdentity?: (operation: string) => void, + ) => void; + requireNativeProviderPolicy?: typeof requireNativeProviderPolicy; /** Injectable resolver for resumed custom-endpoint SSRF preflight tests. */ resolveEndpointHost?: EndpointDnsLookupFn; + /** Resolve the current onboarding policy tier before provider mutation. */ + resolvePolicyTier?: () => Promise; /** Exact private endpoint hosts trusted by the operator (tests may inject this). */ trustedPrivateEndpointHosts?: readonly string[]; checkGatewayRouteCompatibility: CurrentGatewayRouteCompatibilityCheck; @@ -250,12 +274,10 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // #9110 optional GPU-release seams; omitted by test literals that build deps // by hand, so every read below must stay optional-chained. getSandbox?: typeof import("../state/registry").getSandbox; - listOllamaModelOwnershipPeers?: () => readonly OllamaModelHolder[]; - discoverActiveOllamaSandboxNames?: OllamaActiveOwnershipDiscoveryFn; - captureOllamaOwnershipPhases?: OllamaOwnershipPhaseCapture; - resolveOllamaOwnershipGateway?: (peer: OllamaModelHolder) => string; - environment?: NodeJS.ProcessEnv; listSandboxes?: typeof import("../state/registry").listSandboxes; + getNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").getNativeLocalProviderAuthority; + setNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").setNativeLocalProviderAuthority; + clearNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").clearNativeLocalProviderAuthority; getNativeHostedProviderAuthority?: typeof import("../state/registry").getNativeHostedProviderAuthority; setNativeHostedProviderAuthority?: typeof import("../state/registry").setNativeHostedProviderAuthority; getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; @@ -534,7 +556,7 @@ export type SetupInference = ( * the route is committed by this point, so GPU cleanup must never change the * result or the exit code. */ -export function releaseSupersededOllamaModel( +function releaseSupersededOllamaModel( previous: OllamaModelHolder | null, nextProvider: string, nextModel: string, @@ -545,7 +567,7 @@ export function releaseSupersededOllamaModel( ): void { // A reselection retry left the recorded route untouched, so the sandbox // still owns its model. - if (!previous || result.retry) return; + if (!previous || result.retry || result.stagedNativeLocalRecreation) return; let authorityRefusal: unknown; let cleanupWarning: string | null = null; let attemptedModels: readonly string[] = []; @@ -559,7 +581,7 @@ export function releaseSupersededOllamaModel( const persistRetry = (): string | null => { if (attemptedModels.length === 0) return null; try { - persistPending(previous, attemptedModels); + persistPending(previous.name, attemptedModels); return null; } catch (error) { return (error instanceof Error ? error.message : String(error)) @@ -570,85 +592,34 @@ export function releaseSupersededOllamaModel( try { const withOwnershipLock = deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; withOwnershipLock(() => { + const peers = deps.listSandboxes?.().sandboxes ?? []; const selectedHost = deps.localInference.loadPersistedOllamaHost?.() ?? null; - const nextRoute = { provider: nextProvider, model: nextModel, endpointUrl: nextEndpointUrl }; - const previousOwnsOllama = isLocalOllamaRouteOwner(previous, selectedHost); - // This is only a retry candidate. A successful live probe below is still - // required before the model can be unloaded. - const retryCandidate = previousOwnsOllama - ? supersededOllamaModelWithActivePeers(previous, nextRoute, [], new Set(), selectedHost) - : null; - attemptedModels = retryCandidate ? [retryCandidate] : []; - const pending = loadPending(previous); - attemptedModels = [...new Set([...attemptedModels, ...pending])]; - if (!retryCandidate && pending.length === 0) return; - - const peers = ( - deps.listOllamaModelOwnershipPeers ?? listOllamaModelOwnershipPeersAcrossGatewayRoots - )(); - const ollamaRouteCandidates = peers.filter((peer) => - isLocalOllamaRouteOwner(peer, selectedHost), - ); - const environment = deps.environment ?? process.env; - const captureOwnershipPhases: OllamaOwnershipPhaseCapture = - deps.captureOllamaOwnershipPhases ?? captureSandboxPhasesForGateway; - const discoverPeers = (owners: readonly OllamaModelHolder[]) => - deps.discoverActiveOllamaSandboxNames - ? deps.discoverActiveOllamaSandboxNames(owners, environment) - : discoverOllamaModelOwnership(owners, environment, captureOwnershipPhases, { - resolvePersistedSandboxOwnershipGateway: deps.resolveOllamaOwnershipGateway, - }); - // A different model cannot keep one of the models being released resident. - // Discover only matching owners before unloading so unrelated gateways do - // not delay cleanup; all-route discovery is reserved for receipt retirement. - const modelOwners = [ - ...new Set( - attemptedModels.flatMap((model) => - matchingOllamaModelPeers( - { ...previous, provider: "ollama-local", model, endpointUrl: null }, - ollamaRouteCandidates, - selectedHost, - ), - ), - ), - ]; - const discovery = discoverPeers(modelOwners); - if (!discovery.ok) { - pendingRecordFailure = persistRetry(); - const retryMessage = pendingRecordFailure - ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}. Manually verify that no active matching sandbox owns the model before releasing only ${attemptedModels.join(", ")} from the local Ollama host.` - : attemptedModels.length > 0 - ? `Re-run onboarding to retry only: ${attemptedModels.join(", ")}.` - : "The Ollama host receipt was left unchanged."; - cleanupWarning = - ` Warning: NemoClaw could not verify Ollama model ownership for '${previous.name}': ` + - `${discovery.message}. No model was unloaded; the new inference route remains active. ${retryMessage}`; - return; - } - const superseded = previousOwnsOllama - ? supersededOllamaModelWithActivePeers( - previous, - nextRoute, - peers, - discovery.activeSandboxNames, - selectedHost, - discovery.activePeers, - ) - : null; - const retryablePending = pending.filter((model) => { - return !!supersededOllamaModelWithActivePeers( - { ...previous, provider: "ollama-local", model, endpointUrl: null }, + const nextRoute = { + provider: nextProvider, + model: nextModel, + endpointUrl: nextEndpointUrl, + }; + const superseded = supersededOllamaModel(previous, nextRoute, peers, selectedHost); + const pending = loadPending(previous.name); + const retryablePending = pending.filter((model) => + supersededOllamaModel( + { + name: previous.name, + provider: "ollama-local", + model, + endpointUrl: null, + }, nextRoute, peers, - discovery.activeSandboxNames, selectedHost, - discovery.activePeers, - ); - }); + ), + ); attemptedModels = [...new Set([...(superseded ? [superseded] : []), ...retryablePending])]; - const retireRouteCandidate = - previousOwnsOllama && !isLocalOllamaRouteOwner(nextRoute, selectedHost); - if (attemptedModels.length === 0 && !retireRouteCandidate) return; + const retireRoute = + isLocalOllamaRouteOwner(previous, selectedHost) && + !isLocalOllamaRouteOwner(nextRoute, selectedHost) && + !peers.some((peer) => isLocalOllamaRouteOwner(peer, selectedHost)); + if (attemptedModels.length === 0 && !retireRoute) return; try { revalidateSandboxIdentity?.("release the superseded Ollama model"); } catch (error) { @@ -680,7 +651,7 @@ export function releaseSupersededOllamaModel( ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}. Manually release only ${attemptedModels.join(", ")} at ${cleanup.endpoint}.` : `Re-run onboarding or destroy '${previous.name}' to retry only: ${attemptedModels.join(", ")}.`); } else { - clearPending(previous, attemptedModels); + clearPending(previous.name, attemptedModels); } } catch (error) { if (pendingRecordFailure) pendingRecordFailure = persistRetry(); @@ -695,29 +666,9 @@ export function releaseSupersededOllamaModel( : `Re-run onboarding or destroy '${previous.name}' to retry only the recorded models: ${attemptedModels.join(", ")}.`); } } - const pendingAfterCleanup = loadPending(previous); - if (retireRouteCandidate && !cleanupWarning && pendingAfterCleanup.length === 0) { - const routeOwnerDiscovery = - modelOwners.length === ollamaRouteCandidates.length - ? discovery - : discoverPeers(ollamaRouteCandidates); - if (!routeOwnerDiscovery.ok) { - cleanupWarning = - ` Warning: Ollama cleanup for '${previous.name}' was scoped to verified model owners, ` + - "but the host route receipt was retained because other Ollama gateway owners could not be verified."; - } else { - const activeOllamaPeerRoutes = peers.filter( - (peer) => - (routeOwnerDiscovery.activePeers - ? routeOwnerDiscovery.activePeers.has(peer) - : routeOwnerDiscovery.activeSandboxNames.has(peer.name)) && - isLocalOllamaRouteOwner(peer, selectedHost), - ); - if (activeOllamaPeerRoutes.length === 0) { - // Stopped registry owners still need the shared host target if they restart. - deps.localInference.clearPersistedOllamaHostIfUnused?.(ollamaRouteCandidates); - } - } + const pendingAfterCleanup = loadPending(previous.name); + if (retireRoute && !cleanupWarning && pendingAfterCleanup.length === 0) { + deps.localInference.clearPersistedOllamaHostIfUnused?.(peers); } }); } catch (error) { @@ -736,12 +687,406 @@ export function releaseSupersededOllamaModel( if (authorityRefusal) throw authorityRefusal; } +async function rejectNativeLocalSetupFailure(input: { + error: unknown; + attachment?: NativeLocalProviderAttachment; + reservationEntered: boolean; + sandboxName: string | null; + gatewayName: string; + deps: SetupInferenceDeps; +}): Promise { + if ( + input.attachment && + !input.reservationEntered && + input.deps.providerAdapter && + input.sandboxName + ) { + try { + await retireUnreservedNativeLocalProvider({ + adapter: input.deps.providerAdapter, + expected: input.attachment, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + getSandbox: input.deps.getSandbox, + clearAuthority: input.deps.clearNativeLocalProviderAuthority, + }); + } catch (cleanupError) { + throw new Error( + `${hostLocalInferenceFailureDetail(input.error, input.deps)}\n Native local provider cleanup was not confirmed: ${hostLocalInferenceFailureDetail(cleanupError, input.deps)}`, + { cause: input.error }, + ); + } + } + if (input.error instanceof HostLocalInferenceBranchExit) + return input.deps.exitProcess(input.error.code); + throw input.error; +} + +async function cleanupUnreservedNativeLocalAfterHostFailure(input: { + selectingNativeLocal: boolean; + attachment?: NativeLocalProviderAttachment; + reservationEntered: boolean; + sandboxName: string | null; + gatewayName: string; + deps: SetupInferenceDeps; +}): Promise { + if ( + !input.selectingNativeLocal || + !input.attachment || + input.reservationEntered || + !input.sandboxName || + !input.deps.providerAdapter + ) + return; + try { + await retireUnreservedNativeLocalProvider({ + adapter: input.deps.providerAdapter, + expected: input.attachment, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + getSandbox: input.deps.getSandbox, + clearAuthority: input.deps.clearNativeLocalProviderAuthority, + }); + } catch (cleanupError) { + input.deps.error( + ` Native local provider cleanup was not confirmed: ${hostLocalInferenceFailureDetail(cleanupError, input.deps)}`, + ); + } +} + +async function resolveHostedSelection(input: { + provider: string; + endpointUrl: string | null; + sandboxName: string | null; + gatewayName: string; + deps: SetupInferenceDeps; + options: ProviderInferenceSetupOptions; +}) { + const { provider, endpointUrl, sandboxName, gatewayName, deps, options } = input; + const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; + const freshCustomSelection = Boolean( + sandboxName && + isHostedCustomEndpoint(provider, endpointUrl) && + !recordedSandbox?.nativeHostedProviderAttachment?.custom && + (!recordedSandbox || recordedSandbox.pendingRouteReservation), + ); + const resolvePolicyTier = options.resolvePolicyTier ?? deps.resolvePolicyTier; + const policyTier = freshCustomSelection ? await resolvePolicyTier?.() : undefined; + const custom = usesCustomNativeOnboarding( + provider, + endpointUrl, + sandboxName, + recordedSandbox, + policyTier, + ); + const authority = + provider === "hermes-provider" + ? ((recordedSandbox?.provider === provider + ? requireHostedProviderAttachment( + recordedSandbox.nativeHostedProviderAttachment, + provider, + ) + : undefined) ?? + deps.getNativeHostedProviderAuthority?.(gatewayName, provider, endpointUrl || undefined)) + : undefined; + return { + authority, + recordedSandbox, + custom, + selected: + custom || + (Boolean(hostedNativeProvider(provider)) && + (provider !== "hermes-provider" || usesNativeHermesEndpoint(endpointUrl, authority))), + }; +} + +async function prepareSelectedHostedProvider(input: { + provider: string; + gatewayName: string; + sandboxName: string | null; + credentialEnv: string | null; + reuseExistingCredential: boolean; + deps: SetupInferenceDeps; +}): Promise<{ + attachment: NativeProviderAttachment; + retainedCredential: boolean; +}> { + const { provider, gatewayName, sandboxName, credentialEnv, reuseExistingCredential, deps } = + input; + if ( + !deps.providerAdapter || + !deps.getNativeHostedProviderAuthority || + !deps.setNativeHostedProviderAuthority + ) { + throw new Error("Native hosted setup is missing its provider adapter or ownership store."); + } + const hosted = hostedNativeProvider(provider); + if (!hosted) throw new Error("Native hosted provider is unsupported."); + const credentialValue = deps.hydrateCredentialEnv(credentialEnv || hosted.credentialEnv) || null; + const attachment = await prepareHostedNativeProvider({ + provider, + adapter: deps.providerAdapter, + gatewayName, + credentialValue, + reuseExistingCredential, + recordedSandbox: sandboxName ? deps.getSandbox?.(sandboxName) : null, + readAuthority: deps.getNativeHostedProviderAuthority, + writeAuthority: deps.setNativeHostedProviderAuthority, + }); + return { attachment, retainedCredential: !credentialValue }; +} + +async function gatewayRouteCompatible(input: { + provider: string; + model: string; + endpointUrl: string | null; + credentialEnv: string | null; + gatewayName: string; + sandboxName: string | null; + preferredInferenceApi: ProviderInferenceSetupOptions["preferredInferenceApi"]; + nativeHostedSelection: boolean; + selectingNativeLocal: boolean; + deps: SetupInferenceDeps; +}): Promise { + const { + provider, + model, + endpointUrl, + credentialEnv, + gatewayName, + sandboxName, + preferredInferenceApi, + nativeHostedSelection, + selectingNativeLocal, + deps, + } = input; + if (isNativeNvidiaProvider(provider) || nativeHostedSelection || selectingNativeLocal) + return true; + const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ + target: { kind: "named", gatewayName }, + }); + if (!observedRoute.ok) { + deps.error( + ` Cannot reconcile the current OpenShell inference selection on gateway '${gatewayName}' before onboarding mutation: ${observedRoute.error.message}`, + ); + return false; + } + const compatibility = deps.checkGatewayRouteCompatibility({ + gatewayName, + sandboxName, + route: { + provider, + model, + endpointUrl, + credentialEnv, + preferredInferenceApi: preferredInferenceApi ?? null, + }, + }); + if (compatibility.ok) return true; + if (!isAdvisoryGatewayRouteConflict(compatibility)) { + deps.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); + return false; + } + deps.error(` ${formatGatewayRouteImpactWarning(compatibility)}`); + return true; +} + +function shouldStageGatewayRouteAfterBackup( + provider: string, + source: SandboxEntry | null | undefined, + hostLocalSelection: ProviderInferenceSetupOptions["hostLocalInference"], + credentialEnv: string | null, + ollamaProxyCredentialEnv: string, +): boolean { + return Boolean( + inferenceProviders.isRemoteProviderName(provider) && + !hostLocalSelection && + credentialEnv !== ollamaProxyCredentialEnv && + source && + !isLocalOllamaRouteOwner(source) && + source.pendingRouteReservation !== true, + ); +} + +function createGatewayRouteStager(input: { + deps: SetupInferenceDeps; + provider: string; + sandboxName: string | null; + gatewayName: string; + endpointUrl: string | null; + credentialEnv: string | null; + hostLocalSelection: ProviderInferenceSetupOptions["hostLocalInference"]; + options: ProviderInferenceSetupOptions; + revalidateSandboxIdentity?: (operation: string) => void; +}) { + let stagedRoute: Parameters[0] | null = null; + const stagedProviderUpserts: Array< + () => Promise>> + > = []; + const publishedSourceForStaging = (): SandboxEntry | null => { + const source = + input.sandboxName && input.options.deferPublishedRouteReservation + ? input.deps.getSandbox?.(input.sandboxName) + : null; + return shouldStageGatewayRouteAfterBackup( + input.provider, + source, + input.hostLocalSelection, + input.credentialEnv, + input.deps.ollamaProxyCredentialEnv, + ) + ? (source ?? null) + : null; + }; + const mutator: OpenShellInferenceRouteMutator = { + setInferenceRoute: (request) => { + input.revalidateSandboxIdentity?.("change the OpenShell inference provider route"); + if (publishedSourceForStaging()) { + stagedRoute = request; + return Promise.resolve({ ok: true }); + } + return input.deps.inferenceRouteMutator.setInferenceRoute(request); + }, + }; + return { + mutator, + reusePublishedProvider: (providerName: string) => { + const source = publishedSourceForStaging(); + if (!source || source.provider !== providerName) return null; + if ( + (source.endpointUrl ?? null) !== input.endpointUrl || + (source.credentialEnv ?? null) !== input.credentialEnv || + (source.preferredInferenceApi ?? null) !== (input.options.preferredInferenceApi ?? null) + ) { + return { + ok: false, + status: 1, + message: + `Cannot change provider '${providerName}' endpoint, credential binding, or ` + + `inference API while recreating the published sandbox. Re-run this model ` + + `change with the source sandbox's provider configuration.`, + }; + } + return { ok: true }; + }, + stageProviderUpsert: ( + upsert: () => Promise>>, + ) => { + if (!publishedSourceForStaging()) return false; + stagedProviderUpserts.push(upsert); + return true; + }, + hasStagedRoute: () => stagedRoute !== null, + successResult: (): SetupInferenceResult => { + if (!stagedRoute) { + if (stagedProviderUpserts.length > 0) + throw new Error("The staged inference provider has no deferred route to publish."); + return { ok: true }; + } + const request = stagedRoute; + const providerUpserts = [...stagedProviderUpserts]; + return { + ok: true, + // The sandbox create phase holds the gateway-route lock through backup, + // route publication, and reservation. Acquiring it here would deadlock. + deferredInferenceRoute: async (reserve) => { + input.revalidateSandboxIdentity?.("apply the backed-up sandbox inference route"); + const target = { + kind: "named" as const, + gatewayName: input.gatewayName, + }; + const before = await input.deps.inferenceRouteObserver.observeInferenceRoute({ + target, + }); + if (!before.ok || before.value.state !== "configured") { + throw new Error( + `Cannot capture the published inference route on gateway '${input.gatewayName}' before replacement.`, + ); + } + const sourceRoute = before.value.route; + try { + for (const upsert of providerUpserts) { + const providerResult = await upsert(); + if (!providerResult.ok) + throw new Error( + providerResult.message ?? + `Cannot update the inference provider on gateway '${input.gatewayName}'.`, + ); + } + const result = await input.deps.inferenceRouteMutator.setInferenceRoute(request); + if (!result.ok) throw new Error(result.error.message); + const after = await input.deps.inferenceRouteObserver.observeInferenceRoute({ + target, + }); + if ( + !after.ok || + after.value.state !== "configured" || + after.value.route.provider !== request.route.provider || + after.value.route.model !== request.route.model + ) { + throw new Error("The replacement inference route was not verified."); + } + reserve(); + } catch (error) { + const live = await input.deps.inferenceRouteObserver.observeInferenceRoute({ + target, + }); + if ( + !live.ok || + live.value.state !== "configured" || + ((live.value.route.provider !== sourceRoute.provider || + live.value.route.model !== sourceRoute.model) && + (live.value.route.provider !== request.route.provider || + live.value.route.model !== request.route.model)) + ) { + throw new Error( + "Cannot safely restore the published inference route after replacement failed; inspect the live gateway before retrying.", + { cause: error }, + ); + } + if ( + live.value.route.provider !== sourceRoute.provider || + live.value.route.model !== sourceRoute.model + ) { + input.revalidateSandboxIdentity?.("restore the published sandbox inference route"); + const restored = await input.deps.inferenceRouteMutator.setInferenceRoute({ + ...request, + route: sourceRoute, + }); + if (!restored.ok) { + throw new Error( + `Cannot restore the published inference route: ${restored.error.message}`, + { cause: error }, + ); + } + const confirmed = await input.deps.inferenceRouteObserver.observeInferenceRoute({ + target, + }); + if ( + !confirmed.ok || + confirmed.value.state !== "configured" || + confirmed.value.route.provider !== sourceRoute.provider || + confirmed.value.route.model !== sourceRoute.model + ) { + throw new Error( + "Cannot verify restoration of the published inference route; inspect the live gateway before retrying.", + { cause: error }, + ); + } + } + throw error; + } + }, + }; + }, + }; +} + export function createSetupInference( defaults: SetupInferenceDeps, overrides: Partial = {}, ): SetupInference { const deps: SetupInferenceDeps = { ...defaults, ...overrides }; - const { inferenceRouteMutator } = deps; return async function setupInferenceWithDeps( sandboxName: string | null, @@ -757,6 +1102,17 @@ export function createSetupInference( const gatewayName = options.gatewayName ?? deps.getGatewayName(); const endpointSource = options.endpointSource === undefined ? "onboard" : options.endpointSource; + const policyTierResolver = options.resolvePolicyTier ?? deps.resolvePolicyTier; + let policyTierResolution: Promise | undefined; + const resolvePolicyTier = policyTierResolver + ? () => (policyTierResolution ??= policyTierResolver()) + : undefined; + const hostedSelectionOptions = resolvePolicyTier ? { ...options, resolvePolicyTier } : options; + if (sandboxName && isHostedCustomEndpoint(provider, endpointUrl)) { + await resolvePolicyTier?.(); + } + let selectingNativeLocal = false; + let nativeLocalAgent: string | null | undefined; const routedProvider = deps.isRoutedInferenceProvider?.(provider) === true; const usesBedrockRuntimeAdapter = provider === "compatible-anthropic-endpoint" && isBedrockRuntimeEndpoint(endpointUrl); @@ -778,55 +1134,39 @@ export function createSetupInference( ); return deps.exitProcess(1); } - const recordedSandbox = - provider === "hermes-provider" && sandboxName ? deps.getSandbox?.(sandboxName) : null; - const hermesAuthority = - provider === "hermes-provider" - ? ((recordedSandbox?.provider === provider - ? requireHostedProviderAttachment( - recordedSandbox.nativeHostedProviderAttachment, - provider, - ) - : undefined) ?? - deps.getNativeHostedProviderAuthority?.( - gatewayName, - provider, - endpointUrl || undefined, - )) - : undefined; - const nativeHostedSelection = - hostedNativeProvider(provider) && - (provider !== "hermes-provider" || - usesNativeHermesEndpoint(endpointUrl, hermesAuthority)); - if (!isNativeNvidiaProvider(provider) && !nativeHostedSelection) { - const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ - target: { kind: "named", gatewayName }, - }); - if (!observedRoute.ok) { - deps.error( - ` Cannot reconcile the current OpenShell inference selection on gateway '${gatewayName}' before onboarding mutation: ${observedRoute.error.message}`, - ); - return deps.exitProcess(1); - } - const compatibility = deps.checkGatewayRouteCompatibility({ + const { + authority: hermesAuthority, + selected: nativeHostedSelection, + custom: nativeCustomSelection, + recordedSandbox, + } = await resolveHostedSelection({ + provider, + endpointUrl, + sandboxName, + gatewayName, + deps, + options: hostedSelectionOptions, + }); + const selectedInferenceApi = resolveCustomNativeApi( + provider, + options.preferredInferenceApi, + nativeCustomSelection, + ); + if ( + !(await gatewayRouteCompatible({ + provider, + model, + endpointUrl, + credentialEnv, gatewayName, sandboxName, - route: { - provider, - model, - endpointUrl, - credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, - }, - }); - if (!compatibility.ok) { - if (!isAdvisoryGatewayRouteConflict(compatibility)) { - deps.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); - return deps.exitProcess(1); - } - deps.error(` ${formatGatewayRouteImpactWarning(compatibility)}`); - } - } + preferredInferenceApi: selectedInferenceApi, + nativeHostedSelection, + selectingNativeLocal, + deps, + })) + ) + return deps.exitProcess(1); deps.step(4, 8, "Setting up inference provider"); let endpointPinnedAddresses = options.endpointPinnedAddresses; let endpointTrustedPrivateCapability = options.endpointTrustedPrivateCapability; @@ -874,32 +1214,62 @@ export function createSetupInference( revalidateSandboxIdentity?.("change the OpenShell inference provider route"); return runExactGatewayOpenshell(...args); }; - const revalidatingInferenceRouteMutator: OpenShellInferenceRouteMutator = { - setInferenceRoute: (request) => { - revalidateSandboxIdentity?.("change the OpenShell inference provider route"); - return inferenceRouteMutator.setInferenceRoute(request); - }, - }; + const hostLocalSelection = options.hostLocalInference; + const routeStager = createGatewayRouteStager({ + deps, + provider, + sandboxName, + gatewayName, + endpointUrl, + credentialEnv, + hostLocalSelection, + options, + revalidateSandboxIdentity, + }); + const revalidatingInferenceRouteMutator = routeStager.mutator; let hostLocalRoute: HostLocalInferenceStartupRoute | null = null; let hostLocalGatewayMutation: HostLocalInferenceGatewayMutation | null = null; let hostLocalRollbackAttempted = false; let hostLocalRegistryPublicationEntered = false; const hostLocalProviderErrors: string[] = []; - const hostLocalSelection = options.hostLocalInference; let routeReserved = false; + let nativeLocalReservationEntered = false; let hostLocalInferenceReceipt: string | null = null; let hostLocalInferenceProvenance: | import("../state/registry/types").SandboxEntry["hostLocalInferenceProvenance"] | undefined; let hostLocalInferenceGatewayPortAuthority: number | undefined; let hostLocalInferenceRuntimeProviderId: string | undefined; + let nativeLocalRecreationSource: SandboxEntry | undefined; + let nativeLocalProviderAttachment: NativeLocalProviderAttachment | undefined; let nativeHostedEndpoint: string | undefined; let nativeHostedCredentialEnv: string | undefined; let nativeHostedProviderAttachment: NativeProviderAttachment | undefined; let retainedNativeHostedCredential = false; let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { - if (routeReserved) return true; + if (routeReserved || nativeLocalRecreationSource) return true; + // Local Ollama cleanup runs after this reservation; it must not unload + // a model while its source route remains published. + const publishedSource = options.deferPublishedRouteReservation + ? deps.getSandbox?.(name) + : null; + if ( + !selectingNativeLocal && + options.deferPublishedRouteReservation && + shouldStageGatewayRouteAfterBackup( + provider, + publishedSource, + hostLocalSelection, + credentialEnv, + deps.ollamaProxyCredentialEnv, + ) + ) { + // The sandbox phase owns the replacement reservation after its + // pre-delete backup succeeds. Keep the current source connectable + // if that backup rejects the workspace. + return true; + } revalidateSandboxIdentity?.("reserve the sandbox inference route"); // A route-only reservation abandoned by an earlier run otherwise // refuses this one and blames a session that no longer exists @@ -911,11 +1281,12 @@ export function createSetupInference( endpointUrl: nativeHostedEndpoint ?? hostLocalRoute?.applicationBaseUrl ?? endpointUrl, endpointSource: hostLocalRoute ? "inference-set" : endpointSource, credentialEnv: nativeHostedCredentialEnv ?? credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, gatewayName, reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(hostLocalInferenceProvenance && hostLocalInferenceGatewayPortAuthority !== undefined @@ -928,6 +1299,8 @@ export function createSetupInference( if (releaseAbandonedRouteReservation(name, route)) { deps.log(` Released an abandoned inference route reservation for sandbox '${name}'.`); } + // A failed response can follow a durable registry write. Retain authority once publication starts. + nativeLocalReservationEntered = true; const reserved = deps.updateSandbox(name, route); routeReserved = reserved; return reserved; @@ -938,11 +1311,12 @@ export function createSetupInference( gatewayName, revalidateSandboxIdentity, ); - const providerExitProcess: CommonDeps["exitProcess"] = hostLocalSelection - ? (code: number): never => { - throw new HostLocalInferenceBranchExit(code); - } - : deps.exitProcess; + const providerExitProcess: CommonDeps["exitProcess"] = + hostLocalSelection || selectingNativeLocal + ? (code: number): never => { + throw new HostLocalInferenceBranchExit(code); + } + : deps.exitProcess; const ambiguousRouteExitProcess: CommonDeps["exitProcess"] = hostLocalSelection ? (code: number): never => { throw new HostLocalInferenceBranchExit(code, true); @@ -955,15 +1329,90 @@ export function createSetupInference( : deps.error; const selectedUpsertProvider: CommonDeps["upsertProvider"] = async (...args) => { revalidateSandboxIdentity?.("register the inference provider"); + if (selectingNativeLocal) { + if (!sandboxName) throw new Error("Native local inference requires a sandbox."); + if (hostLocalGatewayMutation?.registerNativeProvider) { + nativeLocalProviderAttachment = + await hostLocalGatewayMutation.registerNativeProvider(); + return { ok: true }; + } + if (!deps.providerAdapter) + throw new Error("Native local inference requires a provider adapter."); + const [name, , sourceCredentialEnv, selectedEndpoint, env] = args; + const recorded = deps.getSandbox?.(sandboxName); + if ( + recorded && + recorded.pendingRouteReservation !== true && + (usesNativeLocalInference(recorded.provider, recorded.endpointUrl) || + usesNativeLocalInferenceForAgent( + recorded.agent, + recorded.provider, + recorded.endpointUrl, + )) && + !normalizeNativeLocalProviderAttachment(recorded.nativeLocalProviderAttachment) + ) { + if ( + !options.recreatePublishedSandbox || + !options.deferPublishedRouteReservation || + !options.reservationSessionId || + (recorded.agent !== "langchain-deepagents-code" && + recorded.agent !== "openclaw" && + recorded.agent !== "hermes" && + recorded.agent !== "pi") + ) { + throw new Error("Recreate this beta sandbox before using native local inference."); + } + nativeLocalRecreationSource = structuredClone(recorded); + } + const value = env?.[sourceCredentialEnv] ?? null; + const hostReachableEndpoint = + hostLocalRoute?.gatewayProviderBaseUrl ?? + gatewayReachableCompatibleEndpointUrl(name, selectedEndpoint); + if (typeof hostReachableEndpoint !== "string") + throw new Error("Native local inference endpoint is missing."); + nativeLocalProviderAttachment = await prepareNativeLocalSelection({ + adapter: deps.providerAdapter, + binding: { + provider: name as NativeLocalProvider, + ...(nativeLocalAgent === "openclaw" || + nativeLocalAgent === "pi" || + nativeLocalAgent === "hermes" + ? { agent: nativeLocalAgent } + : {}), + endpointUrl: hostReachableEndpoint, + authMode: + (name === "ollama-local" && value === "ollama") || + (name === "vllm-local" && value === "dummy") + ? "sentinel" + : "authenticated", + gatewayName, + sandboxName, + }, + credentialValue: value, + ownedProxy: + (name === "ollama-local" && !hostLocalRoute && deps.shouldFrontOllamaWithProxy()) || + (name === "compatible-endpoint" && + sourceCredentialEnv === deps.ollamaProxyCredentialEnv), + readAuthority: deps.getNativeLocalProviderAuthority, + writeAuthority: deps.setNativeLocalProviderAuthority, + }); + return { ok: true }; + } + const reused = routeStager.reusePublishedProvider(args[0]); + if (reused) return reused; const upsertProvider = hostLocalGatewayMutation?.upsertProvider ?? defaultUpsertProvider; + if (routeStager.stageProviderUpsert(async () => await upsertProvider(...args))) + return { ok: true }; return await upsertProvider(...args); }; const commonDeps = { runOpenshell: runGatewayOpenshell, inferenceRouteMutator: revalidatingInferenceRouteMutator, + nativeLocalInference: selectingNativeLocal, gatewayName, upsertProvider: selectedUpsertProvider, verifyInferenceRoute: (selectedProvider: string, selectedModel: string) => { + if (routeStager.hasStagedRoute()) return; if (!hostLocalRoute && sandboxName) { reserveRoute(sandboxName, selectedProvider, selectedModel); } @@ -1056,32 +1505,63 @@ export function createSetupInference( } const setupSelectedProvider = async (): Promise => { - const hosted = hostedNativeProvider(provider); - if (hosted && provider !== deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { + if (nativeCustomSelection) { if ( !deps.providerAdapter || !deps.getNativeHostedProviderAuthority || !deps.setNativeHostedProviderAuthority - ) { + ) throw new Error( - "Native hosted setup is missing its provider adapter or ownership store.", + "Native custom setup is missing its provider adapter or ownership store.", ); - } - const credentialValue = - deps.hydrateCredentialEnv(credentialEnv || hosted.credentialEnv) || null; - nativeHostedProviderAttachment = await prepareHostedNativeProvider({ - provider, - adapter: deps.providerAdapter, + const selectedCredentialEnv = credentialEnv || customNativeCredentialEnv(provider); + const credentialValue = deps.hydrateCredentialEnv(selectedCredentialEnv) || null; + nativeHostedProviderAttachment = await prepareCustomNativeProvider({ gatewayName, + provider, + endpointUrl: endpointUrl!, + api: selectedInferenceApi!, + credentialEnv: selectedCredentialEnv, credentialValue, - reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, - recordedSandbox: sandboxName ? deps.getSandbox?.(sandboxName) : null, + adapter: deps.providerAdapter, + recordedAttachment: + recordedSandbox?.provider === provider + ? recordedSandbox.nativeHostedProviderAttachment + : undefined, + recordedSandboxName: + recordedSandbox?.provider === provider ? recordedSandbox.name : null, + lookup: endpointPinnedAddresses + ? async () => endpointPinnedAddresses!.map((address) => ({ address })) + : deps.resolveEndpointHost, + trustedPrivateHosts: deps.trustedPrivateEndpointHosts, readAuthority: deps.getNativeHostedProviderAuthority, writeAuthority: deps.setNativeHostedProviderAuthority, + onCredentialPersisted: (env, value) => { + deps.recordMigratedProviderCredential?.( + provider, + env, + value, + revalidateSandboxIdentity, + ); + }, }); retainedNativeHostedCredential = !credentialValue; return null; } + const hosted = hostedNativeProvider(provider); + if (hosted && provider !== deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { + const prepared = await prepareSelectedHostedProvider({ + provider, + gatewayName, + sandboxName, + credentialEnv, + reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, + deps, + }); + nativeHostedProviderAttachment = prepared.attachment; + retainedNativeHostedCredential = prepared.retainedCredential; + return null; + } if (provider === deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { return inferenceProviders.setupHermesProviderInference( @@ -1127,8 +1607,6 @@ export function createSetupInference( }, hermesProviderAuth: deps.hermesProviderAuth, getHermesToolGatewayBroker: deps.getHermesToolGatewayBroker, - providerExistsInGateway: (name: string) => - deps.providerExistsInGateway(name, gatewayName), normalizeHermesAuthMethod: deps.normalizeHermesAuthMethod, resolveHermesNousApiKey: deps.resolveHermesNousApiKey, checkHermesProviderStoreReachable: deps.checkHermesProviderStoreReachable, @@ -1162,9 +1640,10 @@ export function createSetupInference( `Sandbox '${sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before using native NVIDIA inference; NemoClaw does not migrate existing beta sandboxes automatically.`, ); } + const gatewayAuthority = deps.getNativeNvidiaProviderAuthority?.(gatewayName); const providerAuthority = resolveGatewayNativeNvidiaProviderAuthority({ gatewayName, - gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(gatewayName), + gatewayAuthority, recordedAttachment, }); nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ @@ -1173,7 +1652,12 @@ export function createSetupInference( credentialValue, reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(providerAuthority ? { expected: providerAuthority } : {}), + ...(providerAuthority && !gatewayAuthority && recordedSandbox + ? { recordedSandboxName: recordedSandbox.name } + : {}), }); + // The retained gateway credential is unavailable to a host-side smoke. + retainedNativeHostedCredential = !credentialValue; if (deps.getNativeNvidiaProviderAuthority && deps.setNativeNvidiaProviderAuthority) { await persistNativeNvidiaProviderAuthority({ adapter: providerAdapter, @@ -1203,7 +1687,7 @@ export function createSetupInference( allowLegacyRecordedNoAuthEndpoint: options.allowLegacyRecordedNoAuthEndpoint === true, skipHostInferenceSmoke: options.skipHostInferenceSmoke === true, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, pinnedAddresses: endpointPinnedAddresses, trustedPrivateCapability: endpointTrustedPrivateCapability, capabilityCache: options.inferenceCapabilityCache, @@ -1243,19 +1727,25 @@ export function createSetupInference( getLocalProviderBaseUrl: hostLocalRoute ? () => hostLocalRoute.gatewayProviderBaseUrl : deps.getLocalProviderBaseUrl, - applyLocalInferenceRoute: resolveLocalInferenceRouteApplier( - hostLocalRoute - ? { - ...deps, - exitProcess: commonDeps.exitProcess, - error: commonDeps.error, - } - : deps, - revalidatingInferenceRouteMutator, - gatewayName, - revalidateSandboxIdentity, - ambiguousRouteExitProcess, - ), + applyLocalInferenceRoute: selectingNativeLocal + ? async () => { + if (!nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + return false; + } + : resolveLocalInferenceRouteApplier( + hostLocalRoute + ? { + ...deps, + exitProcess: commonDeps.exitProcess, + error: commonDeps.error, + } + : deps, + revalidatingInferenceRouteMutator, + gatewayName, + revalidateSandboxIdentity, + ambiguousRouteExitProcess, + ), run: deps.run, VLLM_LOCAL_CREDENTIAL_ENV: deps.vllmLocalCredentialEnv, getManagedVllmProviderBinding: hostLocalRoute @@ -1291,7 +1781,9 @@ export function createSetupInference( allowToolsIncompatible: options.allowToolsIncompatible === true, ...(hostLocalRoute ? {} - : { preparedProxyToken: options.preparedOllamaProxyToken }), + : { + preparedProxyToken: options.preparedOllamaProxyToken, + }), }, { ...commonDeps, @@ -1301,19 +1793,25 @@ export function createSetupInference( getLocalProviderBaseUrl: hostLocalRoute ? () => hostLocalRoute.gatewayProviderBaseUrl : deps.getLocalProviderBaseUrl, - applyLocalInferenceRoute: resolveLocalInferenceRouteApplier( - hostLocalRoute - ? { - ...deps, - exitProcess: commonDeps.exitProcess, - error: commonDeps.error, - } - : deps, - revalidatingInferenceRouteMutator, - gatewayName, - revalidateSandboxIdentity, - ambiguousRouteExitProcess, - ), + applyLocalInferenceRoute: selectingNativeLocal + ? async () => { + if (!nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + return false; + } + : resolveLocalInferenceRouteApplier( + hostLocalRoute + ? { + ...deps, + exitProcess: commonDeps.exitProcess, + error: commonDeps.error, + } + : deps, + revalidatingInferenceRouteMutator, + gatewayName, + revalidateSandboxIdentity, + ambiguousRouteExitProcess, + ), run: deps.run, shouldFrontOllamaWithProxy: hostLocalRoute ? () => false @@ -1368,12 +1866,22 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - if (!nativeNvidiaProviderAttachment && !nativeHostedProviderAttachment) + if (selectingNativeLocal && !nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + if ( + !nativeNvidiaProviderAttachment && + !nativeHostedProviderAttachment && + !nativeLocalProviderAttachment + ) commonDeps.verifyInferenceRoute(provider, model); if (hostLocalRoute) { deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", ); + } else if (nativeHostedProviderAttachment?.custom) { + deps.log( + " Custom native inference will be verified from the sandbox using its selected API.", + ); } else if (options.skipHostInferenceSmoke === true || retainedNativeHostedCredential) { deps.log(" Reusing existing gateway credential; skipping host inference smoke."); } else { @@ -1456,9 +1964,35 @@ export function createSetupInference( } revalidateSandboxIdentity?.("report successful inference provider setup"); shouldLogSuccessfulRoute = true; - return { ok: true as const }; + if (nativeLocalRecreationSource && nativeLocalProviderAttachment) { + return { + ok: true, + stagedNativeLocalRecreation: { + source: nativeLocalRecreationSource, + attachment: nativeLocalProviderAttachment, + }, + }; + } + return routeStager.successResult(); } catch (error) { - if (!hostLocalRoute || !hostLocalSelection) throw error; + if (!hostLocalRoute || !hostLocalSelection) { + return rejectNativeLocalSetupFailure({ + error, + attachment: nativeLocalProviderAttachment, + reservationEntered: nativeLocalReservationEntered, + sandboxName, + gatewayName, + deps, + }); + } + await cleanupUnreservedNativeLocalAfterHostFailure({ + selectingNativeLocal, + attachment: nativeLocalProviderAttachment, + reservationEntered: nativeLocalReservationEntered, + sandboxName, + gatewayName, + deps, + }); emitHostLocalInferenceFailure( hostLocalSelection.runtimeProviderId, error instanceof HostLocalInferenceBranchExit @@ -1502,41 +2036,56 @@ export function createSetupInference( // this cleanup runs. const mutateGatewayRouteAndReleaseSupersededModel = async (): Promise => { let previousSandbox: OllamaModelHolder | null = null; + const selectedAgent = options.agentName ?? options.hostLocalInference?.request.application; + let recordedAgent: string | null | undefined; + let recordedNimContainer: string | null | undefined; try { - previousSandbox = sandboxName ? (deps.getSandbox?.(sandboxName) ?? null) : null; - } catch { + const recorded = sandboxName ? (deps.getSandbox?.(sandboxName) ?? null) : null; + previousSandbox = recorded; + recordedAgent = recorded?.agent; + recordedNimContainer = recorded?.nimContainer; + } catch (error) { + if (!selectedAgent && usesNativeLocalInference(provider, endpointUrl)) throw error; /* An unreadable registry skips GPU release; it must not fail onboarding. */ } - // Compatible endpoints can own the same host Ollama daemon as direct Ollama routes. - // Serialize publication with release decisions across gateways to prevent a newly - // published peer route from being missed by concurrent cleanup (#12677). - const participatesInOllamaOwnership = - (previousSandbox !== null && isLocalOllamaRouteOwner(previousSandbox)) || - isLocalOllamaRouteOwner({ provider, endpointUrl }); - const runRouteAndRelease = async (): Promise => { - const result = await mutateGatewayRoute(); - releaseSupersededOllamaModel( - previousSandbox, + nativeLocalAgent = selectedAgent ?? recordedAgent; + selectingNativeLocal = + !options.hostLocalInference?.sharedInferenceRoute && + usesNativeLocalInferenceForAgent( + nativeLocalAgent, provider, - model, endpointUrl, - result, - deps, - revalidateSandboxIdentity, + options.localNimSelected ?? (provider === "vllm-local" && Boolean(recordedNimContainer)), ); - if (shouldLogSuccessfulRoute && "ok" in result) { - deps.log( - isNativeNvidiaProvider(provider) - ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` - : ` ✓ Inference route set: ${provider} / ${model}`, - ); - } - return result; - }; - if (!participatesInOllamaOwnership) return runRouteAndRelease(); - const withOwnershipTransaction = - deps.withOllamaModelOwnershipTransaction ?? withOllamaModelOwnershipTransaction; - return withOwnershipTransaction(runRouteAndRelease); + const preservingLegacyPiRoute = + options.preserveLegacyPiSharedLocalRoute === true && + isPersistedPiSharedLocalInferenceRoute( + sandboxName ? deps.getSandbox?.(sandboxName) : null, + { provider, model, endpointUrl }, + ); + if (options.preserveLegacyPiSharedLocalRoute && !preservingLegacyPiRoute) + throw new Error("Recorded Pi shared local inference route changed before setup."); + selectingNativeLocal = selectingNativeLocal && !preservingLegacyPiRoute; + if (selectingNativeLocal) + await (deps.requireNativeProviderPolicy ?? requireNativeProviderPolicy)(gatewayName); + const result = await mutateGatewayRoute(); + releaseSupersededOllamaModel( + previousSandbox, + provider, + model, + endpointUrl, + result, + deps, + revalidateSandboxIdentity, + ); + if (shouldLogSuccessfulRoute && "ok" in result) { + deps.log( + isNativeNvidiaProvider(provider) + ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` + : ` ✓ Inference route set: ${provider} / ${model}`, + ); + } + return result; }; return sandboxName ? deps.withSandboxMutationLock(sandboxName, mutateGatewayRouteAndReleaseSupersededModel) diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 30ac53a9832..786ee92beea 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -4,6 +4,8 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { normalizeNativeLocalProviderAttachment } from "../../../src/lib/inference/native-local/contract.ts"; +import { getSandbox } from "../../../src/lib/state/registry.ts"; import { containsAnswer } from "../../helpers/e2e-answer-assertions.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -15,13 +17,9 @@ import { resultText } from "../fixtures/clients/command.ts"; import { type HostCliClient } from "../fixtures/clients/host.ts"; import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; +import { nativeLocalChatCommand } from "../fixtures/native-local-chat.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; -import { - PUBLIC_NVIDIA_SWITCH_MODEL, - PUBLIC_NVIDIA_SWITCH_PROVIDER, - requirePublicNvidiaSwitchKey, -} from "./public-nvidia-switch-provider.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-gpu-double"; const PROXY_PORT = process.env.NEMOCLAW_OLLAMA_PROXY_PORT ?? "11435"; @@ -54,12 +52,10 @@ async function nemoclaw( artifactName: string, extraEnv: NodeJS.ProcessEnv = {}, timeoutMs = 20 * 60_000, - redactionValues: string[] = [], ): Promise { return await host.command(process.execPath, [CLI_ENTRYPOINT, ...args], { artifactName, env: env(extraEnv), - redactionValues, timeoutMs, }); } @@ -125,6 +121,10 @@ function parseReplyCommand(): string { return String.raw`python3 -c 'import json,sys; d=json.load(sys.stdin); m=d["choices"][0]["message"]; print((m.get("content") or m.get("reasoning_content") or m.get("reasoning") or "").strip())'`; } +function fileMode(pathname: string): string { + return (fs.statSync(pathname).mode & 0o777).toString(8).padStart(3, "0"); +} + function chatRequest(model: string): string { return JSON.stringify({ model, @@ -138,17 +138,23 @@ function chatRequest(model: string): string { }); } -async function querySandboxForAnswer( +async function expectSandboxInference42( sandbox: SandboxClient, model: string, artifactName: string, -): Promise { - return await sandbox.exec( +): Promise { + // OpenClaw local inference uses a sandbox-owned provider behind the auth proxy, not the shared + // gateway route (#13293). Re-read it after re-onboarding recreates the sandbox. A missing + // attachment yields an unresolvable host, which fails the request assertion below. + const endpoint = + normalizeNativeLocalProviderAttachment(getSandbox(SANDBOX_NAME)?.nativeLocalProviderAttachment) + ?.endpointUrl ?? "http://missing-native-local-attachment.invalid/v1"; + const response = await sandbox.exec( SANDBOX_NAME, [ "sh", "-lc", - `curl -fsS --max-time 120 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data '${chatRequest(model)}' | ${parseReplyCommand()}`, + `${nativeLocalChatCommand(endpoint, chatRequest(model), "-fsS")} | ${parseReplyCommand()}`, ], { artifactName, @@ -156,20 +162,12 @@ async function querySandboxForAnswer( timeoutMs: 150_000, }, ); -} - -async function expectSandboxInference42( - sandbox: SandboxClient, - model: string, - artifactName: string, -): Promise { - const response = await querySandboxForAnswer(sandbox, model, artifactName); expect(response.exitCode, resultText(response)).toBe(0); expect(containsAnswer(response.stdout, "42"), resultText(response)).toBe(true); } test( - "gpu double onboard preserves proxy auth and unloads Ollama on provider switch", + "gpu double onboard keeps Ollama auth proxy token consistent after re-onboard", { timeout: LIVE_TIMEOUT_MS, meta: { @@ -180,9 +178,6 @@ test( "validate first proxy token and inference", "re-onboard GPU sandbox", "validate persisted proxy auth and inference", - "verify the Ollama model is active before switching providers", - "switch inference to a non-Ollama provider", - "verify new-provider inference and confirm Ollama unloaded the old model", "remove GPU double-onboard sandbox", ], }, @@ -194,7 +189,6 @@ test( progress, runtimeProvider, sandbox, - secrets, skip, }) => { await artifacts.target.declare({ @@ -204,17 +198,13 @@ test( contracts: [ "GPU and runtime prerequisites are present", "install.sh onboards with the Ollama provider", - "sandbox inference.local reaches Ollama after first onboard", + "the persisted Ollama auth-proxy token works after first onboard", "nemoclaw onboard --non-interactive --yes recreates the sandbox", "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", - "sandbox inference.local reaches Ollama after re-onboard", - "Ollama reports the selected model as active before the provider switch", - "nemoclaw inference set switches the sandbox to the public NVIDIA provider", - "sandbox inference succeeds through the new provider and host ollama ps no longer reports the superseded model", + "the sandbox-owned native provider reaches Ollama after first onboard and re-onboard", ], }); - const publicApiKey = requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")); await runtimeProvider.requireAvailable({ artifactName: "phase-0-runtime-info", scenarioLabel: "GPU double-onboard", @@ -349,10 +339,23 @@ exit "$status"`, expect(first.exitCode, resultText(first)).toBe(0); progress.phase("validate first proxy token and inference"); + const list = await nemoclaw(host, ["list"], "phase-3-nemoclaw-list"); + expect(list.exitCode, resultText(list)).toBe(0); + expect(list.stdout).toContain(SANDBOX_NAME); + expect(fs.existsSync(TOKEN_FILE), `${TOKEN_FILE} missing`).toBe(true); const tokenAfterFirst = fs.readFileSync(TOKEN_FILE, "utf8").trim(); expect(tokenAfterFirst.length).toBeGreaterThan(10); + expect(fileMode(TOKEN_FILE)).toBe("600"); const model = GPU_E2E_MODEL; + + const firstTokenStatus = await httpStatus( + host, + `http://127.0.0.1:${PROXY_PORT}/v1/models`, + "phase-3-proxy-token-status", + tokenAfterFirst, + ); + expect(firstTokenStatus.stdout.trim(), resultText(firstTokenStatus)).toBe("200"); await expectSandboxInference42(sandbox, model, "phase-3-sandbox-inference-first-onboard"); progress.phase("re-onboard GPU sandbox"); @@ -364,7 +367,10 @@ exit "$status"`, execTimeout(30 * 60_000), ); expect(reonboard.exitCode, resultText(reonboard)).toBe(0); + expect(fs.existsSync(TOKEN_FILE), `${TOKEN_FILE} missing after re-onboard`).toBe(true); const tokenAfterSecond = fs.readFileSync(TOKEN_FILE, "utf8").trim(); + expect(tokenAfterSecond.length).toBeGreaterThan(10); + expect(fileMode(TOKEN_FILE)).toBe("600"); expect(tokenAfterSecond).toBe(tokenAfterFirst); progress.phase("validate persisted proxy auth and inference"); @@ -400,53 +406,6 @@ exit "$status"`, await expectSandboxInference42(sandbox, model, "phase-6-sandbox-inference-after-reonboard"); - progress.phase("verify the Ollama model is active before switching providers"); - const activeModelsBeforeSwitch = await host.command("ollama", ["ps"], { - artifactName: "phase-7-ollama-ps-before-provider-switch", - env: env(), - timeoutMs: 30_000, - }); - expect(activeModelsBeforeSwitch.exitCode, resultText(activeModelsBeforeSwitch)).toBe(0); - expect(activeModelsBeforeSwitch.stdout).toContain(model); - - progress.phase("switch inference to a non-Ollama provider"); - const providerSwitch = await nemoclaw( - host, - [ - "inference", - "set", - "--provider", - PUBLIC_NVIDIA_SWITCH_PROVIDER, - "--model", - PUBLIC_NVIDIA_SWITCH_MODEL, - "--sandbox", - SANDBOX_NAME, - ], - "phase-8-inference-set-away-from-ollama", - { NVIDIA_INFERENCE_API_KEY: publicApiKey }, - execTimeout(5 * 60_000), - [publicApiKey], - ); - expect(providerSwitch.exitCode, resultText(providerSwitch)).toBe(0); - - progress.phase("verify new-provider inference and confirm Ollama unloaded the old model"); - const switchedInference = await querySandboxForAnswer( - sandbox, - PUBLIC_NVIDIA_SWITCH_MODEL, - "phase-9-sandbox-inference-after-provider-switch", - ); - expect(switchedInference.exitCode, resultText(switchedInference)).toBe(0); - expect(containsAnswer(switchedInference.stdout, "42"), resultText(switchedInference)).toBe( - true, - ); - const activeModelsAfterSwitch = await host.command("ollama", ["ps"], { - artifactName: "phase-9-ollama-ps-after-provider-switch", - env: env(), - timeoutMs: 30_000, - }); - expect(activeModelsAfterSwitch.exitCode, resultText(activeModelsAfterSwitch)).toBe(0); - expect(activeModelsAfterSwitch.stdout).not.toContain(model); - progress.phase("remove GPU double-onboard sandbox"); await host.cleanupSandbox(SANDBOX_NAME, { artifactName: "verify-cleanup-nemoclaw-destroy", @@ -459,12 +418,6 @@ exit "$status"`, await artifacts.target.complete({ id: "gpu-double-onboard", status: "passed", - assertions: { - ollamaModelActiveBeforeProviderSwitch: true, - inferenceSetCompleted: providerSwitch.exitCode === 0, - switchedProviderInferenceReturned42: true, - supersededOllamaModelAbsentAfterSwitch: true, - }, }); }, ); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index ef0bdbe97c2..f38b80ee8e8 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -33,7 +33,14 @@ }, { "live": "test/e2e/live/portable-profile-rootless-linux.test.ts", + "liveSources": [ + "test/e2e/fixtures/portable-profile-rootless-finalization-helpers.ts", + "test/e2e/fixtures/portable-registry-readiness.ts" + ], "fast": [ + "src/lib/actions/sandbox/doctor-flow.test.ts", + "src/lib/onboard/machine/finalization-deps.test.ts", + "src/lib/onboard/machine/handlers/finalization.test.ts", "src/lib/onboard/experimental/hermes-portable-container.test.ts", "src/lib/onboard/experimental/hermes-portable-lifecycle.test.ts", "src/lib/onboard/command.test.ts", @@ -41,6 +48,7 @@ "src/lib/onboard/experimental/portable-host-preparation.test.ts", "src/lib/onboard/sandbox-prebuild.test.ts", "test/agents/hermes/hermes-start.test.ts", + "test/e2e/support/portable-registry-readiness.test.ts", "test/e2e/support/portable-profile-rootless-runtime-workflow.test.ts" ] }, @@ -52,7 +60,9 @@ "test/e2e/fixtures/admin-request-selector.ts", "test/e2e/fixtures/issue-4462-admin-approval-evidence.ts", "test/e2e/lib/issue-4462-admin-request-selector.py", - "test/e2e/live/openclaw-admin-scope.ts" + "test/e2e/live/openclaw-admin-scope.ts", + "test/e2e/live/gpu-e2e-helpers.ts", + "test/e2e/fixtures/llama-cpp-runtime-diagnostics.ts" ], "fast": [ "src/lib/inference/llama-cpp/index.test.ts", @@ -60,10 +70,12 @@ "src/lib/inference/llama-cpp/managed-selection.test.ts", "src/lib/inference/llama-cpp/managed-installer.test.ts", "src/lib/onboard/setup-nim-flow.test.ts", + "test/onboarding/onboard-host-local-inference-routing.test.ts", "test/security/admin-approval-helper.test.ts", "test/e2e/support/pr-self-hosted-llama-selector.test.ts", "test/e2e/support/onboard-timeout-contract.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/e2e/support/llama-cpp-generic-gpu-diagnostics.test.ts" ] }, { @@ -79,14 +91,19 @@ }, { "live": "test/e2e/live/managed-image-protected-runtime.test.ts", - "liveSources": ["test/e2e/live/managed-image-protected-runtime-helpers.ts"], + "liveSources": [ + "test/e2e/live/managed-image-protected-runtime-helpers.ts", + "test/e2e/live/managed-image-protected-runtime-budget.ts" + ], "fast": [ "src/lib/inference/nim.test.ts", "src/lib/onboard/sandbox-gpu-create-flow.test.ts", + "test/e2e/support/managed-image-protected-runtime-readiness.test.ts", "test/e2e/support/managed-image-protected-runtime-workflow.test.ts", "test/inference/managed/managed-image-protected-runtime-contract.test.ts", "test/inference/llama/llama-cpp-dgx-spark-qualification-runner.test.ts", - "test/automation/pull-requests/pr-risk-plan.test.ts" + "test/automation/pull-requests/pr-risk-plan.test.ts", + "test/e2e/support/managed-image-protected-runtime-budget.test.ts" ] }, { @@ -101,10 +118,12 @@ "test/e2e/live/openclaw-admin-scope.ts" ], "fast": [ + "test/e2e/support/hermes-native-local-evidence.test.ts", "src/lib/onboard/command.test.ts", "src/lib/onboard/sandbox-workload-preparation.test.ts", "test/e2e/support/managed-image-activation-diagnostics.test.ts", - "test/inference/managed/managed-image-publication-workflow.test.ts" + "test/inference/managed/managed-image-publication-workflow.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -186,6 +205,9 @@ "test/e2e/fixtures/admin-approval-connect.sh" ], "fast": [ + "src/lib/inference/native-local.test.ts", + "test/onboarding/onboard-host-local-inference-routing.test.ts", + "test/agents/deepagents/langchain-deepagents-code-config.test.ts", "nemoclaw/src/shared/openshell-gateway-health-sdk.test.ts", "nemoclaw/src/blueprint/runner.test.ts", "nemoclaw/src/blueprint/runner-identity.test.ts", @@ -196,16 +218,15 @@ "test/e2e/support/onboard-timeout-contract.test.ts", "test/onboarding/onboard-inference-gateway-scope.test.ts", "test/e2e/support/managed-image-activation-diagnostics.test.ts", - "test/e2e/support/hosted-provider-smoke-selection.test.ts" + "test/e2e/support/hosted-provider-smoke-selection.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { "live": "test/e2e/live/inference-routing-provider-smoke.test.ts", - "liveSources": [ - "test/e2e/live/inference-routing-credential-scan.ts", - "test/e2e/fixtures/hermes-api-command.ts" - ], + "liveSources": ["test/e2e/live/inference-routing-credential-scan.ts"], "fast": [ + "test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts", "test/generation/generate-native-hosted-config.test.ts", "test/e2e/support/hosted-provider-smoke-selection.test.ts", "test/e2e/support/hosted-credential-scan.test.ts", @@ -247,7 +268,8 @@ "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/managed-image-receipt.test.ts", "test/helpers/e2e-answer-assertions.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -288,6 +310,7 @@ "test/e2e/support/e2e-semantic-phase-check.test.ts", "test/e2e/support/workflow-e2e-progress.test.ts", "test/e2e/support/prepare-e2e-workflow-boundary.test.ts", + "test/e2e/support/full-e2e-inference-probe.test.ts", "test/e2e/support/openclaw-agent-output.test.ts", "test/helpers/e2e-answer-assertions.test.ts", "test/install/installer-hash-check.test.ts", @@ -358,7 +381,8 @@ "test/mcp/mcp-agent-matrix-artifact-proof.test.ts", "test/e2e/support/mcp-workflow-boundary.test.ts", "test/e2e/support/runtime-provider-fixture.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -389,6 +413,7 @@ { "live": "test/e2e/live/onboard-repair.test.ts", "liveSources": [ + "test/e2e/fixtures/gateway-providers.ts", "test/e2e/fixtures/podman-owner-diagnostic.ts", "test/e2e/fixtures/podman-owner-snapshot.ts", "test/e2e/fixtures/onboard-precleanup.ts", @@ -396,6 +421,7 @@ "test/e2e/fixtures/sandbox-failure-diagnostics.ts" ], "fast": [ + "test/e2e/support/gateway-extra-provider-profile.test.ts", "test/e2e/support/podman-owner-diagnostic.test.ts", "test/e2e/support/podman-owner-snapshot.test.ts", "test/e2e/support/onboard-precleanup.test.ts", @@ -404,6 +430,7 @@ "src/lib/onboard/extra-provider-reconciliation-probes.test.ts", "src/lib/onboard/extra-provider-reconciliation.test.ts", "src/lib/onboard/initial-policy-real-policy.test.ts", + "src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts", "src/lib/onboard/machine/handlers/sandbox-resume.test.ts", "src/lib/onboard/managed-startup-image-runtime-handoff.test.ts", "src/lib/onboard/sandbox-create-plan.test.ts", @@ -417,6 +444,7 @@ { "live": "test/e2e/live/onboard-resume.test.ts", "liveSources": [ + "test/e2e/fixtures/gateway-providers.ts", "test/e2e/fixtures/podman-owner-diagnostic.ts", "test/e2e/fixtures/podman-owner-snapshot.ts", "test/e2e/fixtures/onboard-precleanup.ts", @@ -424,6 +452,7 @@ "test/e2e/fixtures/sandbox-failure-diagnostics.ts" ], "fast": [ + "test/e2e/support/gateway-extra-provider-profile.test.ts", "test/e2e/support/podman-owner-diagnostic.test.ts", "test/e2e/support/podman-owner-snapshot.test.ts", "test/e2e/support/onboard-precleanup.test.ts", @@ -481,12 +510,14 @@ "test/e2e/fixtures/admin-approval-connect.sh" ], "fast": [ + "src/lib/inference/native-provider/custom.test.ts", "test/e2e/support/bedrock-runtime-compatible-anthropic-leaks.test.ts", "test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/openclaw-agent-output.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -547,7 +578,8 @@ "test/e2e/support/retry-policy.test.ts", "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/openclaw-agent-output.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -570,6 +602,7 @@ "live": "test/e2e/live/double-onboard.test.ts", "fast": [ "test/cli/sandbox-status-text.test.ts", + "src/lib/actions/uninstall/run-plan-agent-state-volume.test.ts", "src/lib/onboard/created-sandbox-finalization.test.ts", "src/lib/onboard/gateway-reuse.test.ts", "src/lib/onboard/machine/core-flow-phases.test.ts", @@ -583,21 +616,20 @@ }, { "live": "test/e2e/live/gpu-double-onboard.test.ts", + "liveSources": ["test/e2e/fixtures/native-local-chat.ts"], "fast": [ - "src/lib/inference/ollama/model-ownership.test.ts", - "src/lib/onboard/setup-inference.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/helpers/e2e-answer-assertions.test.ts", - "test/onboarding/onboard-inference-reconciliation.test.ts", - "test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts" + "test/e2e/support/gpu-e2e-helpers.test.ts", + "test/helpers/e2e-answer-assertions.test.ts" ] }, { "live": "test/e2e/live/gpu-e2e.test.ts", "liveSources": [ "test/e2e/live/gpu-e2e-helpers.ts", - "test/e2e/live/hermes-cli-adapter-live.ts" + "test/e2e/live/hermes-cli-adapter-live.ts", + "test/e2e/fixtures/native-local-chat.ts" ], "fast": [ "src/lib/adapters/config/live-export-source-ollama.test.ts", @@ -639,7 +671,8 @@ "test/onboarding/onboard-preset-diff.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/e2e/support/hermes-config-export-live.test.ts" + "test/e2e/support/hermes-config-export-live.test.ts", + "test/e2e/support/hermes-discord-rebuild-contract.test.ts" ] }, { @@ -674,6 +707,9 @@ "test/e2e/live/public-nvidia-switch-provider.ts" ], "fast": [ + "src/lib/onboard/hermes/initial-inference-route.test.ts", + "test/agents/hermes/hermes-nvidia-restore-validation.test.ts", + "test/e2e/support/hermes-native-local-evidence.test.ts", "src/lib/actions/inference-set-compatible-provider.test.ts", "test/e2e/support/hermes-inference-switch-command-shape.test.ts", "test/e2e/support/public-nvidia-switch-provider.test.ts", @@ -681,7 +717,8 @@ "test/e2e/support/compatible-anthropic-switch.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/e2e/support/host-container-discovery.test.ts" + "test/e2e/support/host-container-discovery.test.ts", + "test/e2e/support/hermes-discord-rebuild-contract.test.ts" ] }, { @@ -699,7 +736,8 @@ "test/e2e/support/issue-4462-gateway-snapshot.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -769,7 +807,8 @@ "test/e2e/support/mcp-bridge-https-diagnostics.test.ts", "src/lib/onboard/runtime-provider/docker-stopped-state-capture.test.ts", "test/state/snapshot.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -844,15 +883,22 @@ { "live": "test/e2e/live/openclaw-inference-switch.test.ts", "liveSources": [ + "test/e2e/fixtures/inference-routing-openclaw-native.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", "test/e2e/live/openclaw-admin-scope.ts", "test/e2e/live/public-nvidia-switch-provider.ts", "test/e2e/fixtures/admin-approval-connect.ts", "test/e2e/fixtures/admin-approval-connect.sh", "test/e2e/fixtures/issue-4462-admin-approval-evidence.ts", - "test/e2e/fixtures/managed-image-receipt.ts" + "test/e2e/fixtures/managed-image-receipt.ts", + "test/e2e/fixtures/native-local-ipv6-evidence.ts" ], "fast": [ + "src/lib/inference/native-local.test.ts", + "src/lib/actions/inference-set-openclaw-native-local.test.ts", + "src/lib/actions/inference-set-openclaw-run.test.ts", + "test/onboarding/onboard-host-local-inference-routing.test.ts", + "test/e2e/support/onboard-timeout-contract.test.ts", "src/lib/actions/inference-get.test.ts", "src/lib/actions/inference-set-patch-openclaw.test.ts", "src/lib/actions/inference-set-compatible-provider.test.ts", @@ -866,7 +912,8 @@ "test/e2e/support/openclaw-inference-switch-helpers.test.ts", "test/e2e/support/public-nvidia-switch-provider.test.ts", "test/security/admin-approval-helper.test.ts", - "test/e2e/support/hosted-inference.test.ts" + "test/e2e/support/hosted-inference.test.ts", + "test/e2e/support/native-local-ipv6-evidence.test.ts" ] }, { @@ -982,7 +1029,8 @@ "test/e2e/support/json-envelope.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ] }, { @@ -992,7 +1040,8 @@ "test/e2e/support/skill-agent-classifiers.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", - "test/e2e/support/managed-image-activation-diagnostics.test.ts" + "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/security/admin-approval-helper.test.ts" ], "liveSources": [ "test/e2e/live/openclaw-admin-scope.ts", @@ -1003,6 +1052,7 @@ { "live": "test/e2e/live/dgx-express.test.ts", "fast": [ + "src/lib/inference/vllm-runtime-selection.test.ts", "test/e2e/support/dgx-station-express.test.ts", "test/e2e/support/live-vitest-invocation.test.ts", "test/installer-integration/install-express-noninteractive.test.ts", diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 5371c43f7c9..d572b279d53 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -13,6 +13,11 @@ import { type SetupInference, type SetupInferenceDeps, } from "../../src/lib/onboard/setup-inference.js"; +import { usesNativeLocalInference } from "../../src/lib/inference/native-local/contract"; +import { + createNativeLocalSetupHarness, + withNativePolicyFixture, +} from "./native-local-setup-harness"; import { redact } from "../../src/lib/security/redact.js"; const onboardProviderHelpers = require("../../src/lib/onboard/providers") as { @@ -47,6 +52,8 @@ export type DirectRunStubResult = { }; export type DirectSetupHarnessOptions = { + /** Exercise an existing custom sandbox's shared inference route. */ + legacyCustomRoute?: boolean; runOpenshell?: ( args: string[], options: DirectRunOptions, @@ -378,6 +385,7 @@ export function createDirectSetupInferenceHarnessFactory( createSetupInference: CreateSetupInference, ) { return function createDirectSetupInferenceHarness(options: DirectSetupHarnessOptions = {}) { + let legacySandbox: ReturnType> = null; const commands: DirectCommandEntry[] = []; const errors: string[] = []; const logs: string[] = []; @@ -421,7 +429,7 @@ export function createDirectSetupInferenceHarnessFactory( } return directRunResult(); }; - const setupInferenceWithoutPolicyAuthority = createSetupInference({ + const harnessDeps: Partial = { checkGatewayRouteCompatibility: () => ({ ok: true }), withGatewayRouteMutationLock: async ( _gatewayName: string, @@ -539,16 +547,21 @@ export function createDirectSetupInferenceHarnessFactory( // #9110: neutralize the GPU-release seams so harness consumers backed by // the production defaults never read the developer's real registry or // curl a live Ollama daemon. - getSandbox: () => null, - listOllamaModelOwnershipPeers: () => [], - discoverActiveOllamaSandboxNames: (peers) => ({ - ok: true, - activeSandboxNames: new Set(peers.map((peer) => peer.name)), - gatewayChecks: [], - }), + getSandbox: () => legacySandbox, + listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => operation(), ...options.overrides, + }; + const setupInferenceWithoutPolicyAuthority = createSetupInference(harnessDeps); + const native = createNativeLocalSetupHarness(); + const setupNativeInference = createSetupInference({ + ...harnessDeps, + providerAdapter: native.adapter, + getNativeLocalProviderAuthority: native.getNativeLocalProviderAuthority, + setNativeLocalProviderAuthority: native.setNativeLocalProviderAuthority, + clearNativeLocalProviderAuthority: native.clearNativeLocalProviderAuthority, + ...options.overrides, }); const revalidateSandboxIdentity = vi.fn(); const setupInference: SetupInference = ( @@ -560,22 +573,30 @@ export function createDirectSetupInferenceHarnessFactory( hermesAuthMethod, hermesToolGateways, inferenceOptions = {}, - ) => - setupInferenceWithoutPolicyAuthority( - sandboxName, - model, - provider, - endpointUrl, - credentialEnv, - hermesAuthMethod, - hermesToolGateways, - { - ...inferenceOptions, - revalidateSandboxIdentity: - inferenceOptions.revalidateSandboxIdentity ?? revalidateSandboxIdentity, - }, - ); + ) => { + if (options.legacyCustomRoute && sandboxName) { + legacySandbox = { name: sandboxName, provider, model, endpointUrl, credentialEnv }; + } + const nativeLocal = usesNativeLocalInference(provider, endpointUrl); + const operation = () => + (nativeLocal ? setupNativeInference : setupInferenceWithoutPolicyAuthority)( + sandboxName, + model, + provider, + endpointUrl, + credentialEnv, + hermesAuthMethod, + hermesToolGateways, + { + ...inferenceOptions, + revalidateSandboxIdentity: + inferenceOptions.revalidateSandboxIdentity ?? revalidateSandboxIdentity, + }, + ); + return nativeLocal ? withNativePolicyFixture(operation) : operation(); + }; return { + native, commands, errors, logs, diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 8b83cd5a1f2..5d4459cb1c3 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -20,8 +20,11 @@ import { } from "./gateway-runtime.mts"; import { FULL_E2E_STANDARD_PROFILE_JOB_TIMEOUT_MINUTES } from "./full-e2e-timeout-contract.mts"; import { + ONBOARD_REPAIR_TARGET_TIMEOUT_MINUTES, ONBOARD_RESUME_TARGET_TIMEOUT_MINUTES, - ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES, + INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES, + OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, + PI_QUALIFICATION_TARGET_TIMEOUT_MINUTES, } from "./onboard-timeout-contract.mts"; import { HERMES_ACP_E2E_OWNING_PATHS } from "./hermes-acp-owning-paths.mts"; import { @@ -31,10 +34,7 @@ import { import { SANDBOX_SURVIVAL_TARGET_TIMEOUT_MINUTES } from "./sandbox-survival-timeout-contract.mts"; import { normalizeE2eSelectorId } from "./selector-aliases.mts"; -import { - HOSTED_PROVIDER_SMOKE_CASES, - hostedProviderSmokeEnvironment, -} from "./hosted-provider-smoke.mts"; +import { OPENROUTER_SMOKE, configureOpenRouterSmokeEnvironment } from "./hosted-provider-smoke.mts"; export const E2E_EXECUTION_PROFILES = [ "standard", @@ -312,7 +312,14 @@ const PI_IMAGE_SOURCE_OWNING_PATHS = [ "scripts/security/patches/libssh2-1.11.1-cve-2026.patch", "scripts/security/patches/perl-5.44.0-net-ping-capability-tests.patch", "scripts/security/patches/python3.13-htmlparser-cve-2026-15308.patch", + "scripts/security/patches/zlib-1.3.1-write-error.patch", + "scripts/security/zlib-write-error.c", + "scripts/security/libssh2-sftp-response-regression.c", + "scripts/security/security-package-inventory.mts", + "src/lib/sandbox-base-image/security-package-specs.ts", "scripts/upgrade-bundled-npm.mts", + "src/lib/core/endpoint-url-safety.ts", + "src/lib/inference/native-local/agent-config.ts", "src/lib/inference/native-provider/agent-config.ts", "src/lib/inference/native-nvidia/contract.ts", "src/lib/inference/native-provider/contract.ts", @@ -804,20 +811,17 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }), ), managedRuntimeTarget("gpu-double-onboard", { - displayName: "Onboarding: preserves Ollama auth after GPU re-onboarding and provider switch", + displayName: "Onboarding: preserves Ollama authentication after GPU re-onboarding", agentRuntime: "openclaw", - environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama and NVIDIA API inference", - profile: "nvidia-api", + environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama", + profile: "standard", runner: "linux-amd64-gpu-rtxpro6000-latest-1", podmanHostPackages: NATIVE_PODMAN_HOST_PACKAGES, timeoutMinutes: 100, installMode: "authenticated", restoreCli: true, exposeCliBin: true, - owningPaths: [ - "src/lib/inference/ollama/model-ownership.ts", - "src/lib/onboard/setup-inference.ts", - ], + owningPaths: ["test/e2e/fixtures/native-local-chat.ts"], environment: { ...nonInteractive, NEMOCLAW_MODEL: "qwen3.5:9b", @@ -838,6 +842,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ exposeCliBin: true, owningPaths: [ "test/e2e/live/gpu-e2e-helpers.ts", + "test/e2e/fixtures/native-local-chat.ts", "test/e2e/live/hermes-cli-adapter-live.ts", "src/lib/inference/ollama/proxy.ts", "src/lib/inference/ollama/proxy-observation.ts", @@ -884,7 +889,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("hermes-discord", { - displayName: "Messaging: Hermes preserves Discord configuration across rebuild", + displayName: "Messaging: Hermes isolates Discord credentials and verifies transport", agentRuntime: "hermes", environmentOrInferenceEndpoint: "Ubuntu; NVIDIA hosted inference and Discord", profile: "nvidia-inference", @@ -910,7 +915,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("hermes-inference-switch", { - displayName: "Inference: Hermes switches to native NVIDIA and remains responsive", + displayName: "Inference: Hermes switches to NVIDIA and preserves Discord across rebuild", agentRuntime: "hermes", environmentOrInferenceEndpoint: "Ubuntu; native NVIDIA Endpoints provider", profile: "nvidia-api", @@ -934,7 +939,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_AGENT: "hermes", NEMOCLAW_SANDBOX_NAME: "e2e-hm-inf-switch", NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod", - NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3.5-super-vl-120b-a12b", NEMOCLAW_SWITCH_INFERENCE_API: "openai-completions", OPENSHELL_GATEWAY: "nemoclaw", }, @@ -1007,43 +1012,66 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_SANDBOX_NAME: "e2e-issue-4462", }, }), - ...HOSTED_PROVIDER_SMOKE_CASES.map((selected) => - dockerOnlyTarget(`hosted-inference-${selected.selector}`, { - displayName: `Inference: completes a native ${selected.label} agent request`, - agentRuntime: selected.selector === "hermes" ? "hermes" : "openclaw", - prAdvisorSelectable: true, - owningPaths: [ - "test/e2e/live/inference-routing-credential-scan.ts", - `managed-inference/provider-profiles/nemoclaw-${selected.selector}-inference-v1.yaml`, - ...(["openai", "anthropic", "hermes"].includes(selected.selector) - ? ["src/lib/inference/native-provider/", "src/lib/onboard/setup-inference.ts"] - : []), - ...(selected.selector === "hermes" ? ["src/lib/hermes-provider-auth.ts"] : []), - ], - environmentOrInferenceEndpoint: `Ubuntu; ${selected.label} hosted inference`, - profile: "hosted-inference", - releaseRequired: false, - testFile: "test/e2e/live/inference-routing-provider-smoke.test.ts", - selector: `^${selected.id}`, - timeoutMinutes: 30, - installMode: "none", - restoreCli: true, - exposeCliBin: true, - environment: { NEMOCLAW_INFERENCE_ROUTING_PROVIDER_SMOKE: selected.selector }, - }), - ), + dockerOnlyTarget("hosted-inference-openrouter", { + displayName: "Inference: completes native OpenRouter agent requests", + agentRuntime: "openclaw + langchain-deepagents-code", + prAdvisorSelectable: true, + owningPaths: [ + "test/e2e/live/inference-routing-credential-scan.ts", + "managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml", + "agents/langchain-deepagents-code/managed-dcode-runtime.py", + "agents/langchain-deepagents-code/generate-config.ts", + "src/lib/inference/managed-dcode/", + ], + environmentOrInferenceEndpoint: "Ubuntu; OpenRouter hosted inference", + profile: "hosted-inference", + releaseRequired: false, + testFile: "test/e2e/live/inference-routing-provider-smoke.test.ts", + selector: OPENROUTER_SMOKE.id, + timeoutMinutes: 90, + installMode: "none", + restoreCli: true, + exposeCliBin: true, + environment: { NEMOCLAW_INFERENCE_ROUTING_PROVIDER_SMOKE: "openrouter" }, + }), managedRuntimeTarget("inference-routing", { displayName: "Inference: rejects unsafe routes and proves runtime identities", agentRuntime: "openclaw + langchain-deepagents-code", environmentOrInferenceEndpoint: "Ubuntu; local compatible and HTTPS inference fixtures", profile: "standard", - timeoutMinutes: ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES, + timeoutMinutes: INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES, installMode: "none", restoreCli: true, exposeCliBin: false, cloudflared: true, owningPaths: ["tools/e2e/onboard-timeout-contract.mts"], }), + managedRuntimeTarget("inference-routing-openclaw-native", { + testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + selector: "^TC-INF-1", + displayName: "Inference: OpenClaw native local requests and isolation", + agentRuntime: "openclaw", + environmentOrInferenceEndpoint: + "Ubuntu; authenticated llama.cpp and credentialless vLLM fixtures; skips WSL-only TC-INF-19", + profile: "standard", + timeoutMinutes: OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, + installMode: "none", + restoreCli: true, + exposeCliBin: false, + owningPaths: [ + "src/lib/actions/inference-set/native-local.ts", + "src/lib/actions/inference-set/local-runtime.ts", + "src/lib/inference/native-local/", + "src/lib/onboard/openclaw/initial-inference-route.ts", + "src/lib/onboard/setup-inference.ts", + "src/lib/actions/sandbox/rebuild-preflight-guards.ts", + "src/lib/actions/sandbox/inference-invocation-probe.ts", + "src/lib/actions/sandbox/inference-route-health.ts", + "test/e2e/fixtures/inference-routing-openclaw-native.ts", + "test/e2e/fixtures/native-local-ipv6-evidence.ts", + "tools/e2e/onboard-timeout-contract.mts", + ], + }), dockerOnlyTarget("llama-cpp-generic-gpu", { displayName: "Inference: completes an agent turn with llama.cpp on a generic NVIDIA GPU", agentRuntime: "openclaw", @@ -1091,6 +1119,9 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ installMode: "none", restoreCli: true, exposeCliBin: true, + // ubuntu-latest (26.04) ships only Python 3.14, which Model Router does not + // yet support (src/lib/onboard/model-router-python.ts). Pin until 3.14 is qualified. + runner: "ubuntu-24.04", owningPaths: [ "nemoclaw-blueprint/router/pool-config.yaml", "src/lib/actions/sandbox/destroy-preflight.ts", @@ -1153,10 +1184,11 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu Docker host; local onboarding fixtures", profile: "standard", - timeoutMinutes: 75, + timeoutMinutes: ONBOARD_REPAIR_TARGET_TIMEOUT_MINUTES, installMode: "authenticated", restoreCli: true, exposeCliBin: true, + owningPaths: ["tools/e2e/onboard-timeout-contract.mts"], environment: { ...nonInteractive, NEMOCLAW_SANDBOX_NAME: "e2e-repair" }, }), managedRuntimeTarget("onboard-policy-preset-sequencing", { @@ -1225,6 +1257,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("openclaw-inference-switch", { + selector: "^openclaw-inference-switch:", displayName: "Inference: OpenClaw switches to native NVIDIA and remains responsive", agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; native NVIDIA Endpoints provider", @@ -1246,6 +1279,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ "src/lib/onboard/machine/handlers/sandbox.ts", "src/lib/onboard/openclaw-setup.ts", "src/lib/onboard/openclaw/initial-inference-route.ts", + "src/lib/onboard/sandbox-prebuild.ts", "src/lib/onboard/sandbox-recreate-transaction.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", "test/e2e/live/public-nvidia-switch-provider.ts", @@ -1261,12 +1295,13 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_E2E_SHARD: "native-nvidia", NEMOCLAW_SANDBOX_NAME: "e2e-oc-inf-switch", NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod", - NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3.5-super-vl-120b-a12b", NEMOCLAW_SWITCH_INFERENCE_API: "openai-completions", OPENSHELL_GATEWAY: "nemoclaw", }, }), managedRuntimeTarget("openclaw-compatible-anthropic-inference-switch", { + selector: "^openclaw-inference-switch:", targetId: "openclaw-inference-switch", displayName: "Inference: OpenClaw switches to an Anthropic-compatible endpoint", agentRuntime: "openclaw", @@ -1280,6 +1315,9 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ shard: "anthropic", owningPaths: [ "src/lib/actions/inference-set.ts", + "src/lib/actions/inference-set/native.ts", + "src/lib/inference/native-provider/", + "src/lib/onboard/setup-inference.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", ], environment: { @@ -1291,6 +1329,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_SWITCH_NATIVE_CUSTOM: "1", OPENSHELL_GATEWAY: "nemoclaw", }, }), @@ -1316,10 +1355,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ targetId: "pi-agent-qualification", displayName: "Pi: qualifies managed runtime on Linux AMD64", agentRuntime: "pi", - environmentOrInferenceEndpoint: "Linux AMD64 Docker; NVIDIA hosted inference", + environmentOrInferenceEndpoint: "Linux AMD64 Docker; NVIDIA hosted and native-local inference", profile: "nvidia-api", testFile: "test/e2e/live/pi-agent-qualification.test.ts", - timeoutMinutes: 100, + timeoutMinutes: PI_QUALIFICATION_TARGET_TIMEOUT_MINUTES, installMode: "authenticated", installNonInteractive: true, restoreCli: true, @@ -1329,6 +1368,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ shard: "linux-amd64", owningPaths: [ ...PI_IMAGE_SOURCE_OWNING_PATHS, + "tools/e2e/onboard-timeout-contract.mts", "ci/pi-agent-qualification-v1-linux-amd64.json", "src/lib/agent/candidate-authority.ts", "src/lib/agent/candidate.ts", @@ -1341,7 +1381,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_CANDIDATE_AGENTS: "1", NEMOCLAW_CANDIDATE_QUALIFICATION_RECEIPT: "ci/pi-agent-qualification-v1-linux-amd64.json", NEMOCLAW_E2E_INFERENCE_MODE: "public-nvidia", - NEMOCLAW_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_MODEL: "nvidia/nemotron-3.5-super-vl-120b-a12b", NEMOCLAW_PI_QUALIFICATION_PLATFORM: "linux/amd64", NEMOCLAW_SANDBOX_NAME: "e2e-pi-qual-amd64", OPENSHELL_GATEWAY: "nemoclaw", @@ -1906,9 +1946,7 @@ export function catalogueMatrix( e2eRuntimeProviders(entry.gatewayRuntimes, gatewayRuntimes).map((runtimeProvider) => ({ ...(profile === "hosted-inference" ? { - model_env: HOSTED_PROVIDER_SMOKE_CASES.find( - (selected) => entry.id === `hosted-inference-${selected.selector}`, - )!.modelEnv, + model_env: OPENROUTER_SMOKE.modelEnv, } : {}), id: entry.id, @@ -1947,10 +1985,7 @@ export async function runCatalogueTarget(id: string, testFile: string): Promise< } Object.assign(process.env, entry.environment); if (entry.profile === "hosted-inference") { - const selectedEnvironment = hostedProviderSmokeEnvironment(id, process.env); - for (const selected of HOSTED_PROVIDER_SMOKE_CASES) delete process.env[selected.credential]; - delete process.env.HOSTED_INFERENCE_API_KEY; - Object.assign(process.env, selectedEnvironment); + configureOpenRouterSmokeEnvironment(process.env); } if (entry.exposeCliBin) { process.env.NEMOCLAW_CLI_BIN = path.join(process.cwd(), "bin", "nemoclaw.js"); From 5b68ff877bf9334d788fc810b4c7f68d51ecfc7d Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Mon, 26 Oct 2026 12:12:58 -0700 Subject: [PATCH 20/44] fix(inference): reconcile Ollama cleanup with current main Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-budget.json | 14 +- src/lib/inference/ollama/proxy.test.ts | 7 +- src/lib/onboard.ts | 2 + src/lib/onboard/setup-inference.test.ts | 713 ++++++++++++++++++- src/lib/onboard/setup-inference.ts | 191 +++-- test/e2e/live/gpu-double-onboard.test.ts | 117 ++- test/e2e/mock-parity.json | 6 +- test/support/setup-inference-test-harness.ts | 6 + tools/e2e/target-catalogue.mts | 12 +- 9 files changed, 977 insertions(+), 91 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index c15695e5515..8e7dca0b3c3 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 187, "direct": { - "expectCalls": 1270, - "matcherAssertions": 1250, + "expectCalls": 1269, + "matcherAssertions": 1249, "nodeAssertions": 108, "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2014, + "assertionPoints": 2013, "generatedProbeBlocks": 84, "generatedProbeConditions": 206 }, "unique": { - "expectCalls": 1698, - "matcherAssertions": 1673, + "expectCalls": 1697, + "matcherAssertions": 1672, "nodeAssertions": 131, "namedAssertionHelpers": 668, "failCalls": 1, "throwGuards": 531, "objectFieldAssertions": 266, - "assertionPoints": 3270, + "assertionPoints": 3269, "generatedProbeBlocks": 208, "generatedProbeConditions": 713 }, @@ -63,7 +63,7 @@ "test/e2e/live/double-onboard.test.ts": [46,51,46,51,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], - "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], + "test/e2e/live/gpu-double-onboard.test.ts": [20,23,20,23,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [9,19,16,58,12], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], diff --git a/src/lib/inference/ollama/proxy.test.ts b/src/lib/inference/ollama/proxy.test.ts index 6c84592b088..dc5b1a04fa5 100644 --- a/src/lib/inference/ollama/proxy.test.ts +++ b/src/lib/inference/ollama/proxy.test.ts @@ -130,6 +130,9 @@ function loadProxyWithMocks(setup: MockSetup): { describe("Ollama model ownership locks", () => { it("shares one lock across non-default gateway state roots", async () => { + const isolatedHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-lock-")); + const homedir = vi.spyOn(require("node:os") as typeof import("node:os"), "homedir"); + homedir.mockReturnValue(isolatedHome); vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); const originalProxy = require.cache[PROXY_DIST]; const originalLocal = require.cache[LOCAL_DIST]; @@ -190,8 +193,10 @@ describe("Ollama model ownership locks", () => { require.cache[STATE_PATHS_DIST] = originalStatePaths; require.cache[STATE_ROOT_DIST] = originalStateRoot; require.cache[CORE_PORTS_DIST] = originalCorePorts; + homedir.mockRestore(); + fs.rmSync(isolatedHome, { recursive: true, force: true }); } - }); + }, 15_000); }); describe("promptOllamaModel installed-model fit filter", () => { diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index d368b18c70b..26c7154c7b8 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2272,6 +2272,7 @@ const getSetupInferenceDeps = (): SetupInferenceDeps => ({ withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, step, getGatewayName: () => GATEWAY_NAME, + resolveOllamaOwnershipGateway: gatewayBinding.resolveSandboxGatewayName, runOpenshell, inferenceRouteMutator, inferenceRouteObserver, @@ -2325,6 +2326,7 @@ const getSetupInferenceDeps = (): SetupInferenceDeps => ({ error: (message: string) => console.error(message), exitProcess: (code: number): never => process.exit(code), }); + export type SetupInferenceDeps = import("./onboard/setup-inference").SetupInferenceDeps; export type SetupInference = import("./onboard/setup-inference").SetupInference; function createSetupInference(overrides: Partial = {}): SetupInference { diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index f318be8b6d0..916c2ff005c 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -1,13 +1,24 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import type { + OllamaModelCleanupOwner, + OllamaModelHolder, +} from "../inference/ollama/model-ownership"; +import type { OllamaUnloadResult } from "../inference/ollama/proxy"; +import type { SandboxEntry } from "../state/registry"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { createProviderReviewDeps, createSetupInference, + releaseSupersededOllamaModel, type SetupInferenceDeps, } from "./setup-inference"; @@ -17,6 +28,439 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); +function createOllamaCleanupHarness( + options: { + peers?: readonly SandboxEntry[]; + useProductionPeerSource?: boolean; + useProductionDiscovery?: boolean; + activeSandboxNames?: ReadonlySet; + discovery?: SetupInferenceDeps["discoverActiveOllamaSandboxNames"]; + pendingModels?: readonly string[]; + unloadResult?: OllamaUnloadResult; + } = {}, +) { + let pendingModels = [...(options.pendingModels ?? [])]; + const localInference = { + loadPersistedOllamaHost: vi.fn(() => "127.0.0.1"), + loadPendingOllamaModelCleanup: vi.fn((_owner: OllamaModelCleanupOwner) => pendingModels), + persistPendingOllamaModelCleanup: vi.fn( + (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { + pendingModels = [...new Set([...pendingModels, ...models])]; + }, + ), + clearPendingOllamaModelCleanup: vi.fn( + (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { + pendingModels = pendingModels.filter((model) => !models.includes(model)); + }, + ), + clearPersistedOllamaHostIfUnused: vi.fn(), + }; + const unloadOllamaModels = vi.fn( + () => + options.unloadResult ?? { + ok: true, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }, + ); + const discoverActiveOllamaSandboxNames = vi.fn( + options.discovery ?? + (() => ({ + ok: true as const, + activeSandboxNames: options.activeSandboxNames ?? new Set(), + gatewayChecks: [], + })), + ); + const deps = { + localInference, + ...(options.useProductionPeerSource + ? {} + : { listOllamaModelOwnershipPeers: () => options.peers ?? [] }), + ...(!options.useProductionDiscovery ? { discoverActiveOllamaSandboxNames } : {}), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + } as unknown as SetupInferenceDeps; + return { deps, localInference, unloadOllamaModels, discoverActiveOllamaSandboxNames }; +} + +const previousLocalOllamaRoute: OllamaModelHolder = { + name: "alpha", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-alpha", + lifecycleLiveIdentityFingerprint: "a".repeat(64), +}; + +function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): void { + releaseSupersededOllamaModel( + previous, + "nvidia-prod", + "nvidia/test-model", + "https://integrate.api.nvidia.com/v1", + { ok: true }, + deps, + ); +} + +describe("releaseSupersededOllamaModel", () => { + it("preserves the host target for a stopped peer after releasing its model", () => { + const stoppedPeer = { + name: "stopped-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434", + gatewayName: "nemoclaw-32678", + gatewayPort: 32678, + } as unknown as SandboxEntry; + const harness = createOllamaCleanupHarness({ peers: [stoppedPeer] }); + + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).toHaveBeenCalledExactlyOnceWith( + [stoppedPeer], + ); + }); + + it("releases the target model before unrelated gateway discovery for receipt retirement", () => { + const unrelatedPeer = { + name: "unrelated-peer", + provider: "ollama-local", + model: "llama3.2:1b", + endpointUrl: null, + gatewayName: "unavailable-gateway", + } as unknown as SandboxEntry; + const discovery = vi.fn((owners: readonly OllamaModelHolder[]) => + owners.some((owner) => owner.model === "llama3.2:1b") + ? { ok: false as const, message: "unrelated gateway unavailable" } + : { ok: true as const, activeSandboxNames: new Set(), gatewayChecks: [] }, + ); + const harness = createOllamaCleanupHarness({ peers: [unrelatedPeer], discovery }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(discovery).toHaveBeenCalledTimes(2); + expect(discovery.mock.calls[0]?.[0]).toEqual([]); + expect(discovery.mock.calls[1]?.[0]).toEqual([unrelatedPeer]); + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("host route receipt was retained"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("preserves the model and host receipt while a matching live peer owns it", () => { + const activePeer = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: null, + gatewayName: "peer-gateway-port", + } as unknown as SandboxEntry; + const harness = createOllamaCleanupHarness({ + peers: [activePeer], + activeSandboxNames: new Set([activePeer.name]), + }); + + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); + + it("uses Ollama peer records from other gateway roots by default", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-peer-roots-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "active-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + activeSandboxNames: new Set([peer.name]), + }); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); + expect(harness.discoverActiveOllamaSandboxNames.mock.calls[0]?.[0]).toEqual([ + expect.objectContaining({ name: "active-peer", gatewayName: "nemoclaw-32665" }), + ]); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("uses the injected phase capture for cross-gateway discovery", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "active-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + useProductionDiscovery: true, + }); + const captureOllamaOwnershipPhases = vi.fn(() => ({ + status: 0, + output: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", + })); + const deps = harness.deps as SetupInferenceDeps; + deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; + deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName!; + + try { + releaseToNvidia(previousLocalOllamaRoute, deps); + + expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( + "nemoclaw-32665", + process.env, + ); + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("fails closed and records retry state when a successful inventory omits a matching peer", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-omitted-inventory-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "stale-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "stale-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + useProductionDiscovery: true, + }); + const captureOllamaOwnershipPhases = vi.fn(() => ({ + status: 0, + output: "NAME CREATED PHASE", + })); + const deps = harness.deps as SetupInferenceDeps; + deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; + deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName ?? "default"; + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( + "nemoclaw-32665", + process.env, + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); + } finally { + warning.mockRestore(); + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("records a failed ownership probe for retry, then unloads only after a safe retry", () => { + const discovery = vi + .fn>() + .mockReturnValueOnce({ ok: false, message: "gateway unavailable" }) + .mockReturnValueOnce({ ok: true, activeSandboxNames: new Set(), gatewayChecks: [] }); + const harness = createOllamaCleanupHarness({ discovery }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); + + releaseToNvidia({ ...previousLocalOllamaRoute, provider: "nvidia-prod" }, harness.deps); + + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + expect.objectContaining({ + name: "alpha", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-alpha", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + }), + ["qwen2.5:1.5b"], + ); + } finally { + warning.mockRestore(); + } + }); + + it("requires manual recovery when ownership failure cannot be recorded for retry", () => { + const discovery = vi.fn>( + () => ({ ok: false, message: "gateway unavailable" }), + ); + const harness = createOllamaCleanupHarness({ discovery }); + harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { + throw new Error( + "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", + ); + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia( + { + ...previousLocalOllamaRoute, + lifecycleGeneration: undefined, + lifecycleLiveIdentityFingerprint: undefined, + }, + harness.deps, + ); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining( + "Manually verify that no active matching sandbox owns the model before releasing only qwen2.5:1.5b", + ), + ); + expect(warning).not.toHaveBeenCalledWith( + expect.stringContaining("Re-run onboarding to retry only"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("keeps the retry record when unloading the superseded model fails", () => { + const harness = createOllamaCleanupHarness({ + unloadResult: { + ok: false, + outcome: "still-resident", + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }, + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(harness.localInference.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("Re-run onboarding or destroy 'alpha' to retry only"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("does not probe or warn when the selected route still owns the same Ollama model", () => { + const harness = createOllamaCleanupHarness(); + + releaseSupersededOllamaModel( + previousLocalOllamaRoute, + "ollama-local", + "qwen2.5:1.5b", + "http://127.0.0.1:11434", + { ok: true }, + harness.deps, + ); + + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); + + it("does not probe unrelated routes when there is no Ollama cleanup retry", () => { + const harness = createOllamaCleanupHarness({ + peers: [{ name: "ollama-peer", provider: "ollama-local", model: "qwen2.5:1.5b" }], + }); + + releaseToNvidia( + { name: "alpha", provider: "nvidia-prod", model: "nvidia/model" }, + harness.deps, + ); + + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + + }); +}); + describe("recorded Pi local inference route", () => { it("rejects a changed selection before invoking a provider or gateway", async () => { const getSandbox = vi.fn(() => ({ @@ -343,7 +787,22 @@ describe("native NVIDIA onboarding", () => { createProvider, } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); - const updateSandbox = vi.fn(() => true); + const events: string[] = []; + const updateSandbox = vi.fn(() => { + events.push("route-published"); + return true; + }); + const unloadOllamaModels = vi.fn(() => { + events.push("unload"); + return { + ok: true as const, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }; + }); const setNativeNvidiaProviderAuthority = vi.fn(() => true); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); @@ -358,7 +817,28 @@ describe("native NVIDIA onboarding", () => { runOpenshell, updateSandbox, setNativeNvidiaProviderAuthority, - getSandbox: () => null, + getSandbox: () => previousLocalOllamaRoute, + localInference: { + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + persistPendingOllamaModelCleanup: vi.fn(), + clearPendingOllamaModelCleanup: vi.fn(), + clearPersistedOllamaHostIfUnused: vi.fn(), + }, + listOllamaModelOwnershipPeers: () => [], + discoverActiveOllamaSandboxNames: () => ({ + ok: true as const, + activeSandboxNames: new Set(), + gatewayChecks: [], + }), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + withOllamaModelOwnershipTransaction: async (operation: () => Promise | T) => { + events.push("ownership-transaction-start"); + const result = await operation(); + events.push("ownership-transaction-end"); + return result; + }, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute, verifyOnboardInferenceSmoke, @@ -423,6 +903,10 @@ describe("native NVIDIA onboarding", () => { }, }), ); + expect(events.indexOf("route-published")).toBeLessThan(events.indexOf("unload")); + expect(events[0]).toBe("ownership-transaction-start"); + expect(events.at(-1)).toBe("ownership-transaction-end"); + expect(unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("onboarding-gateway", { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", @@ -728,3 +1212,228 @@ describe("native NVIDIA onboarding", () => { expect(updateSandbox).not.toHaveBeenCalled(); }); }); + +describe("concurrent Ollama ownership transactions", () => { + it("serializes route publication before superseded-model release (#12677)", async () => { + const events: string[] = []; + const registry = new Map([ + [ + "alpha", + { + name: "alpha", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434/v1", + gatewayName: "gateway-alpha", + }, + ], + [ + "beta", + { + name: "beta", + provider: "compatible-endpoint", + model: "previous-model", + endpointUrl: "https://previous.example/v1", + gatewayName: "gateway-beta", + }, + ], + ]); + let signalBetaRouteStarted!: () => void; + let signalAlphaRouteStarted!: () => void; + let releaseBetaRoute!: () => void; + let signalAlphaQueued!: () => void; + const betaRouteStarted = new Promise((resolve) => { + signalBetaRouteStarted = resolve; + }); + const alphaRouteStarted = new Promise((resolve) => { + signalAlphaRouteStarted = resolve; + }); + const allowBetaRouteToFinish = new Promise((resolve) => { + releaseBetaRoute = resolve; + }); + const alphaQueuedForTransaction = new Promise((resolve) => { + signalAlphaQueued = resolve; + }); + const transactionLabels = ["gateway-beta", "gateway-alpha"]; + let transactionTail = Promise.resolve(); + let transactionCalls = 0; + const withOwnershipTransaction: NonNullable< + SetupInferenceDeps["withOllamaModelOwnershipTransaction"] + > = async (operation: () => Promise | T): Promise => { + transactionCalls += 1; + const label = transactionLabels[transactionCalls - 1] ?? "unknown"; + events.push(`transaction-request:${label}`); + [() => undefined, signalAlphaQueued][transactionCalls - 1]?.(); + const previous = transactionTail; + let release!: () => void; + transactionTail = new Promise((resolve) => { + release = resolve; + }); + await previous; + events.push(`transaction-enter:${label}`); + try { + const result = await operation(); + events.push(`transaction-exit:${label}`); + return result; + } finally { + release(); + } + }; + const signalRouteStarted: Record void> = { + "gateway-alpha": signalAlphaRouteStarted, + "gateway-beta": signalBetaRouteStarted, + }; + const inferenceRouteMutator: SetupInferenceDeps["inferenceRouteMutator"] = { + setInferenceRoute: async (request) => { + const gateway = request.target.gatewayName; + events.push(`route-start:${gateway}`); + signalRouteStarted[gateway]?.(); + await (gateway === "gateway-beta" ? allowBetaRouteToFinish : Promise.resolve()); + events.push(`route-finished:${gateway}`); + return { ok: true }; + }, + }; + const updateSandbox: SetupInferenceDeps["updateSandbox"] = (name, route) => { + const previous = registry.get(name); + registry.set(name, { ...previous, ...route, name } as OllamaModelHolder); + events.push(`registry-published:${name}`); + return true; + }; + const listOllamaModelOwnershipPeers = vi.fn(() => { + events.push("peer-discovery"); + return [...registry.values()]; + }); + const unloadOllamaModels = vi.fn(() => { + events.push("unload"); + return { + ok: true as const, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }; + }); + const localInference = { + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => [], + persistPendingOllamaModelCleanup: vi.fn(), + clearPendingOllamaModelCleanup: vi.fn(), + clearPersistedOllamaHostIfUnused: vi.fn(), + }; + const deps = { + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "gateway-default", + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + inferenceRouteMutator, + inferenceRouteObserver: { + observeInferenceRoute: vi.fn(async () => ({ ok: true as const })), + } as unknown as SetupInferenceDeps["inferenceRouteObserver"], + updateSandbox, + getSandbox: (name: string) => registry.get(name) ?? null, + listOllamaModelOwnershipPeers, + discoverActiveOllamaSandboxNames: (owners: readonly OllamaModelHolder[]) => ({ + ok: true as const, + activeSandboxNames: new Set(owners.map((owner) => owner.name)), + gatewayChecks: [], + }), + localInference, + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + withOllamaModelOwnershipTransaction: withOwnershipTransaction, + upsertProvider: vi.fn(async () => ({ ok: true as const })), + bedrockRuntimeOnboard: { + setupBedrockRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + openrouterRuntimeOnboard: { + setupOpenRouterRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + isNonInteractive: () => true, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + hydrateCredentialEnv: vi.fn(() => "test-compatible-api-key"), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + localInferenceTimeoutSecs: 30, + vllmLocalCredentialEnv: "VLLM_API_KEY", + ollamaProxyCredentialEnv: "NEMOCLAW_OLLAMA_PROXY_TOKEN", + isRoutedInferenceProvider: () => false, + } as unknown as SetupInferenceDeps; + const setupAlpha = createSetupInference(deps); + const setupBeta = createSetupInference(deps); + const betaSwitch = setupBeta( + "beta", + "qwen2.5:1.5b", + "compatible-endpoint", + "http://127.0.0.1:11434/v1", + "COMPATIBLE_API_KEY", + null, + [], + { + gatewayName: "gateway-beta", + endpointPinnedAddresses: ["127.0.0.1"], + skipHostInferenceSmoke: true, + }, + ); + + await betaRouteStarted; + const alphaSwitch = setupAlpha( + "alpha", + "other-model", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { + gatewayName: "gateway-alpha", + endpointPinnedAddresses: ["93.184.216.34"], + skipHostInferenceSmoke: true, + }, + ); + const alphaOrder = await Promise.race([ + alphaQueuedForTransaction.then(() => "queued"), + alphaRouteStarted.then(() => "route-started"), + ]); + releaseBetaRoute(); + await expect(Promise.all([alphaSwitch, betaSwitch])).resolves.toEqual([ + { ok: true }, + { ok: true }, + ]); + + expect(alphaOrder).toBe("queued"); + expect(events).toContain("registry-published:beta"); + expect(events).toContain("route-start:gateway-alpha"); + expect(events).toContain("transaction-exit:gateway-beta"); + expect(events).toContain("transaction-exit:gateway-alpha"); + expect(events).toContain("peer-discovery"); + expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( + events.indexOf("route-start:gateway-alpha"), + ); + expect(events.indexOf("registry-published:beta")).toBeLessThan( + events.indexOf("route-start:gateway-alpha"), + ); + expect(events.indexOf("transaction-exit:gateway-beta")).toBeLessThan( + events.indexOf("peer-discovery"), + ); + expect(events.indexOf("registry-published:alpha")).toBeLessThan( + events.indexOf("peer-discovery"), + ); + expect(events.indexOf("peer-discovery")).toBeLessThan( + events.indexOf("transaction-exit:gateway-alpha"), + ); + expect(listOllamaModelOwnershipPeers).toHaveBeenCalledOnce(); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + }, 20_000); +}); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 93806f2d1a4..91e862e9de5 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -59,11 +59,16 @@ import { } from "../inference/native-nvidia"; import { clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, + listOllamaModelOwnershipPeersAcrossGatewayRoots, loadPendingOllamaModelCleanup, + matchingOllamaModelPeers, + type OllamaActiveOwnershipDiscoveryFn, type OllamaModelHolder, + type OllamaOwnershipPhaseCapture, persistPendingOllamaModelCleanup, - supersededOllamaModel, + supersededOllamaModelWithActivePeers, } from "../inference/ollama/model-ownership"; import { getOllamaProxyToken, @@ -75,9 +80,10 @@ import { } from "../inference/ollama/proxy"; import { assertNoOpenShellGatewayEndpointOverride, + captureSandboxPhasesForGateway, scopeGatewayOpenshellArgs, type OpenShellGatewayEndpointEnvironment, -} from "../adapters/openshell/gateway-scope"; +} from "../adapters/openshell/runtime"; import type { withSandboxMutationLock } from "../state/mcp-lifecycle-lock"; import type { Session } from "../state/onboard-session"; import type { SandboxEntry } from "../state/registry/types"; @@ -274,6 +280,11 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // #9110 optional GPU-release seams; omitted by test literals that build deps // by hand, so every read below must stay optional-chained. getSandbox?: typeof import("../state/registry").getSandbox; + listOllamaModelOwnershipPeers?: () => readonly OllamaModelHolder[]; + discoverActiveOllamaSandboxNames?: OllamaActiveOwnershipDiscoveryFn; + captureOllamaOwnershipPhases?: OllamaOwnershipPhaseCapture; + resolveOllamaOwnershipGateway?: (peer: OllamaModelHolder) => string; + environment?: NodeJS.ProcessEnv; listSandboxes?: typeof import("../state/registry").listSandboxes; getNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").getNativeLocalProviderAuthority; setNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").setNativeLocalProviderAuthority; @@ -556,7 +567,7 @@ export type SetupInference = ( * the route is committed by this point, so GPU cleanup must never change the * result or the exit code. */ -function releaseSupersededOllamaModel( +export function releaseSupersededOllamaModel( previous: OllamaModelHolder | null, nextProvider: string, nextModel: string, @@ -581,7 +592,7 @@ function releaseSupersededOllamaModel( const persistRetry = (): string | null => { if (attemptedModels.length === 0) return null; try { - persistPending(previous.name, attemptedModels); + persistPending(previous, attemptedModels); return null; } catch (error) { return (error instanceof Error ? error.message : String(error)) @@ -592,34 +603,85 @@ function releaseSupersededOllamaModel( try { const withOwnershipLock = deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; withOwnershipLock(() => { - const peers = deps.listSandboxes?.().sandboxes ?? []; const selectedHost = deps.localInference.loadPersistedOllamaHost?.() ?? null; - const nextRoute = { - provider: nextProvider, - model: nextModel, - endpointUrl: nextEndpointUrl, - }; - const superseded = supersededOllamaModel(previous, nextRoute, peers, selectedHost); - const pending = loadPending(previous.name); - const retryablePending = pending.filter((model) => - supersededOllamaModel( - { - name: previous.name, - provider: "ollama-local", - model, - endpointUrl: null, - }, + const nextRoute = { provider: nextProvider, model: nextModel, endpointUrl: nextEndpointUrl }; + const previousOwnsOllama = isLocalOllamaRouteOwner(previous, selectedHost); + // This is only a retry candidate. A successful live probe below is still + // required before the model can be unloaded. + const retryCandidate = previousOwnsOllama + ? supersededOllamaModelWithActivePeers(previous, nextRoute, [], new Set(), selectedHost) + : null; + attemptedModels = retryCandidate ? [retryCandidate] : []; + const pending = loadPending(previous); + attemptedModels = [...new Set([...attemptedModels, ...pending])]; + if (!retryCandidate && pending.length === 0) return; + + const peers = ( + deps.listOllamaModelOwnershipPeers ?? listOllamaModelOwnershipPeersAcrossGatewayRoots + )(); + const ollamaRouteCandidates = peers.filter((peer) => + isLocalOllamaRouteOwner(peer, selectedHost), + ); + const environment = deps.environment ?? process.env; + const captureOwnershipPhases: OllamaOwnershipPhaseCapture = + deps.captureOllamaOwnershipPhases ?? captureSandboxPhasesForGateway; + const discoverPeers = (owners: readonly OllamaModelHolder[]) => + deps.discoverActiveOllamaSandboxNames + ? deps.discoverActiveOllamaSandboxNames(owners, environment) + : discoverOllamaModelOwnership(owners, environment, captureOwnershipPhases, { + resolvePersistedSandboxOwnershipGateway: deps.resolveOllamaOwnershipGateway, + }); + // A different model cannot keep one of the models being released resident. + // Discover only matching owners before unloading so unrelated gateways do + // not delay cleanup; all-route discovery is reserved for receipt retirement. + const modelOwners = [ + ...new Set( + attemptedModels.flatMap((model) => + matchingOllamaModelPeers( + { ...previous, provider: "ollama-local", model, endpointUrl: null }, + ollamaRouteCandidates, + selectedHost, + ), + ), + ), + ]; + const discovery = discoverPeers(modelOwners); + if (!discovery.ok) { + pendingRecordFailure = persistRetry(); + const retryMessage = pendingRecordFailure + ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}. Manually verify that no active matching sandbox owns the model before releasing only ${attemptedModels.join(", ")} from the local Ollama host.` + : attemptedModels.length > 0 + ? `Re-run onboarding to retry only: ${attemptedModels.join(", ")}.` + : "The Ollama host receipt was left unchanged."; + cleanupWarning = + ` Warning: NemoClaw could not verify Ollama model ownership for '${previous.name}': ` + + `${discovery.message}. No model was unloaded; the new inference route remains active. ${retryMessage}`; + return; + } + const superseded = previousOwnsOllama + ? supersededOllamaModelWithActivePeers( + previous, + nextRoute, + peers, + discovery.activeSandboxNames, + selectedHost, + discovery.activePeers, + ) + : null; + const retryablePending = pending.filter((model) => { + return !!supersededOllamaModelWithActivePeers( + { ...previous, provider: "ollama-local", model, endpointUrl: null }, nextRoute, peers, + discovery.activeSandboxNames, selectedHost, - ), - ); + discovery.activePeers, + ); + }); attemptedModels = [...new Set([...(superseded ? [superseded] : []), ...retryablePending])]; - const retireRoute = - isLocalOllamaRouteOwner(previous, selectedHost) && - !isLocalOllamaRouteOwner(nextRoute, selectedHost) && - !peers.some((peer) => isLocalOllamaRouteOwner(peer, selectedHost)); - if (attemptedModels.length === 0 && !retireRoute) return; + const retireRouteCandidate = + previousOwnsOllama && !isLocalOllamaRouteOwner(nextRoute, selectedHost); + if (attemptedModels.length === 0 && !retireRouteCandidate) return; try { revalidateSandboxIdentity?.("release the superseded Ollama model"); } catch (error) { @@ -651,7 +713,7 @@ function releaseSupersededOllamaModel( ? `Cleanup retry state could not be recorded: ${pendingRecordFailure}. Manually release only ${attemptedModels.join(", ")} at ${cleanup.endpoint}.` : `Re-run onboarding or destroy '${previous.name}' to retry only: ${attemptedModels.join(", ")}.`); } else { - clearPending(previous.name, attemptedModels); + clearPending(previous, attemptedModels); } } catch (error) { if (pendingRecordFailure) pendingRecordFailure = persistRetry(); @@ -666,9 +728,29 @@ function releaseSupersededOllamaModel( : `Re-run onboarding or destroy '${previous.name}' to retry only the recorded models: ${attemptedModels.join(", ")}.`); } } - const pendingAfterCleanup = loadPending(previous.name); - if (retireRoute && !cleanupWarning && pendingAfterCleanup.length === 0) { - deps.localInference.clearPersistedOllamaHostIfUnused?.(peers); + const pendingAfterCleanup = loadPending(previous); + if (retireRouteCandidate && !cleanupWarning && pendingAfterCleanup.length === 0) { + const routeOwnerDiscovery = + modelOwners.length === ollamaRouteCandidates.length + ? discovery + : discoverPeers(ollamaRouteCandidates); + if (!routeOwnerDiscovery.ok) { + cleanupWarning = + ` Warning: Ollama cleanup for '${previous.name}' was scoped to verified model owners, ` + + "but the host route receipt was retained because other Ollama gateway owners could not be verified."; + } else { + const activeOllamaPeerRoutes = peers.filter( + (peer) => + (routeOwnerDiscovery.activePeers + ? routeOwnerDiscovery.activePeers.has(peer) + : routeOwnerDiscovery.activeSandboxNames.has(peer.name)) && + isLocalOllamaRouteOwner(peer, selectedHost), + ); + if (activeOllamaPeerRoutes.length === 0) { + // Stopped registry owners still need the shared host target if they restart. + deps.localInference.clearPersistedOllamaHostIfUnused?.(ollamaRouteCandidates); + } + } } }); } catch (error) { @@ -2068,24 +2150,37 @@ export function createSetupInference( selectingNativeLocal = selectingNativeLocal && !preservingLegacyPiRoute; if (selectingNativeLocal) await (deps.requireNativeProviderPolicy ?? requireNativeProviderPolicy)(gatewayName); - const result = await mutateGatewayRoute(); - releaseSupersededOllamaModel( - previousSandbox, - provider, - model, - endpointUrl, - result, - deps, - revalidateSandboxIdentity, - ); - if (shouldLogSuccessfulRoute && "ok" in result) { - deps.log( - isNativeNvidiaProvider(provider) - ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` - : ` ✓ Inference route set: ${provider} / ${model}`, + + // Compatible endpoints can own the same host Ollama daemon as direct Ollama routes. + // Serialize publication with release decisions across gateways to prevent a newly + // published peer route from being missed by concurrent cleanup (#12677). + const participatesInOllamaOwnership = + (previousSandbox !== null && isLocalOllamaRouteOwner(previousSandbox)) || + isLocalOllamaRouteOwner({ provider, endpointUrl }); + const runRouteAndRelease = async (): Promise => { + const result = await mutateGatewayRoute(); + releaseSupersededOllamaModel( + previousSandbox, + provider, + model, + endpointUrl, + result, + deps, + revalidateSandboxIdentity, ); - } - return result; + if (shouldLogSuccessfulRoute && "ok" in result) { + deps.log( + isNativeNvidiaProvider(provider) + ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` + : ` ✓ Inference route set: ${provider} / ${model}`, + ); + } + return result; + }; + if (!participatesInOllamaOwnership) return runRouteAndRelease(); + const withOwnershipTransaction = + deps.withOllamaModelOwnershipTransaction ?? withOllamaModelOwnershipTransaction; + return withOwnershipTransaction(runRouteAndRelease); }; return sandboxName ? deps.withSandboxMutationLock(sandboxName, mutateGatewayRouteAndReleaseSupersededModel) diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 786ee92beea..08c7b53b072 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -13,13 +13,18 @@ import { cleanupWhenCommandAvailable, cleanupWhenOpenShellAvailable, } from "../fixtures/cleanup-resources.ts"; -import { resultText } from "../fixtures/clients/command.ts"; +import { resultText, shellQuote } from "../fixtures/clients/command.ts"; import { type HostCliClient } from "../fixtures/clients/host.ts"; import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { nativeLocalChatCommand } from "../fixtures/native-local-chat.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { + PUBLIC_NVIDIA_SWITCH_MODEL, + PUBLIC_NVIDIA_SWITCH_PROVIDER, + requirePublicNvidiaSwitchKey, +} from "./public-nvidia-switch-provider.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-gpu-double"; const PROXY_PORT = process.env.NEMOCLAW_OLLAMA_PROXY_PORT ?? "11435"; @@ -52,10 +57,12 @@ async function nemoclaw( artifactName: string, extraEnv: NodeJS.ProcessEnv = {}, timeoutMs = 20 * 60_000, + redactionValues: string[] = [], ): Promise { return await host.command(process.execPath, [CLI_ENTRYPOINT, ...args], { artifactName, env: env(extraEnv), + redactionValues, timeoutMs, }); } @@ -121,10 +128,6 @@ function parseReplyCommand(): string { return String.raw`python3 -c 'import json,sys; d=json.load(sys.stdin); m=d["choices"][0]["message"]; print((m.get("content") or m.get("reasoning_content") or m.get("reasoning") or "").strip())'`; } -function fileMode(pathname: string): string { - return (fs.statSync(pathname).mode & 0o777).toString(8).padStart(3, "0"); -} - function chatRequest(model: string): string { return JSON.stringify({ model, @@ -138,23 +141,27 @@ function chatRequest(model: string): string { }); } -async function expectSandboxInference42( +async function querySandboxForAnswer( sandbox: SandboxClient, model: string, artifactName: string, -): Promise { + sharedRoute = false, +): Promise { // OpenClaw local inference uses a sandbox-owned provider behind the auth proxy, not the shared // gateway route (#13293). Re-read it after re-onboarding recreates the sandbox. A missing - // attachment yields an unresolvable host, which fails the request assertion below. + // attachment yields an unresolvable host. Provider switch uses the shared route. const endpoint = normalizeNativeLocalProviderAttachment(getSandbox(SANDBOX_NAME)?.nativeLocalProviderAttachment) ?.endpointUrl ?? "http://missing-native-local-attachment.invalid/v1"; - const response = await sandbox.exec( + const command = sharedRoute + ? `curl -fsS --max-time 120 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(chatRequest(model))}` + : nativeLocalChatCommand(endpoint, chatRequest(model), "-fsS"); + return await sandbox.exec( SANDBOX_NAME, [ "sh", "-lc", - `${nativeLocalChatCommand(endpoint, chatRequest(model), "-fsS")} | ${parseReplyCommand()}`, + `${command} | ${parseReplyCommand()}`, ], { artifactName, @@ -162,12 +169,20 @@ async function expectSandboxInference42( timeoutMs: 150_000, }, ); +} + +async function expectSandboxInference42( + sandbox: SandboxClient, + model: string, + artifactName: string, +): Promise { + const response = await querySandboxForAnswer(sandbox, model, artifactName); expect(response.exitCode, resultText(response)).toBe(0); expect(containsAnswer(response.stdout, "42"), resultText(response)).toBe(true); } test( - "gpu double onboard keeps Ollama auth proxy token consistent after re-onboard", + "gpu double onboard preserves proxy auth and unloads Ollama on provider switch", { timeout: LIVE_TIMEOUT_MS, meta: { @@ -178,6 +193,9 @@ test( "validate first proxy token and inference", "re-onboard GPU sandbox", "validate persisted proxy auth and inference", + "verify the Ollama model is active before switching providers", + "switch inference to a non-Ollama provider", + "verify new-provider inference and confirm Ollama unloaded the old model", "remove GPU double-onboard sandbox", ], }, @@ -189,6 +207,7 @@ test( progress, runtimeProvider, sandbox, + secrets, skip, }) => { await artifacts.target.declare({ @@ -198,13 +217,17 @@ test( contracts: [ "GPU and runtime prerequisites are present", "install.sh onboards with the Ollama provider", - "the persisted Ollama auth-proxy token works after first onboard", + "sandbox inference.local reaches Ollama after first onboard", "nemoclaw onboard --non-interactive --yes recreates the sandbox", "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", "the sandbox-owned native provider reaches Ollama after first onboard and re-onboard", + "Ollama reports the selected model as active before the provider switch", + "nemoclaw inference set switches the sandbox to the public NVIDIA provider", + "sandbox inference succeeds through the new provider and host ollama ps no longer reports the superseded model", ], }); + const publicApiKey = requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")); await runtimeProvider.requireAvailable({ artifactName: "phase-0-runtime-info", scenarioLabel: "GPU double-onboard", @@ -339,23 +362,10 @@ exit "$status"`, expect(first.exitCode, resultText(first)).toBe(0); progress.phase("validate first proxy token and inference"); - const list = await nemoclaw(host, ["list"], "phase-3-nemoclaw-list"); - expect(list.exitCode, resultText(list)).toBe(0); - expect(list.stdout).toContain(SANDBOX_NAME); - expect(fs.existsSync(TOKEN_FILE), `${TOKEN_FILE} missing`).toBe(true); const tokenAfterFirst = fs.readFileSync(TOKEN_FILE, "utf8").trim(); expect(tokenAfterFirst.length).toBeGreaterThan(10); - expect(fileMode(TOKEN_FILE)).toBe("600"); const model = GPU_E2E_MODEL; - - const firstTokenStatus = await httpStatus( - host, - `http://127.0.0.1:${PROXY_PORT}/v1/models`, - "phase-3-proxy-token-status", - tokenAfterFirst, - ); - expect(firstTokenStatus.stdout.trim(), resultText(firstTokenStatus)).toBe("200"); await expectSandboxInference42(sandbox, model, "phase-3-sandbox-inference-first-onboard"); progress.phase("re-onboard GPU sandbox"); @@ -367,10 +377,7 @@ exit "$status"`, execTimeout(30 * 60_000), ); expect(reonboard.exitCode, resultText(reonboard)).toBe(0); - expect(fs.existsSync(TOKEN_FILE), `${TOKEN_FILE} missing after re-onboard`).toBe(true); const tokenAfterSecond = fs.readFileSync(TOKEN_FILE, "utf8").trim(); - expect(tokenAfterSecond.length).toBeGreaterThan(10); - expect(fileMode(TOKEN_FILE)).toBe("600"); expect(tokenAfterSecond).toBe(tokenAfterFirst); progress.phase("validate persisted proxy auth and inference"); @@ -406,6 +413,54 @@ exit "$status"`, await expectSandboxInference42(sandbox, model, "phase-6-sandbox-inference-after-reonboard"); + progress.phase("verify the Ollama model is active before switching providers"); + const activeModelsBeforeSwitch = await host.command("ollama", ["ps"], { + artifactName: "phase-7-ollama-ps-before-provider-switch", + env: env(), + timeoutMs: 30_000, + }); + expect(activeModelsBeforeSwitch.exitCode, resultText(activeModelsBeforeSwitch)).toBe(0); + expect(activeModelsBeforeSwitch.stdout).toContain(model); + + progress.phase("switch inference to a non-Ollama provider"); + const providerSwitch = await nemoclaw( + host, + [ + "inference", + "set", + "--provider", + PUBLIC_NVIDIA_SWITCH_PROVIDER, + "--model", + PUBLIC_NVIDIA_SWITCH_MODEL, + "--sandbox", + SANDBOX_NAME, + ], + "phase-8-inference-set-away-from-ollama", + { NVIDIA_INFERENCE_API_KEY: publicApiKey }, + execTimeout(5 * 60_000), + [publicApiKey], + ); + expect(providerSwitch.exitCode, resultText(providerSwitch)).toBe(0); + + progress.phase("verify new-provider inference and confirm Ollama unloaded the old model"); + const switchedInference = await querySandboxForAnswer( + sandbox, + PUBLIC_NVIDIA_SWITCH_MODEL, + "phase-9-sandbox-inference-after-provider-switch", + true, + ); + expect(switchedInference.exitCode, resultText(switchedInference)).toBe(0); + expect(containsAnswer(switchedInference.stdout, "42"), resultText(switchedInference)).toBe( + true, + ); + const activeModelsAfterSwitch = await host.command("ollama", ["ps"], { + artifactName: "phase-9-ollama-ps-after-provider-switch", + env: env(), + timeoutMs: 30_000, + }); + expect(activeModelsAfterSwitch.exitCode, resultText(activeModelsAfterSwitch)).toBe(0); + expect(activeModelsAfterSwitch.stdout).not.toContain(model); + progress.phase("remove GPU double-onboard sandbox"); await host.cleanupSandbox(SANDBOX_NAME, { artifactName: "verify-cleanup-nemoclaw-destroy", @@ -418,6 +473,12 @@ exit "$status"`, await artifacts.target.complete({ id: "gpu-double-onboard", status: "passed", + assertions: { + ollamaModelActiveBeforeProviderSwitch: true, + inferenceSetCompleted: providerSwitch.exitCode === 0, + switchedProviderInferenceReturned42: true, + supersededOllamaModelAbsentAfterSwitch: true, + }, }); }, ); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index f38b80ee8e8..13a869e5761 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -618,10 +618,14 @@ "live": "test/e2e/live/gpu-double-onboard.test.ts", "liveSources": ["test/e2e/fixtures/native-local-chat.ts"], "fast": [ + "src/lib/inference/ollama/model-ownership.test.ts", + "src/lib/onboard/setup-inference.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/gpu-e2e-helpers.test.ts", - "test/helpers/e2e-answer-assertions.test.ts" + "test/helpers/e2e-answer-assertions.test.ts", + "test/onboarding/onboard-inference-reconciliation.test.ts", + "test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts" ] }, { diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index d572b279d53..72bf3b44b51 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -549,6 +549,12 @@ export function createDirectSetupInferenceHarnessFactory( // curl a live Ollama daemon. getSandbox: () => legacySandbox, listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), + listOllamaModelOwnershipPeers: () => [], + discoverActiveOllamaSandboxNames: (peers) => ({ + ok: true, + activeSandboxNames: new Set(peers.map((peer) => peer.name)), + gatewayChecks: [], + }), unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => operation(), ...options.overrides, diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 5d4459cb1c3..945c0074106 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -811,17 +811,21 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }), ), managedRuntimeTarget("gpu-double-onboard", { - displayName: "Onboarding: preserves Ollama authentication after GPU re-onboarding", + displayName: "Onboarding: preserves Ollama auth after GPU re-onboarding and provider switch", agentRuntime: "openclaw", - environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama", - profile: "standard", + environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama and NVIDIA API inference", + profile: "nvidia-api", runner: "linux-amd64-gpu-rtxpro6000-latest-1", podmanHostPackages: NATIVE_PODMAN_HOST_PACKAGES, timeoutMinutes: 100, installMode: "authenticated", restoreCli: true, exposeCliBin: true, - owningPaths: ["test/e2e/fixtures/native-local-chat.ts"], + owningPaths: [ + "src/lib/inference/ollama/model-ownership.ts", + "src/lib/onboard/setup-inference.ts", + "test/e2e/fixtures/native-local-chat.ts", + ], environment: { ...nonInteractive, NEMOCLAW_MODEL: "qwen3.5:9b", From bb7f71b57b9cd91f3699d50fb86ec773f90a6e23 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Mon, 26 Oct 2026 12:57:55 -0700 Subject: [PATCH 21/44] fix(inference): satisfy cleanup PR guardrails Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/destroy-flow.test.ts | 11 ----- src/lib/actions/sandbox/destroy.test.ts | 34 +++++++++++++++ src/lib/onboard.ts | 2 - src/lib/onboard/setup-inference.test.ts | 1 - .../tunnel/services-ollama-cleanup.test.ts | 43 +++++++++++++++++++ src/lib/tunnel/services.test.ts | 29 ------------- test/e2e/live/gpu-double-onboard.test.ts | 18 +++----- ...standard-profile-workflow-boundary.test.ts | 34 ++++++++++++++- test/e2e/support/workflow-plan.test.ts | 24 ----------- 9 files changed, 115 insertions(+), 81 deletions(-) create mode 100644 src/lib/tunnel/services-ollama-cleanup.test.ts diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index 36714b0e7d3..3884218504d 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -1364,17 +1364,6 @@ describe("destroySandbox flow", () => { expect(exitSpy).not.toHaveBeenCalled(); }); - it("preserves host resources when --force cannot confirm sandbox deletion", async () => { - const harness = createDestroyHarness({ deleteStatus: 1, deleteOutput: "connection refused" }); - await expect(harness.destroySandbox("alpha", { force: true })).resolves.toBeUndefined(); - expect(harness.unloadOllamaModelsSpy).not.toHaveBeenCalled(); - expect(harness.stopAllSpy).not.toHaveBeenCalled(); - expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith( - expect.arrayContaining(["provider", "delete"]), - expect.anything(), - ); - }); - it("fails closed and restores MCP state when --force cannot confirm sandbox deletion", async () => { const harness = createDestroyHarness({ deleteStatus: 1, diff --git a/src/lib/actions/sandbox/destroy.test.ts b/src/lib/actions/sandbox/destroy.test.ts index 280414c4f43..84872853249 100644 --- a/src/lib/actions/sandbox/destroy.test.ts +++ b/src/lib/actions/sandbox/destroy.test.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -8,6 +10,10 @@ import * as openshellRuntime from "../../adapters/openshell/runtime"; import type { SandboxEntry } from "../../state/registry"; import { SANDBOX_PROVIDER_SUFFIXES } from "../../onboard/sandbox-provider-cleanup"; import { assertUnambiguousDestroyContainerIdentity, cleanupSandboxServices } from "./destroy"; +import { + createDestroyHarness, + resetDestroyModuleCache, +} from "../../../../test/helpers/destroy-flow-test-harness"; afterEach(() => vi.restoreAllMocks()); @@ -608,3 +614,31 @@ describe("assertUnambiguousDestroyContainerIdentity (#8999)", () => { expect(classify).toHaveBeenCalledWith("destroytest"); }); }); + +describe("forced destroy host cleanup", () => { + it( + "preserves host resources when --force cannot confirm sandbox deletion", + { timeout: 30_000 }, + async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-destroy-force-home-")); + vi.stubEnv("HOME", home); + try { + const harness = createDestroyHarness({ + deleteStatus: 1, + deleteOutput: "connection refused", + }); + await expect(harness.destroySandbox("alpha", { force: true })).resolves.toBeUndefined(); + expect(harness.unloadOllamaModelsSpy).not.toHaveBeenCalled(); + expect(harness.stopAllSpy).not.toHaveBeenCalled(); + expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["provider", "delete"]), + expect.anything(), + ); + } finally { + vi.unstubAllEnvs(); + resetDestroyModuleCache(); + fs.rmSync(home, { force: true, recursive: true }); + } + }, + ); +}); diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 26c7154c7b8..e7b1da8b0df 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2326,7 +2326,6 @@ const getSetupInferenceDeps = (): SetupInferenceDeps => ({ error: (message: string) => console.error(message), exitProcess: (code: number): never => process.exit(code), }); - export type SetupInferenceDeps = import("./onboard/setup-inference").SetupInferenceDeps; export type SetupInference = import("./onboard/setup-inference").SetupInference; function createSetupInference(overrides: Partial = {}): SetupInference { @@ -2370,7 +2369,6 @@ const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxC promptOrDefault, }), }); - const stageSandboxCredentialProviders = ( input: import("./onboard/credential-provider-registration").StageSandboxCredentialProvidersInput, ) => diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 916c2ff005c..8ff343125ec 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -457,7 +457,6 @@ describe("releaseSupersededOllamaModel", () => { expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - }); }); diff --git a/src/lib/tunnel/services-ollama-cleanup.test.ts b/src/lib/tunnel/services-ollama-cleanup.test.ts new file mode 100644 index 00000000000..e58259c8446 --- /dev/null +++ b/src/lib/tunnel/services-ollama-cleanup.test.ts @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { expect, it, vi } from "vitest"; + +import { stopAll } from "./services"; + +it("runs injected Ollama cleanup before reporting services stopped", () => { + const pidDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-stop-")); + const cleanup = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + const ollamaCleanupOwner = { + name: "test-box", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-test-box", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + }; + const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + stopAll({ + pidDir, + sandboxName: "test-box", + ollamaCleanupOwner, + unloadOllamaModels: cleanup, + clearPendingOllamaModelCleanup, + unmanagedCloudflaredPids: () => [], + }); + const stoppedCallIndex = logSpy.mock.calls.findIndex(([message]) => + String(message).includes("All services stopped"), + ); + const stoppedCallOrder = logSpy.mock.invocationCallOrder[stoppedCallIndex]; + expect(cleanup).toHaveBeenCalledOnce(); + expect(clearPendingOllamaModelCleanup).toHaveBeenCalledWith(ollamaCleanupOwner); + expect(cleanup.mock.invocationCallOrder[0]).toBeLessThan(stoppedCallOrder ?? 0); + } finally { + logSpy.mockRestore(); + fs.rmSync(pidDir, { recursive: true, force: true }); + } +}); diff --git a/src/lib/tunnel/services.test.ts b/src/lib/tunnel/services.test.ts index a3418cacc44..ad936e4431c 100644 --- a/src/lib/tunnel/services.test.ts +++ b/src/lib/tunnel/services.test.ts @@ -1283,35 +1283,6 @@ describe("stopAll", () => { expect(output).toContain("All services stopped"); logSpy.mockRestore(); }); - it("runs injected Ollama cleanup before reporting services stopped", () => { - const cleanup = vi.fn(); - const clearPendingOllamaModelCleanup = vi.fn(); - const ollamaCleanupOwner = { - name: "test-box", - gatewayName: "nemoclaw-32677", - gatewayPort: 32677, - lifecycleGeneration: "generation-test-box", - lifecycleLiveIdentityFingerprint: "a".repeat(64), - }; - const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ - pidDir, - sandboxName: "test-box", - ollamaCleanupOwner, - unloadOllamaModels: cleanup, - clearPendingOllamaModelCleanup, - unmanagedCloudflaredPids: () => [], - }); - const stoppedCallIndex = logSpy.mock.calls.findIndex(([message]) => - String(message).includes("All services stopped"), - ); - const stoppedCallOrder = logSpy.mock.invocationCallOrder[stoppedCallIndex]; - logSpy.mockRestore(); - expect(cleanup).toHaveBeenCalledOnce(); - expect(clearPendingOllamaModelCleanup).toHaveBeenCalledWith(ollamaCleanupOwner); - expect(cleanup.mock.invocationCallOrder[0]).toBeLessThan(stoppedCallOrder ?? 0); - }); - it("skips Ollama cleanup when the scoped caller proves no model ownership", () => { const cleanup = vi.fn(); const clearPendingOllamaModelCleanup = vi.fn(); diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 08c7b53b072..a145a4a513b 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -156,19 +156,11 @@ async function querySandboxForAnswer( const command = sharedRoute ? `curl -fsS --max-time 120 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(chatRequest(model))}` : nativeLocalChatCommand(endpoint, chatRequest(model), "-fsS"); - return await sandbox.exec( - SANDBOX_NAME, - [ - "sh", - "-lc", - `${command} | ${parseReplyCommand()}`, - ], - { - artifactName, - env: env(), - timeoutMs: 150_000, - }, - ); + return await sandbox.exec(SANDBOX_NAME, ["sh", "-lc", `${command} | ${parseReplyCommand()}`], { + artifactName, + env: env(), + timeoutMs: 150_000, + }); } async function expectSandboxInference42( diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index 1081848be07..0b7e4375a0b 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -16,7 +16,11 @@ import { FULL_E2E_TEST_TIMEOUT_MINUTES, } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; -import { catalogueTarget } from "../../../tools/e2e/target-catalogue.mts"; +import { + catalogueTarget, + catalogueTargetsForChangedFiles, +} from "../../../tools/e2e/target-catalogue.mts"; +import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/workflow-plan.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; const REPO_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -31,6 +35,34 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); + it( + "routes the GPU Ollama provider-switch target through the guarded NVIDIA API profile", + { timeout: 30_000 }, + () => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({ targets: targetId }); + + expect(catalogueTarget(targetId).profile).toBe("nvidia-api"); + expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toEqual([targetId]); + expect(plan.catalogueMatrices.standard).toEqual([]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); + }, + ); + + it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( + "selects the GPU provider-switch target for a source-only %s change", + (changedFile) => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); + + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + targetId, + ); + expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toContain(targetId); + expect(selectedWorkflowJobs(plan)).toContain("catalogue-nvidia-api"); + }, + ); + it("reserves the standard full-E2E setup, test, and artifact envelope", () => { // The original 70-minute path now includes native configuration and plugin lifecycle work. expect(FULL_E2E_TEST_TIMEOUT_MINUTES).toBeGreaterThanOrEqual(100); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 74b8287c3db..1099760fede 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -247,30 +247,6 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-inference"]); }); - it("routes the GPU Ollama provider-switch target through the guarded NVIDIA API profile", () => { - const targetId = "gpu-double-onboard"; - const plan = buildE2eWorkflowPlan({ targets: targetId }); - - expect(catalogueTarget(targetId).profile).toBe("nvidia-api"); - expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toEqual([targetId]); - expect(plan.catalogueMatrices.standard).toEqual([]); - expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); - }); - - it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( - "selects the GPU provider-switch target for a source-only %s change", - (changedFile) => { - const targetId = "gpu-double-onboard"; - const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); - - expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( - targetId, - ); - expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toContain(targetId); - expect(selectedWorkflowJobs(plan)).toContain("catalogue-nvidia-api"); - }, - ); - it("routes Pi lifecycle qualification through the AMD64 NVIDIA API key profile (#7926)", () => { const targetId = "pi-agent-qualification-amd64"; const plan = buildE2eWorkflowPlan({ targets: targetId }); From 6648e4cc1118e5a821c4df671520d560e06aeba7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 02:44:25 -0700 Subject: [PATCH 22/44] fix(ollama): reject gateway override during ownership probe Guard both ambient and supplied endpoint overrides before listing sibling phases, so cleanup cannot trust a redirected gateway inventory. Signed-off-by: Rebecca Sliter --- src/lib/adapters/openshell/runtime.test.ts | 43 ++++++++++++++++++++++ src/lib/adapters/openshell/runtime.ts | 4 ++ 2 files changed, 47 insertions(+) diff --git a/src/lib/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts index 675f8fd06b7..d8ef1279ef5 100644 --- a/src/lib/adapters/openshell/runtime.test.ts +++ b/src/lib/adapters/openshell/runtime.test.ts @@ -18,6 +18,7 @@ import { import { captureResolvedOpenshell, captureResolvedOpenshellAsync, + captureSandboxPhasesForGateway, getStatusProbeTimeoutMs, runOpenshell, } from "./runtime"; @@ -133,6 +134,48 @@ describe("captureResolvedOpenshell", () => { }); }); +describe("captureSandboxPhasesForGateway", () => { + it("rejects an endpoint override before probing another gateway", () => { + const marker = path.join(os.tmpdir(), `nemoclaw-openshell-probe-${process.pid}.marker`); + const openshell = nodeExecutable( + "openshell", + `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "ran");`, + ); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", openshell); + try { + expect(() => + captureSandboxPhasesForGateway("recorded-gateway", { + ...process.env, + OPENSHELL_GATEWAY_ENDPOINT: "https://wrong-gateway.invalid", + }), + ).toThrow(/OPENSHELL_GATEWAY_ENDPOINT is set/); + expect(fs.existsSync(marker)).toBe(false); + } finally { + fs.rmSync(marker, { force: true }); + } + }); + + it("rejects an ambient endpoint override omitted from the supplied environment", () => { + const marker = path.join(os.tmpdir(), `nemoclaw-openshell-ambient-${process.pid}.marker`); + const openshell = nodeExecutable( + "openshell", + `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "ran");`, + ); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", openshell); + const environment = { ...process.env }; + delete environment.OPENSHELL_GATEWAY_ENDPOINT; + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://wrong-gateway.invalid"); + try { + expect(() => captureSandboxPhasesForGateway("recorded-gateway", environment)).toThrow( + /OPENSHELL_GATEWAY_ENDPOINT is set/, + ); + expect(fs.existsSync(marker)).toBe(false); + } finally { + fs.rmSync(marker, { force: true }); + } + }); +}); + describe("captureResolvedOpenshellAsync", () => { it("bounds captured output from the selected executable", async () => { const result = await captureResolvedOpenshellAsync([], { diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index 8b817001c5b..07ec56307bc 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -15,6 +15,7 @@ import { runOpenshellCommand, } from "./command-execution"; import { cliOpenShellInstalledVersionObserver } from "./installed-version-cli"; +import { assertNoOpenShellGatewayEndpointOverride } from "./gateway-scope"; import { buildOpenShellSubprocessEnv, resolveOpenshellBinaryOrNull } from "./resolve-shared"; type CommandArgs = string[]; @@ -120,6 +121,9 @@ export function captureSandboxPhasesForGateway( gatewayName: string, environment: NodeJS.ProcessEnv, ): { readonly output: string; readonly status: number | null } { + // captureOpenshell also inherits ambient variables when it builds the child environment. + assertNoOpenShellGatewayEndpointOverride(); + assertNoOpenShellGatewayEndpointOverride(environment); const result = captureOpenshell(["sandbox", "list", "-g", gatewayName], { env: environment, ignoreError: true, From d491bc7e7ea8005ad11ff7e8e860959a2dfe0076 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 02:44:56 -0700 Subject: [PATCH 23/44] chore(e2e): align conflict files with target branch Temporarily align the two conflicting files with canonical main for a guarded Update branch. The reviewed combined tests and assertion budget will be restored after the merge. Signed-off-by: Rebecca Sliter --- ci/e2e-assertion-budget.json | 26 ++++---- ...standard-profile-workflow-boundary.test.ts | 61 ++++++++----------- 2 files changed, 38 insertions(+), 49 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 8e7dca0b3c3..c1e1995e29a 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,28 +15,28 @@ "testFileCount": 77, "liveFileCount": 187, "direct": { - "expectCalls": 1269, - "matcherAssertions": 1249, + "expectCalls": 1271, + "matcherAssertions": 1251, "nodeAssertions": 108, "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2013, + "assertionPoints": 2015, "generatedProbeBlocks": 84, "generatedProbeConditions": 206 }, "unique": { - "expectCalls": 1697, - "matcherAssertions": 1672, + "expectCalls": 1701, + "matcherAssertions": 1676, "nodeAssertions": 131, "namedAssertionHelpers": 668, "failCalls": 1, - "throwGuards": 531, + "throwGuards": 532, "objectFieldAssertions": 266, - "assertionPoints": 3269, - "generatedProbeBlocks": 208, - "generatedProbeConditions": 713 + "assertionPoints": 3274, + "generatedProbeBlocks": 210, + "generatedProbeConditions": 715 }, "fileMetricOrder": [ "directExpectCalls", @@ -63,12 +63,12 @@ "test/e2e/live/double-onboard.test.ts": [46,51,46,51,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], - "test/e2e/live/gpu-double-onboard.test.ts": [20,23,20,23,0], + "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [9,19,16,58,12], - "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], + "test/e2e/live/hermes-e2e.test.ts": [82,93,114,129,5], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [40,48,58,87,1], + "test/e2e/live/hermes-inference-switch.test.ts": [38,46,56,86,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], @@ -108,7 +108,7 @@ "test/e2e/live/portable-cpu-delegation-proof.test.ts": [0,22,0,22,0], "test/e2e/live/portable-profile-rootless-linux.test.ts": [0,76,0,82,2], "test/e2e/live/rebuild-hermes.test.ts": [2,8,9,47,6], - "test/e2e/live/rebuild-openclaw.test.ts": [2,7,2,26,1], + "test/e2e/live/rebuild-openclaw.test.ts": [5,10,5,29,1], "test/e2e/live/registry-targets.test.ts": [2,4,5,24,0], "test/e2e/live/sandbox-operations.test.ts": [2,11,9,50,6], "test/e2e/live/sandbox-rlimits-connect.test.ts": [1,1,1,1,0], diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index 0b7e4375a0b..607cb2d8822 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -16,11 +16,7 @@ import { FULL_E2E_TEST_TIMEOUT_MINUTES, } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; -import { - catalogueTarget, - catalogueTargetsForChangedFiles, -} from "../../../tools/e2e/target-catalogue.mts"; -import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/workflow-plan.mts"; +import { catalogueTarget } from "../../../tools/e2e/target-catalogue.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; const REPO_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -30,38 +26,31 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); - it("routes the GPU provider-switch target through guarded NVIDIA API credentials", () => { - expect(catalogueTarget("gpu-double-onboard").profile).toBe("nvidia-api"); - expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); - }); - - it( - "routes the GPU Ollama provider-switch target through the guarded NVIDIA API profile", - { timeout: 30_000 }, - () => { - const targetId = "gpu-double-onboard"; - const plan = buildE2eWorkflowPlan({ targets: targetId }); - - expect(catalogueTarget(targetId).profile).toBe("nvidia-api"); - expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toEqual([targetId]); - expect(plan.catalogueMatrices.standard).toEqual([]); - expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); - }, - ); - - it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( - "selects the GPU provider-switch target for a source-only %s change", - (changedFile) => { - const targetId = "gpu-double-onboard"; - const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); - - expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( - targetId, + it.each([ + { field: "uses", value: "actions/setup-python@v7" }, + { field: "if", value: "true" }, + { field: "with", value: { "python-version": "3.14" } }, + { field: "env", value: { UNREVIEWED_INPUT: "present" } }, + { field: "run", value: "python3 --version" }, + ])("rejects unreviewed Model Router Python $field", ({ field, value }) => { + const profile = YAML.parse( + fs.readFileSync(path.join(REPO_ROOT, ".github/workflows/e2e-standard-profile.yaml"), "utf8"), + ) as { jobs: { run: { steps: Array> } } }; + const python = profile.jobs.run.steps.find( + (step) => step.name === "Set up supported Model Router Python", + )!; + python[field] = value; + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-router-python-")); + const profilePath = path.join(directory, "profile.yaml"); + try { + fs.writeFileSync(profilePath, YAML.stringify(profile)); + expect(validateStandardProfileWorkflowBoundary(readWorkflow(), profilePath)).toContain( + "standard E2E profile must provision reviewed Python only for Model Router", ); - expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toContain(targetId); - expect(selectedWorkflowJobs(plan)).toContain("catalogue-nvidia-api"); - }, - ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); it("reserves the standard full-E2E setup, test, and artifact envelope", () => { // The original 70-minute path now includes native configuration and plugin lifecycle work. From 770eaaf0ddf5be5b7a83e470c9b7fe33b6d75f02 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 02:46:04 -0700 Subject: [PATCH 24/44] test(e2e): retain GPU and Python workflow boundary checks Preserve the provider-switch credential routing checks alongside the target branch Python boundary regression. Reconcile the E2E assertion budget with the existing one-assertion reduction. Signed-off-by: Rebecca Sliter --- ci/e2e-assertion-budget.json | 14 +++---- ...standard-profile-workflow-boundary.test.ts | 39 ++++++++++++++++++- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index c1e1995e29a..0e8df7716eb 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 187, "direct": { - "expectCalls": 1271, - "matcherAssertions": 1251, + "expectCalls": 1270, + "matcherAssertions": 1250, "nodeAssertions": 108, "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2015, + "assertionPoints": 2014, "generatedProbeBlocks": 84, "generatedProbeConditions": 206 }, "unique": { - "expectCalls": 1701, - "matcherAssertions": 1676, + "expectCalls": 1700, + "matcherAssertions": 1675, "nodeAssertions": 131, "namedAssertionHelpers": 668, "failCalls": 1, "throwGuards": 532, "objectFieldAssertions": 266, - "assertionPoints": 3274, + "assertionPoints": 3273, "generatedProbeBlocks": 210, "generatedProbeConditions": 715 }, @@ -63,7 +63,7 @@ "test/e2e/live/double-onboard.test.ts": [46,51,46,51,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], - "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], + "test/e2e/live/gpu-double-onboard.test.ts": [20,23,20,23,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [9,19,16,58,12], "test/e2e/live/hermes-e2e.test.ts": [82,93,114,129,5], diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index 607cb2d8822..f802d44ebfb 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -16,7 +16,11 @@ import { FULL_E2E_TEST_TIMEOUT_MINUTES, } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; -import { catalogueTarget } from "../../../tools/e2e/target-catalogue.mts"; +import { + catalogueTarget, + catalogueTargetsForChangedFiles, +} from "../../../tools/e2e/target-catalogue.mts"; +import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/workflow-plan.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; const REPO_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -26,6 +30,39 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); + it("routes the GPU provider-switch target through guarded NVIDIA API credentials", () => { + expect(catalogueTarget("gpu-double-onboard").profile).toBe("nvidia-api"); + expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); + }); + + it( + "routes the GPU Ollama provider-switch target through the guarded NVIDIA API profile", + { timeout: 30_000 }, + () => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({ targets: targetId }); + + expect(catalogueTarget(targetId).profile).toBe("nvidia-api"); + expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toEqual([targetId]); + expect(plan.catalogueMatrices.standard).toEqual([]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); + }, + ); + + it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( + "selects the GPU provider-switch target for a source-only %s change", + (changedFile) => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); + + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + targetId, + ); + expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toContain(targetId); + expect(selectedWorkflowJobs(plan)).toContain("catalogue-nvidia-api"); + }, + ); + it.each([ { field: "uses", value: "actions/setup-python@v7" }, { field: "if", value: "true" }, From ab7f863796163ece05ff085b510004be6c1b31d5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 03:22:16 -0700 Subject: [PATCH 25/44] fix: limit OpenShell phase probe environment Signed-off-by: Rebecca Sliter --- src/lib/adapters/openshell/runtime.test.ts | 42 ++++++++++++++++++++++ src/lib/adapters/openshell/runtime.ts | 9 +++-- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/lib/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts index d8ef1279ef5..e1e47f6a3b6 100644 --- a/src/lib/adapters/openshell/runtime.test.ts +++ b/src/lib/adapters/openshell/runtime.test.ts @@ -174,6 +174,48 @@ describe("captureSandboxPhasesForGateway", () => { fs.rmSync(marker, { force: true }); } }); + + it("passes gateway config but excludes supplied and ambient credentials from the child", async () => { + const openshell = nodeExecutable( + "openshell", + `process.stdout.write(JSON.stringify({ + args: process.argv.slice(2), + home: process.env.HOME, + config: process.env.XDG_CONFIG_HOME, + gateway: process.env.OPENSHELL_GATEWAY, + workspace: process.env.OPENSHELL_WORKSPACE, + tls: process.env.OPENSHELL_LOCAL_TLS_DIR, + suppliedSecret: process.env.NVIDIA_API_KEY ?? null, + ambientSecret: process.env.AWS_SECRET_ACCESS_KEY ?? null, + }));`, + ); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", openshell); + vi.stubEnv("AWS_SECRET_ACCESS_KEY", "ambient-canary"); + vi.resetModules(); + const { captureSandboxPhasesForGateway: captureFresh } = await import("./runtime"); + + const result = captureFresh("recorded-gateway", { + HOME: "/recorded/home", + PATH: process.env.PATH, + XDG_CONFIG_HOME: "/recorded/config", + OPENSHELL_GATEWAY: "recorded-gateway", + OPENSHELL_WORKSPACE: "recorded-workspace", + OPENSHELL_LOCAL_TLS_DIR: "/recorded/tls", + NVIDIA_API_KEY: "supplied-canary", + }); + + expect(result.status).toBe(0); + expect(JSON.parse(result.output)).toEqual({ + args: ["sandbox", "list", "-g", "recorded-gateway"], + home: "/recorded/home", + config: "/recorded/config", + gateway: "recorded-gateway", + workspace: "recorded-workspace", + tls: "/recorded/tls", + suppliedSecret: null, + ambientSecret: null, + }); + }); }); describe("captureResolvedOpenshellAsync", () => { diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index 07ec56307bc..92542cfac79 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -16,7 +16,11 @@ import { } from "./command-execution"; import { cliOpenShellInstalledVersionObserver } from "./installed-version-cli"; import { assertNoOpenShellGatewayEndpointOverride } from "./gateway-scope"; -import { buildOpenShellSubprocessEnv, resolveOpenshellBinaryOrNull } from "./resolve-shared"; +import { + buildOpenShellDiagnosticEnvironment, + buildOpenShellSubprocessEnv, + resolveOpenshellBinaryOrNull, +} from "./resolve-shared"; type CommandArgs = string[]; @@ -125,7 +129,8 @@ export function captureSandboxPhasesForGateway( assertNoOpenShellGatewayEndpointOverride(); assertNoOpenShellGatewayEndpointOverride(environment); const result = captureOpenshell(["sandbox", "list", "-g", gatewayName], { - env: environment, + env: buildOpenShellDiagnosticEnvironment(environment), + replaceEnv: true, ignoreError: true, includeStderr: true, maxBuffer: 1024 * 1024, From cfd8e060685d2fc8d12a761f3d549de1c564a85b Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 04:27:39 -0700 Subject: [PATCH 26/44] test: keep GPU provider-switch validation credential-free Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-budget.json | 14 ++--- test/e2e/live/gpu-double-onboard.test.ts | 62 +++++++++++++++---- test/e2e/mock-parity.json | 2 + ...standard-profile-workflow-boundary.test.ts | 19 +++--- test/e2e/support/workflow-plan.test.ts | 12 ++-- tools/e2e/target-catalogue.mts | 4 +- 6 files changed, 71 insertions(+), 42 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 0e8df7716eb..c1e1995e29a 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 187, "direct": { - "expectCalls": 1270, - "matcherAssertions": 1250, + "expectCalls": 1271, + "matcherAssertions": 1251, "nodeAssertions": 108, "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2014, + "assertionPoints": 2015, "generatedProbeBlocks": 84, "generatedProbeConditions": 206 }, "unique": { - "expectCalls": 1700, - "matcherAssertions": 1675, + "expectCalls": 1701, + "matcherAssertions": 1676, "nodeAssertions": 131, "namedAssertionHelpers": 668, "failCalls": 1, "throwGuards": 532, "objectFieldAssertions": 266, - "assertionPoints": 3273, + "assertionPoints": 3274, "generatedProbeBlocks": 210, "generatedProbeConditions": 715 }, @@ -63,7 +63,7 @@ "test/e2e/live/double-onboard.test.ts": [46,51,46,51,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], - "test/e2e/live/gpu-double-onboard.test.ts": [20,23,20,23,0], + "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [9,19,16,58,12], "test/e2e/live/hermes-e2e.test.ts": [82,93,114,129,5], diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index a145a4a513b..739fae4c0d5 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -17,18 +17,16 @@ import { resultText, shellQuote } from "../fixtures/clients/command.ts"; import { type HostCliClient } from "../fixtures/clients/host.ts"; import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; +import { startFakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compatible.ts"; import { nativeLocalChatCommand } from "../fixtures/native-local-chat.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; -import { - PUBLIC_NVIDIA_SWITCH_MODEL, - PUBLIC_NVIDIA_SWITCH_PROVIDER, - requirePublicNvidiaSwitchKey, -} from "./public-nvidia-switch-provider.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-gpu-double"; const PROXY_PORT = process.env.NEMOCLAW_OLLAMA_PROXY_PORT ?? "11435"; const GPU_E2E_MODEL = process.env.NEMOCLAW_MODEL ?? "qwen3.5:9b"; +const SWITCH_MODEL = "nemoclaw-e2e-after-ollama"; +const SWITCH_API_KEY = "sk-compatible-TEST-NOT-A-REAL-VALUE"; const TOKEN_FILE = path.join(os.homedir(), ".nemoclaw", "ollama-proxy-token"); const LIVE_TIMEOUT_MS = testTimeout(90 * 60_000); @@ -199,7 +197,6 @@ test( progress, runtimeProvider, sandbox, - secrets, skip, }) => { await artifacts.target.declare({ @@ -214,12 +211,11 @@ test( "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", "the sandbox-owned native provider reaches Ollama after first onboard and re-onboard", "Ollama reports the selected model as active before the provider switch", - "nemoclaw inference set switches the sandbox to the public NVIDIA provider", + "nemoclaw inference set switches the sandbox to a local compatible endpoint", "sandbox inference succeeds through the new provider and host ollama ps no longer reports the superseded model", ], }); - const publicApiKey = requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")); await runtimeProvider.requireAvailable({ artifactName: "phase-0-runtime-info", scenarioLabel: "GPU double-onboard", @@ -414,6 +410,27 @@ exit "$status"`, expect(activeModelsBeforeSwitch.exitCode, resultText(activeModelsBeforeSwitch)).toBe(0); expect(activeModelsBeforeSwitch.stdout).toContain(model); + const fake = await startFakeOpenAiCompatibleServer({ + apiKey: SWITCH_API_KEY, + chatContent: "42", + host: "0.0.0.0", + model: SWITCH_MODEL, + port: 8000, + progress, + publicHost: "localhost", + requireAuth: true, + requireAuthModels: true, + }); + cleanupRegistry.trackDisposable("close switched compatible endpoint", async () => { + try { + await artifacts.writeJson("phase-9-compatible-endpoint-requests.json", fake.requests()); + } finally { + await fake.close(); + } + }); + // Inference set accepts this explicit sandbox-to-host bridge, while a raw + // localhost URL is deliberately rejected at its SSRF boundary. + const switchEndpointUrl = fake.baseUrl.replace("localhost", "host.openshell.internal"); progress.phase("switch inference to a non-Ollama provider"); const providerSwitch = await nemoclaw( host, @@ -421,23 +438,30 @@ exit "$status"`, "inference", "set", "--provider", - PUBLIC_NVIDIA_SWITCH_PROVIDER, + "compatible-endpoint", "--model", - PUBLIC_NVIDIA_SWITCH_MODEL, + SWITCH_MODEL, "--sandbox", SANDBOX_NAME, + "--endpoint-url", + switchEndpointUrl, + "--credential-env", + "COMPATIBLE_API_KEY", + "--inference-api", + "openai-completions", ], "phase-8-inference-set-away-from-ollama", - { NVIDIA_INFERENCE_API_KEY: publicApiKey }, + { COMPATIBLE_API_KEY: SWITCH_API_KEY }, execTimeout(5 * 60_000), - [publicApiKey], + [SWITCH_API_KEY], ); expect(providerSwitch.exitCode, resultText(providerSwitch)).toBe(0); progress.phase("verify new-provider inference and confirm Ollama unloaded the old model"); + const switchedRequestOffset = fake.requests().length; const switchedInference = await querySandboxForAnswer( sandbox, - PUBLIC_NVIDIA_SWITCH_MODEL, + SWITCH_MODEL, "phase-9-sandbox-inference-after-provider-switch", true, ); @@ -445,6 +469,18 @@ exit "$status"`, expect(containsAnswer(switchedInference.stdout, "42"), resultText(switchedInference)).toBe( true, ); + expect( + fake + .requests() + .slice(switchedRequestOffset) + .some( + (request) => + request.auth === "ok" && + request.method === "POST" && + request.path === "/v1/chat/completions" && + request.model === SWITCH_MODEL, + ), + ).toBe(true); const activeModelsAfterSwitch = await host.command("ollama", ["ps"], { artifactName: "phase-9-ollama-ps-after-provider-switch", env: env(), diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 9be4378b7c5..00e75611755 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -624,6 +624,8 @@ "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/gpu-e2e-helpers.test.ts", + "test/e2e/support/standard-profile-workflow-boundary.test.ts", + "test/e2e/support/workflow-plan.test.ts", "test/helpers/e2e-answer-assertions.test.ts", "test/onboarding/onboard-inference-reconciliation.test.ts", "test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts" diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index f802d44ebfb..eaaf0c6e3b6 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -30,22 +30,17 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); - it("routes the GPU provider-switch target through guarded NVIDIA API credentials", () => { - expect(catalogueTarget("gpu-double-onboard").profile).toBe("nvidia-api"); - expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); - }); - it( - "routes the GPU Ollama provider-switch target through the guarded NVIDIA API profile", + "routes the credential-free GPU Ollama provider-switch target through the standard profile", { timeout: 30_000 }, () => { const targetId = "gpu-double-onboard"; const plan = buildE2eWorkflowPlan({ targets: targetId }); - expect(catalogueTarget(targetId).profile).toBe("nvidia-api"); - expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toEqual([targetId]); - expect(plan.catalogueMatrices.standard).toEqual([]); - expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api"]); + expect(catalogueTarget(targetId).profile).toBe("standard"); + expect(plan.catalogueMatrices.standard.map((row) => row.id)).toEqual([targetId]); + expect(plan.catalogueMatrices["nvidia-api"]).toEqual([]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard"]); }, ); @@ -58,8 +53,8 @@ describe("standard E2E execution profile", () => { expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( targetId, ); - expect(plan.catalogueMatrices["nvidia-api"].map((row) => row.id)).toContain(targetId); - expect(selectedWorkflowJobs(plan)).toContain("catalogue-nvidia-api"); + expect(plan.catalogueMatrices.standard.map((row) => row.id)).toContain(targetId); + expect(selectedWorkflowJobs(plan)).toContain("catalogue-standard"); }, ); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 1099760fede..6cee6cd5b35 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -672,23 +672,19 @@ describe("E2E workflow plan", () => { }); }); - it("routes GPU targets through their profile-specific workflow matrices", () => { + it("routes credential-free GPU targets through the standard workflow matrix", () => { const targetIds = ["gpu-double-onboard", "gpu-e2e", "llama-cpp-generic-gpu"]; const expectedRunner = "linux-amd64-gpu-rtxpro6000-latest-1"; const plan = buildE2eWorkflowPlan({ jobs: targetIds.join(",") }); expect(plan.catalogueMatrices.standard).toEqual( - ["gpu-e2e", "llama-cpp-generic-gpu"].map((id) => - expect.objectContaining({ id, runner: expectedRunner }), - ), + targetIds.map((id) => expect.objectContaining({ id, runner: expectedRunner })), ); - expect(plan.catalogueMatrices["nvidia-api"]).toEqual([ - expect.objectContaining({ id: "gpu-double-onboard", runner: expectedRunner }), - ]); + expect(plan.catalogueMatrices["nvidia-api"]).toEqual([]); expect(plan.catalogueMatrices.standard.find((row) => row.id === "gpu-e2e")).not.toHaveProperty( "selector", ); - expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-nvidia-api", "catalogue-standard"]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard"]); }); it("selects the complete GPU reply target when its Hermes helper changes", () => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 945c0074106..4c2bf4391a8 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -813,8 +813,8 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ managedRuntimeTarget("gpu-double-onboard", { displayName: "Onboarding: preserves Ollama auth after GPU re-onboarding and provider switch", agentRuntime: "openclaw", - environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama and NVIDIA API inference", - profile: "nvidia-api", + environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama and compatible endpoint", + profile: "standard", runner: "linux-amd64-gpu-rtxpro6000-latest-1", podmanHostPackages: NATIVE_PODMAN_HOST_PACKAGES, timeoutMinutes: 100, From 76d68458c2d17989f2d016eea654e84abc992178 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 05:04:56 -0700 Subject: [PATCH 27/44] fix: retain Ollama token mode check and simplify ownership imports Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/destroy.ts | 6 ++++-- src/lib/inference/ollama/proxy.ts | 4 ---- test/e2e/live/gpu-double-onboard.test.ts | 7 +------ 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 455ee36e7f4..d5be95ad8b1 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -29,13 +29,15 @@ import { } from "../../inference/local-model-profile/cleanup"; import { discoverOllamaModelOwnership, + matchingOllamaModelPeers, + type OllamaModelCleanupOwner, +} from "../../inference/ollama/model-ownership"; +import { isLocalOllamaRouteOwner, loadPersistedOllamaHost, - matchingOllamaModelPeers, type OllamaUnloadResult, withOllamaModelOwnershipTransaction, } from "../../inference/ollama/proxy"; -import type { OllamaModelCleanupOwner } from "../../inference/ollama/model-ownership"; import { CURRENT_RUNTIME_PROVIDER_BUNDLES, normalizeRuntimeProviderIdentity, diff --git a/src/lib/inference/ollama/proxy.ts b/src/lib/inference/ollama/proxy.ts index 2988c4bf07c..0b74b389846 100644 --- a/src/lib/inference/ollama/proxy.ts +++ b/src/lib/inference/ollama/proxy.ts @@ -32,10 +32,8 @@ const { const { ollamaModelRefsMatch }: typeof import("./model-discovery") = require("./model-discovery"); const { clearPendingOllamaModelCleanup, - discoverOllamaModelOwnership, isLocalOllamaRouteOwner, loadPendingOllamaModelCleanup, - matchingOllamaModelPeers, }: typeof import("./model-ownership") = require("./model-ownership"); const { getBootstrapOllamaModelOptions, @@ -1839,7 +1837,6 @@ export { buildOllamaAuthProxySpawnEnv, checkOllamaModelToolSupport, clearPendingOllamaModelCleanup, - discoverOllamaModelOwnership, ensureOllamaAuthProxy, getOllamaProxyToken, getOllamaPullTimeoutMs, @@ -1849,7 +1846,6 @@ export { killStaleProxyIfUnused, loadPendingOllamaModelCleanup, loadPersistedOllamaHost, - matchingOllamaModelPeers, noAuthProxy, ollamaModelRefsMatch, persistAndProbeOllamaProxy, diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 739fae4c0d5..488c7733231 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -367,14 +367,9 @@ exit "$status"`, expect(reonboard.exitCode, resultText(reonboard)).toBe(0); const tokenAfterSecond = fs.readFileSync(TOKEN_FILE, "utf8").trim(); expect(tokenAfterSecond).toBe(tokenAfterFirst); + expect(fs.statSync(TOKEN_FILE).mode & 0o777).toBe(0o600); progress.phase("validate persisted proxy auth and inference"); - const liveStatus = await httpStatus( - host, - `http://127.0.0.1:${PROXY_PORT}/api/tags`, - "phase-5-proxy-live-status", - ); - expect(liveStatus.stdout.trim()).toMatch(/^[1-9][0-9]{2}$/); const authStatus = await httpStatus( host, `http://127.0.0.1:${PROXY_PORT}/v1/models`, From ccb9dbb725a292c65d99d1b6a860c4db3c2a1454 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 05:55:02 -0700 Subject: [PATCH 28/44] fix: preserve Ollama cleanup ownership on provider switch Signed-off-by: Rebecca Sliter --- src/lib/actions/sandbox/destroy.ts | 6 +- src/lib/inference/ollama/proxy.ts | 4 + src/lib/onboard/setup-inference.test.ts | 62 +++++++++++++++ src/lib/onboard/setup-inference.ts | 6 ++ src/lib/state/registry/cross-port.test.ts | 30 +++++++ src/lib/state/registry/cross-port.ts | 23 +++++- ...standard-profile-workflow-boundary.test.ts | 78 +++++++++++-------- 7 files changed, 169 insertions(+), 40 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index d5be95ad8b1..455ee36e7f4 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -29,15 +29,13 @@ import { } from "../../inference/local-model-profile/cleanup"; import { discoverOllamaModelOwnership, - matchingOllamaModelPeers, - type OllamaModelCleanupOwner, -} from "../../inference/ollama/model-ownership"; -import { isLocalOllamaRouteOwner, loadPersistedOllamaHost, + matchingOllamaModelPeers, type OllamaUnloadResult, withOllamaModelOwnershipTransaction, } from "../../inference/ollama/proxy"; +import type { OllamaModelCleanupOwner } from "../../inference/ollama/model-ownership"; import { CURRENT_RUNTIME_PROVIDER_BUNDLES, normalizeRuntimeProviderIdentity, diff --git a/src/lib/inference/ollama/proxy.ts b/src/lib/inference/ollama/proxy.ts index 0b74b389846..2988c4bf07c 100644 --- a/src/lib/inference/ollama/proxy.ts +++ b/src/lib/inference/ollama/proxy.ts @@ -32,8 +32,10 @@ const { const { ollamaModelRefsMatch }: typeof import("./model-discovery") = require("./model-discovery"); const { clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, loadPendingOllamaModelCleanup, + matchingOllamaModelPeers, }: typeof import("./model-ownership") = require("./model-ownership"); const { getBootstrapOllamaModelOptions, @@ -1837,6 +1839,7 @@ export { buildOllamaAuthProxySpawnEnv, checkOllamaModelToolSupport, clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, ensureOllamaAuthProxy, getOllamaProxyToken, getOllamaPullTimeoutMs, @@ -1846,6 +1849,7 @@ export { killStaleProxyIfUnused, loadPendingOllamaModelCleanup, loadPersistedOllamaHost, + matchingOllamaModelPeers, noAuthProxy, ollamaModelRefsMatch, persistAndProbeOllamaProxy, diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 8ff343125ec..624cae97cc6 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -224,6 +224,31 @@ describe("releaseSupersededOllamaModel", () => { } }); + it("keeps the model and records retry when a sibling gateway has state but no registry", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-missing-peer-registry-")); + vi.stubEnv("HOME", home); + const siblingRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(siblingRoot, { recursive: true }); + fs.writeFileSync(path.join(siblingRoot, "onboard-session.json"), "{}"); + const harness = createOllamaCleanupHarness({ useProductionPeerSource: true }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("sandboxes.json is missing")); + } finally { + warning.mockRestore(); + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("uses the injected phase capture for cross-gateway discovery", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); vi.stubEnv("HOME", home); @@ -361,6 +386,43 @@ describe("releaseSupersededOllamaModel", () => { } }); + it("records the old model when identity changes after the new route commits", () => { + const harness = createOllamaCleanupHarness(); + const refusal = new Error("sandbox lifecycle changed"); + const attempt = () => + releaseSupersededOllamaModel( + previousLocalOllamaRoute, + "nvidia-prod", + "nvidia/test-model", + "https://integrate.api.nvidia.com/v1", + { ok: true }, + harness.deps, + () => { + throw refusal; + }, + ); + + expect(attempt).toThrow(refusal); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledExactlyOnceWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { + throw new Error("receipt write failed"); + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + expect(attempt).toThrow(refusal); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("Cleanup retry state could not be recorded"), + ); + } finally { + warning.mockRestore(); + } + }); + it("requires manual recovery when ownership failure cannot be recorded for retry", () => { const discovery = vi.fn>( () => ({ ok: false, message: "gateway unavailable" }), diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 91e862e9de5..3aa0f4d9d6e 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -686,6 +686,12 @@ export function releaseSupersededOllamaModel( revalidateSandboxIdentity?.("release the superseded Ollama model"); } catch (error) { authorityRefusal = error; + pendingRecordFailure = persistRetry(); + if (pendingRecordFailure) { + cleanupWarning = + ` Warning: Cleanup retry state could not be recorded for '${previous.name}' after the new inference route became active: ${pendingRecordFailure}. ` + + `No model was unloaded. Manually verify ownership before releasing only ${attemptedModels.join(", ") || "the superseded model"} from the saved local Ollama endpoint.`; + } return; } if (attemptedModels.length > 0 && deps.unloadOllamaModels) { diff --git a/src/lib/state/registry/cross-port.test.ts b/src/lib/state/registry/cross-port.test.ts index fc070f1d0ec..d5dec2c76ee 100644 --- a/src/lib/state/registry/cross-port.test.ts +++ b/src/lib/state/registry/cross-port.test.ts @@ -234,4 +234,34 @@ describe("listSandboxNamesAcrossGatewayRoots", () => { expect(listSandboxNamesInGatewayRoot(8080)).toEqual([]); expect(listInferenceRouteOwnersAcrossGatewayRoots()).toEqual([]); }); + + it("allows an empty new gateway root but rejects a missing registry beside retained gateway state", async () => { + const siblingRoot = path.join(home, ".nemoclaw", "gateways", "8245"); + fs.mkdirSync(siblingRoot, { recursive: true }); + const { listInferenceRouteOwnersAcrossGatewayRoots } = await loadModule(); + + expect(listInferenceRouteOwnersAcrossGatewayRoots()).toEqual([]); + + fs.writeFileSync(path.join(siblingRoot, "onboard-session.json"), "{}"); + expect(() => listInferenceRouteOwnersAcrossGatewayRoots()).toThrow( + "sandboxes.json is missing for a recorded gateway", + ); + }); + + it("rejects a missing default registry when a default gateway config remains", async () => { + const gatewayStateDir = path.join( + home, + ".local", + "state", + "nemoclaw", + "openshell-docker-gateway", + ); + fs.mkdirSync(gatewayStateDir, { recursive: true }); + fs.writeFileSync(path.join(gatewayStateDir, "openshell-gateway.toml"), ""); + const { listInferenceRouteOwnersAcrossGatewayRoots } = await loadModule(); + + expect(() => listInferenceRouteOwnersAcrossGatewayRoots()).toThrow( + "sandboxes.json is missing for a recorded gateway", + ); + }); }); diff --git a/src/lib/state/registry/cross-port.ts b/src/lib/state/registry/cross-port.ts index 886bc881289..83827d97bdd 100644 --- a/src/lib/state/registry/cross-port.ts +++ b/src/lib/state/registry/cross-port.ts @@ -1,10 +1,12 @@ // 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"; import { DEFAULT_GATEWAY_PORT, + hasDefaultGatewayEvidence, listGatewayStateRoots, readGatewayRegistryFile, registryEntryGatewayPort, @@ -44,12 +46,27 @@ function normalizeEntryForRoot( return entry; } -function listSandboxHitsAcrossGatewayRoots(home: string): CrossPortSandboxHit[] { +function listSandboxHitsAcrossGatewayRoots( + home: string, + requireCompleteOwnerInventory = false, +): CrossPortSandboxHit[] { const hits: CrossPortSandboxHit[] = []; for (const state of listGatewayStateRoots(home)) { const registryFile = path.join(state.root, "sandboxes.json"); const registry = readGatewayRegistryFile(home, registryFile); - if (!registry) continue; + if (!registry) { + // An unused root can have no registry. A root with gateway state cannot + // safely be treated as an empty ownership inventory before model unload. + if ( + requireCompleteOwnerInventory && + (state.gatewayPort === DEFAULT_GATEWAY_PORT + ? hasDefaultGatewayEvidence(home) + : fs.readdirSync(state.root).length > 0) + ) { + throw crossPortStateError(`${registryFile} is missing for a recorded gateway`); + } + continue; + } for (const rawEntry of Object.values(registry.sandboxes)) { const entry = normalizeEntryForRoot(rawEntry, state.gatewayPort); @@ -223,7 +240,7 @@ export function listPublishedSandboxesAcrossGatewayRoots( export function listInferenceRouteOwnersAcrossGatewayRoots( home: string = resolveHome(), ): SandboxEntry[] { - return listSandboxHitsAcrossGatewayRoots(home).map(({ entry }) => entry); + return listSandboxHitsAcrossGatewayRoots(home, true).map(({ entry }) => entry); } /** Published sandbox names across every registry root, base root first, then ports ascending. */ diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index eaaf0c6e3b6..9e412aa2dee 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -16,11 +16,7 @@ import { FULL_E2E_TEST_TIMEOUT_MINUTES, } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; -import { - catalogueTarget, - catalogueTargetsForChangedFiles, -} from "../../../tools/e2e/target-catalogue.mts"; -import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/workflow-plan.mts"; +import { catalogueTarget } from "../../../tools/e2e/target-catalogue.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; const REPO_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -30,33 +26,49 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); - it( - "routes the credential-free GPU Ollama provider-switch target through the standard profile", - { timeout: 30_000 }, - () => { - const targetId = "gpu-double-onboard"; - const plan = buildE2eWorkflowPlan({ targets: targetId }); - - expect(catalogueTarget(targetId).profile).toBe("standard"); - expect(plan.catalogueMatrices.standard.map((row) => row.id)).toEqual([targetId]); - expect(plan.catalogueMatrices["nvidia-api"]).toEqual([]); - expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard"]); - }, - ); - - it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( - "selects the GPU provider-switch target for a source-only %s change", - (changedFile) => { - const targetId = "gpu-double-onboard"; - const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); - - expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( - targetId, - ); - expect(plan.catalogueMatrices.standard.map((row) => row.id)).toContain(targetId); - expect(selectedWorkflowJobs(plan)).toContain("catalogue-standard"); - }, - ); + it.each< + [string, (steps: Array<{ name: string; with?: Record; if?: string }>) => void] + >([ + [ + "early install", + (steps) => { + steps.find((step) => step.name === "Prepare E2E workspace")!.with!["install-dependencies"] = + "true"; + }, + ], + [ + "late archive", + (steps) => { + const index = steps.findIndex( + (step) => step.name === "Download reviewed OpenShell SDK archive", + ); + const [archive] = steps.splice(index, 1); + steps.push(archive); + }, + ], + [ + "conditional install", + (steps) => { + steps.find( + (step) => + step.name === "Install reviewed OpenShell SDK archive without package credentials", + )!.if = "${{ false }}"; + }, + ], + ])("rejects %s in the reviewed SDK handoff", (_scenario, mutate) => { + const profile = YAML.parse( + fs.readFileSync(path.join(REPO_ROOT, ".github/workflows/e2e-standard-profile.yaml"), "utf8"), + ); + mutate(profile.jobs.run.steps); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "sdk-profile-order-")); + try { + const profilePath = path.join(directory, "profile.yaml"); + fs.writeFileSync(profilePath, YAML.stringify(profile)); + expect(validateStandardProfileWorkflowBoundary(readWorkflow(), profilePath)).not.toEqual([]); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); it.each([ { field: "uses", value: "actions/setup-python@v7" }, @@ -192,7 +204,7 @@ describe("standard E2E execution profile", () => { const workflow = readWorkflow() as { jobs: Record }; workflow.jobs["package-openshell-sdk"]!.if = "${{ inputs.jobs == 'external-gateway-health' }}"; expect(validateStandardProfileWorkflowBoundary(workflow)).toContain( - "catalogue profiles require SDK packaging for every E2E run with package-read permission", + "catalogue profiles require SDK packaging with package-read permission whenever candidate compilation is selected", ); }); From 322ed37232b631d11470950e461dc8bc6ddd4f5a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 05:56:15 -0700 Subject: [PATCH 29/44] test: preserve provider-switch profile coverage after main sync Signed-off-by: Rebecca Sliter --- ...standard-profile-workflow-boundary.test.ts | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index 9e412aa2dee..7da6607855c 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -16,7 +16,11 @@ import { FULL_E2E_TEST_TIMEOUT_MINUTES, } from "../../../tools/e2e/full-e2e-timeout-contract.mts"; import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; -import { catalogueTarget } from "../../../tools/e2e/target-catalogue.mts"; +import { + catalogueTarget, + catalogueTargetsForChangedFiles, +} from "../../../tools/e2e/target-catalogue.mts"; +import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/workflow-plan.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; const REPO_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -26,6 +30,34 @@ describe("standard E2E execution profile", () => { expect(validateStandardProfileWorkflowBoundary(readWorkflow())).toEqual([]); }); + it( + "routes the credential-free GPU Ollama provider-switch target through the standard profile", + { timeout: 30_000 }, + () => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({ targets: targetId }); + + expect(catalogueTarget(targetId).profile).toBe("standard"); + expect(plan.catalogueMatrices.standard.map((row) => row.id)).toEqual([targetId]); + expect(plan.catalogueMatrices["nvidia-api"]).toEqual([]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard"]); + }, + ); + + it.each(["src/lib/inference/ollama/model-ownership.ts", "src/lib/onboard/setup-inference.ts"])( + "selects the GPU provider-switch target for a source-only %s change", + (changedFile) => { + const targetId = "gpu-double-onboard"; + const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); + + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + targetId, + ); + expect(plan.catalogueMatrices.standard.map((row) => row.id)).toContain(targetId); + expect(selectedWorkflowJobs(plan)).toContain("catalogue-standard"); + }, + ); + it.each< [string, (steps: Array<{ name: string; with?: Record; if?: string }>) => void] >([ From d82fd074d5961b071b42d3e6065d7894b7b73e97 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 06:30:27 -0700 Subject: [PATCH 30/44] fix(ollama): share fail-closed ownership discovery during destroy Capture peer gateway phases once for all pending model cleanup candidates, then preserve per-model ownership decisions. Cover an omitted sibling and a retry with one active and one stopped model. Signed-off-by: Rebecca Sliter --- src/lib/actions/sandbox/destroy.test.ts | 66 +++++++++++++++++++++++++ src/lib/actions/sandbox/destroy.ts | 31 ++++++------ 2 files changed, 83 insertions(+), 14 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.test.ts b/src/lib/actions/sandbox/destroy.test.ts index 84872853249..3316af77692 100644 --- a/src/lib/actions/sandbox/destroy.test.ts +++ b/src/lib/actions/sandbox/destroy.test.ts @@ -130,6 +130,72 @@ describe("cleanupSandboxServices Google Chat tunnel cleanup (#7317)", () => { }); describe("cleanupSandboxServices Ollama ownership", () => { + it("discovers two pending models in one gateway once and keeps cleanup fail-closed", async () => { + const own = { + name: SANDBOX, + gatewayName: "gateway-a", + gatewayPort: 18080, + provider: "nvidia-prod", + model: "replacement", + } as SandboxEntry; + const activePeer = { + name: "active-peer", + gatewayName: "gateway-b", + gatewayPort: 18081, + provider: "ollama-local", + model: "old-model", + } as SandboxEntry; + const stoppedPeer = { + ...activePeer, + name: "stopped-peer", + model: "other-model", + }; + const captureSandboxOwnershipPhases = vi + .fn() + .mockReturnValueOnce({ + status: 0, + output: "NAME CREATED PHASE\nactive-peer 2026-01-01 Running", + }) + .mockReturnValue({ + status: 0, + output: + "NAME CREATED PHASE\nactive-peer 2026-01-01 Running\nstopped-peer 2026-01-01 Stopped", + }); + const unloadOllamaModels = vi.fn(); + const clearPendingOllamaModelCleanup = vi.fn(); + const cleanup = () => + cleanupSandboxServices( + SANDBOX, + { stopHostServices: false, gatewayPort: 18080 }, + { + getSandbox: () => own, + listOllamaModelOwnershipPeers: () => [own, activePeer, stoppedPeer], + loadPersistedOllamaHost: () => "127.0.0.1", + loadPendingOllamaModelCleanup: () => ["old-model", "other-model"], + clearPendingOllamaModelCleanup, + captureSandboxOwnershipPhases, + resolvePersistedSandboxOwnershipGateway: () => "gateway-b", + migrateLegacyCloudflaredState: vi.fn(() => false), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation) => operation(), + rmSync: vi.fn(), + runOpenshell: vi.fn(() => ({ status: 0 })), + stopGooglechatWebhookTunnel: vi.fn(() => googlechatPidDir), + googlechatWebhookTunnelPidDir: vi.fn(() => googlechatPidDir), + }, + ); + + await expect(cleanup()).rejects.toThrow(/omitted sibling/); + expect(captureSandboxOwnershipPhases).toHaveBeenCalledTimes(1); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + + await cleanup(); + expect(captureSandboxOwnershipPhases).toHaveBeenCalledTimes(2); + expect(unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["other-model"]); + expect(clearPendingOllamaModelCleanup).toHaveBeenCalledExactlyOnceWith(own, ["other-model"]); + }); + it("retains a pending model owned by an active sandbox in another gateway root", async () => { const own = { name: SANDBOX, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 455ee36e7f4..9f164971d3c 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -492,8 +492,7 @@ export async function cleanupSandboxServices( } return resolveSandboxDestroyGatewayName(owner.name, owner as registry.SandboxEntry); }); - const releasable: string[] = []; - for (const model of candidates) { + const peersByModel = candidates.map((model) => { const holder = { name: validatedSandboxName, gatewayName: sb?.gatewayName ?? null, @@ -502,19 +501,23 @@ export async function cleanupSandboxServices( model, endpointUrl: null, }; - const matchingPeers = matchingOllamaModelPeers(holder, ownerRows, selectedHost); - const discovery = (deps.discoverOllamaModelOwnership ?? discoverOllamaModelOwnership)( - matchingPeers, - process.env, - captureOwnershipPhases, - { resolvePersistedSandboxOwnershipGateway: resolveOwnerGateway }, + return matchingOllamaModelPeers(holder, ownerRows, selectedHost); + }); + const discovery = (deps.discoverOllamaModelOwnership ?? discoverOllamaModelOwnership)( + [...new Set(peersByModel.flat())], + process.env, + captureOwnershipPhases, + { resolvePersistedSandboxOwnershipGateway: resolveOwnerGateway }, + ); + if (!discovery.ok) { + throw new Error( + `Ollama model ownership could not be verified for '${candidates.join(", ")}': ${discovery.message}. ` + + "No model was unloaded; retry destroy after restoring gateway access.", ); - if (!discovery.ok) { - throw new Error( - `Ollama model ownership could not be verified for '${model}': ${discovery.message}. ` + - "No model was unloaded; retry destroy after restoring gateway access.", - ); - } + } + const releasable: string[] = []; + for (const [index, model] of candidates.entries()) { + const matchingPeers = peersByModel[index]!; const activePeers = discovery.activePeers ? matchingPeers.filter((peer) => discovery.activePeers?.has(peer)) : matchingPeers.filter((peer) => discovery.activeSandboxNames.has(peer.name)); From 48638bfea6ed050aca3be3607461aea463092dfa Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 19:47:46 -0700 Subject: [PATCH 31/44] test(onboard): split Ollama cleanup regression tests Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../setup-inference-ollama-cleanup.test.ts | 516 ++++++++++++++++++ src/lib/onboard/setup-inference.test.ts | 495 +---------------- 2 files changed, 517 insertions(+), 494 deletions(-) create mode 100644 src/lib/onboard/setup-inference-ollama-cleanup.test.ts diff --git a/src/lib/onboard/setup-inference-ollama-cleanup.test.ts b/src/lib/onboard/setup-inference-ollama-cleanup.test.ts new file mode 100644 index 00000000000..f22c449ab89 --- /dev/null +++ b/src/lib/onboard/setup-inference-ollama-cleanup.test.ts @@ -0,0 +1,516 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { + OllamaModelCleanupOwner, + OllamaModelHolder, +} from "../inference/ollama/model-ownership"; +import type { OllamaUnloadResult } from "../inference/ollama/proxy"; +import type { SandboxEntry } from "../state/registry"; +import { releaseSupersededOllamaModel, type SetupInferenceDeps } from "./setup-inference"; + +// Reservation recovery has its own state tests; this suite injects registry writes. +vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ + ...(await importOriginal()), + releaseAbandonedRouteReservation: vi.fn(() => false), +})); + +function createOllamaCleanupHarness( + options: { + peers?: readonly SandboxEntry[]; + useProductionPeerSource?: boolean; + useProductionDiscovery?: boolean; + activeSandboxNames?: ReadonlySet; + discovery?: SetupInferenceDeps["discoverActiveOllamaSandboxNames"]; + pendingModels?: readonly string[]; + unloadResult?: OllamaUnloadResult; + } = {}, +) { + let pendingModels = [...(options.pendingModels ?? [])]; + const localInference = { + loadPersistedOllamaHost: vi.fn(() => "127.0.0.1"), + loadPendingOllamaModelCleanup: vi.fn((_owner: OllamaModelCleanupOwner) => pendingModels), + persistPendingOllamaModelCleanup: vi.fn( + (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { + pendingModels = [...new Set([...pendingModels, ...models])]; + }, + ), + clearPendingOllamaModelCleanup: vi.fn( + (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { + pendingModels = pendingModels.filter((model) => !models.includes(model)); + }, + ), + clearPersistedOllamaHostIfUnused: vi.fn(), + }; + const unloadOllamaModels = vi.fn( + () => + options.unloadResult ?? { + ok: true, + outcome: "released" as const, + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }, + ); + const discoverActiveOllamaSandboxNames = vi.fn( + options.discovery ?? + (() => ({ + ok: true as const, + activeSandboxNames: options.activeSandboxNames ?? new Set(), + gatewayChecks: [], + })), + ); + const deps = { + localInference, + ...(options.useProductionPeerSource + ? {} + : { listOllamaModelOwnershipPeers: () => options.peers ?? [] }), + ...(!options.useProductionDiscovery ? { discoverActiveOllamaSandboxNames } : {}), + unloadOllamaModels, + withOllamaModelOwnershipLock: (operation: () => void) => operation(), + } as unknown as SetupInferenceDeps; + return { deps, localInference, unloadOllamaModels, discoverActiveOllamaSandboxNames }; +} + +const previousLocalOllamaRoute: OllamaModelHolder = { + name: "alpha", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-alpha", + lifecycleLiveIdentityFingerprint: "a".repeat(64), +}; + +function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): void { + releaseSupersededOllamaModel( + previous, + "nvidia-prod", + "nvidia/test-model", + "https://integrate.api.nvidia.com/v1", + { ok: true }, + deps, + ); +} + +describe("releaseSupersededOllamaModel", () => { + it("preserves the host target for a stopped peer after releasing its model", () => { + const stoppedPeer = { + name: "stopped-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: "http://127.0.0.1:11434", + gatewayName: "nemoclaw-32678", + gatewayPort: 32678, + } as unknown as SandboxEntry; + const harness = createOllamaCleanupHarness({ peers: [stoppedPeer] }); + + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).toHaveBeenCalledExactlyOnceWith( + [stoppedPeer], + ); + }); + + it("releases the target model before unrelated gateway discovery for receipt retirement", () => { + const unrelatedPeer = { + name: "unrelated-peer", + provider: "ollama-local", + model: "llama3.2:1b", + endpointUrl: null, + gatewayName: "unavailable-gateway", + } as unknown as SandboxEntry; + const discovery = vi.fn((owners: readonly OllamaModelHolder[]) => + owners.some((owner) => owner.model === "llama3.2:1b") + ? { ok: false as const, message: "unrelated gateway unavailable" } + : { ok: true as const, activeSandboxNames: new Set(), gatewayChecks: [] }, + ); + const harness = createOllamaCleanupHarness({ peers: [unrelatedPeer], discovery }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(discovery).toHaveBeenCalledTimes(2); + expect(discovery.mock.calls[0]?.[0]).toEqual([]); + expect(discovery.mock.calls[1]?.[0]).toEqual([unrelatedPeer]); + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("host route receipt was retained"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("preserves the model and host receipt while a matching live peer owns it", () => { + const activePeer = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + endpointUrl: null, + gatewayName: "peer-gateway-port", + } as unknown as SandboxEntry; + const harness = createOllamaCleanupHarness({ + peers: [activePeer], + activeSandboxNames: new Set([activePeer.name]), + }); + + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); + + it("uses Ollama peer records from other gateway roots by default", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-peer-roots-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "active-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + activeSandboxNames: new Set([peer.name]), + }); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); + expect(harness.discoverActiveOllamaSandboxNames.mock.calls[0]?.[0]).toEqual([ + expect.objectContaining({ name: "active-peer", gatewayName: "nemoclaw-32665" }), + ]); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("keeps the model and records retry when a sibling gateway has state but no registry", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-missing-peer-registry-")); + vi.stubEnv("HOME", home); + const siblingRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(siblingRoot, { recursive: true }); + fs.writeFileSync(path.join(siblingRoot, "onboard-session.json"), "{}"); + const harness = createOllamaCleanupHarness({ useProductionPeerSource: true }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("sandboxes.json is missing")); + } finally { + warning.mockRestore(); + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("uses the injected phase capture for cross-gateway discovery", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "active-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "active-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + useProductionDiscovery: true, + }); + const captureOllamaOwnershipPhases = vi.fn(() => ({ + status: 0, + output: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", + })); + const deps = harness.deps as SetupInferenceDeps; + deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; + deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName!; + + try { + releaseToNvidia(previousLocalOllamaRoute, deps); + + expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( + "nemoclaw-32665", + process.env, + ); + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("fails closed and records retry state when a successful inventory omits a matching peer", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-omitted-inventory-")); + vi.stubEnv("HOME", home); + const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); + fs.mkdirSync(gatewayRoot, { recursive: true }); + const peer: SandboxEntry = { + name: "stale-peer", + provider: "ollama-local", + model: "qwen2.5:1.5b", + gatewayName: "nemoclaw-32665", + gatewayPort: 32665, + endpointUrl: "http://127.0.0.1:11434", + }; + fs.writeFileSync( + path.join(gatewayRoot, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { "stale-peer": peer }, + }), + ); + const harness = createOllamaCleanupHarness({ + useProductionPeerSource: true, + useProductionDiscovery: true, + }); + const captureOllamaOwnershipPhases = vi.fn(() => ({ + status: 0, + output: "NAME CREATED PHASE", + })); + const deps = harness.deps as SetupInferenceDeps; + deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; + deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName ?? "default"; + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( + "nemoclaw-32665", + process.env, + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); + } finally { + warning.mockRestore(); + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("records a failed ownership probe for retry, then unloads only after a safe retry", () => { + const discovery = vi + .fn>() + .mockReturnValueOnce({ ok: false, message: "gateway unavailable" }) + .mockReturnValueOnce({ ok: true, activeSandboxNames: new Set(), gatewayChecks: [] }); + const harness = createOllamaCleanupHarness({ discovery }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); + + releaseToNvidia({ ...previousLocalOllamaRoute, provider: "nvidia-prod" }, harness.deps); + + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( + expect.objectContaining({ + name: "alpha", + gatewayName: "nemoclaw-32677", + gatewayPort: 32677, + lifecycleGeneration: "generation-alpha", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + }), + ["qwen2.5:1.5b"], + ); + } finally { + warning.mockRestore(); + } + }); + + it("records the old model when identity changes after the new route commits", () => { + const harness = createOllamaCleanupHarness(); + const refusal = new Error("sandbox lifecycle changed"); + const attempt = () => + releaseSupersededOllamaModel( + previousLocalOllamaRoute, + "nvidia-prod", + "nvidia/test-model", + "https://integrate.api.nvidia.com/v1", + { ok: true }, + harness.deps, + () => { + throw refusal; + }, + ); + + expect(attempt).toThrow(refusal); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledExactlyOnceWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { + throw new Error("receipt write failed"); + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + expect(attempt).toThrow(refusal); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("Cleanup retry state could not be recorded"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("requires manual recovery when ownership failure cannot be recorded for retry", () => { + const discovery = vi.fn>( + () => ({ ok: false, message: "gateway unavailable" }), + ); + const harness = createOllamaCleanupHarness({ discovery }); + harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { + throw new Error( + "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", + ); + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia( + { + ...previousLocalOllamaRoute, + lifecycleGeneration: undefined, + lifecycleLiveIdentityFingerprint: undefined, + }, + harness.deps, + ); + + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining( + "Manually verify that no active matching sandbox owns the model before releasing only qwen2.5:1.5b", + ), + ); + expect(warning).not.toHaveBeenCalledWith( + expect.stringContaining("Re-run onboarding to retry only"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("keeps the retry record when unloading the superseded model fails", () => { + const harness = createOllamaCleanupHarness({ + unloadResult: { + ok: false, + outcome: "still-resident", + endpoint: "http://127.0.0.1:11434", + selectedModels: ["qwen2.5:1.5b"], + discoveries: [], + requests: [], + }, + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + try { + releaseToNvidia(previousLocalOllamaRoute, harness.deps); + + expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); + expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( + previousLocalOllamaRoute, + ["qwen2.5:1.5b"], + ); + expect(harness.localInference.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("Re-run onboarding or destroy 'alpha' to retry only"), + ); + } finally { + warning.mockRestore(); + } + }); + + it("does not probe or warn when the selected route still owns the same Ollama model", () => { + const harness = createOllamaCleanupHarness(); + + releaseSupersededOllamaModel( + previousLocalOllamaRoute, + "ollama-local", + "qwen2.5:1.5b", + "http://127.0.0.1:11434", + { ok: true }, + harness.deps, + ); + + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); + + it("does not probe unrelated routes when there is no Ollama cleanup retry", () => { + const harness = createOllamaCleanupHarness({ + peers: [{ name: "ollama-peer", provider: "ollama-local", model: "qwen2.5:1.5b" }], + }); + + releaseToNvidia( + { name: "alpha", provider: "nvidia-prod", model: "nvidia/model" }, + harness.deps, + ); + + expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); + expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 72c25fed6bf..cff449faf67 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -1,25 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../inference/native-nvidia/contract"; -import type { - OllamaModelCleanupOwner, - OllamaModelHolder, -} from "../inference/ollama/model-ownership"; -import type { OllamaUnloadResult } from "../inference/ollama/proxy"; -import type { SandboxEntry } from "../state/registry"; +import type { OllamaModelHolder } from "../inference/ollama/model-ownership"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { createProviderReviewDeps, createSetupInference, - releaseSupersededOllamaModel, type SetupInferenceDeps, } from "./setup-inference"; @@ -29,64 +19,6 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); -function createOllamaCleanupHarness( - options: { - peers?: readonly SandboxEntry[]; - useProductionPeerSource?: boolean; - useProductionDiscovery?: boolean; - activeSandboxNames?: ReadonlySet; - discovery?: SetupInferenceDeps["discoverActiveOllamaSandboxNames"]; - pendingModels?: readonly string[]; - unloadResult?: OllamaUnloadResult; - } = {}, -) { - let pendingModels = [...(options.pendingModels ?? [])]; - const localInference = { - loadPersistedOllamaHost: vi.fn(() => "127.0.0.1"), - loadPendingOllamaModelCleanup: vi.fn((_owner: OllamaModelCleanupOwner) => pendingModels), - persistPendingOllamaModelCleanup: vi.fn( - (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { - pendingModels = [...new Set([...pendingModels, ...models])]; - }, - ), - clearPendingOllamaModelCleanup: vi.fn( - (_owner: OllamaModelCleanupOwner, models: readonly string[]) => { - pendingModels = pendingModels.filter((model) => !models.includes(model)); - }, - ), - clearPersistedOllamaHostIfUnused: vi.fn(), - }; - const unloadOllamaModels = vi.fn( - () => - options.unloadResult ?? { - ok: true, - outcome: "released" as const, - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - }, - ); - const discoverActiveOllamaSandboxNames = vi.fn( - options.discovery ?? - (() => ({ - ok: true as const, - activeSandboxNames: options.activeSandboxNames ?? new Set(), - gatewayChecks: [], - })), - ); - const deps = { - localInference, - ...(options.useProductionPeerSource - ? {} - : { listOllamaModelOwnershipPeers: () => options.peers ?? [] }), - ...(!options.useProductionDiscovery ? { discoverActiveOllamaSandboxNames } : {}), - unloadOllamaModels, - withOllamaModelOwnershipLock: (operation: () => void) => operation(), - } as unknown as SetupInferenceDeps; - return { deps, localInference, unloadOllamaModels, discoverActiveOllamaSandboxNames }; -} - const previousLocalOllamaRoute: OllamaModelHolder = { name: "alpha", provider: "ollama-local", @@ -98,431 +30,6 @@ const previousLocalOllamaRoute: OllamaModelHolder = { lifecycleLiveIdentityFingerprint: "a".repeat(64), }; -function releaseToNvidia(previous: OllamaModelHolder, deps: SetupInferenceDeps): void { - releaseSupersededOllamaModel( - previous, - "nvidia-prod", - "nvidia/test-model", - "https://integrate.api.nvidia.com/v1", - { ok: true }, - deps, - ); -} - -describe("releaseSupersededOllamaModel", () => { - it("preserves the host target for a stopped peer after releasing its model", () => { - const stoppedPeer = { - name: "stopped-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - endpointUrl: "http://127.0.0.1:11434", - gatewayName: "nemoclaw-32678", - gatewayPort: 32678, - } as unknown as SandboxEntry; - const harness = createOllamaCleanupHarness({ peers: [stoppedPeer] }); - - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).toHaveBeenCalledExactlyOnceWith( - [stoppedPeer], - ); - }); - - it("releases the target model before unrelated gateway discovery for receipt retirement", () => { - const unrelatedPeer = { - name: "unrelated-peer", - provider: "ollama-local", - model: "llama3.2:1b", - endpointUrl: null, - gatewayName: "unavailable-gateway", - } as unknown as SandboxEntry; - const discovery = vi.fn((owners: readonly OllamaModelHolder[]) => - owners.some((owner) => owner.model === "llama3.2:1b") - ? { ok: false as const, message: "unrelated gateway unavailable" } - : { ok: true as const, activeSandboxNames: new Set(), gatewayChecks: [] }, - ); - const harness = createOllamaCleanupHarness({ peers: [unrelatedPeer], discovery }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(discovery).toHaveBeenCalledTimes(2); - expect(discovery.mock.calls[0]?.[0]).toEqual([]); - expect(discovery.mock.calls[1]?.[0]).toEqual([unrelatedPeer]); - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining("host route receipt was retained"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("preserves the model and host receipt while a matching live peer owns it", () => { - const activePeer = { - name: "active-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - endpointUrl: null, - gatewayName: "peer-gateway-port", - } as unknown as SandboxEntry; - const harness = createOllamaCleanupHarness({ - peers: [activePeer], - activeSandboxNames: new Set([activePeer.name]), - }); - - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - }); - - it("uses Ollama peer records from other gateway roots by default", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-peer-roots-")); - vi.stubEnv("HOME", home); - const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(gatewayRoot, { recursive: true }); - const peer: SandboxEntry = { - name: "active-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - gatewayName: "nemoclaw-32665", - gatewayPort: 32665, - endpointUrl: "http://127.0.0.1:11434", - }; - fs.writeFileSync( - path.join(gatewayRoot, "sandboxes.json"), - JSON.stringify({ - defaultSandbox: null, - defaultSelectionRevision: 1, - sandboxes: { "active-peer": peer }, - }), - ); - const harness = createOllamaCleanupHarness({ - useProductionPeerSource: true, - activeSandboxNames: new Set([peer.name]), - }); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.discoverActiveOllamaSandboxNames).toHaveBeenCalledOnce(); - expect(harness.discoverActiveOllamaSandboxNames.mock.calls[0]?.[0]).toEqual([ - expect.objectContaining({ name: "active-peer", gatewayName: "nemoclaw-32665" }), - ]); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - } finally { - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("keeps the model and records retry when a sibling gateway has state but no registry", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-missing-peer-registry-")); - vi.stubEnv("HOME", home); - const siblingRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(siblingRoot, { recursive: true }); - fs.writeFileSync(path.join(siblingRoot, "onboard-session.json"), "{}"); - const harness = createOllamaCleanupHarness({ useProductionPeerSource: true }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("sandboxes.json is missing")); - } finally { - warning.mockRestore(); - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("uses the injected phase capture for cross-gateway discovery", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-default-discovery-")); - vi.stubEnv("HOME", home); - const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(gatewayRoot, { recursive: true }); - const peer: SandboxEntry = { - name: "active-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - gatewayName: "nemoclaw-32665", - gatewayPort: 32665, - endpointUrl: "http://127.0.0.1:11434", - }; - fs.writeFileSync( - path.join(gatewayRoot, "sandboxes.json"), - JSON.stringify({ - defaultSandbox: null, - defaultSelectionRevision: 1, - sandboxes: { "active-peer": peer }, - }), - ); - const harness = createOllamaCleanupHarness({ - useProductionPeerSource: true, - useProductionDiscovery: true, - }); - const captureOllamaOwnershipPhases = vi.fn(() => ({ - status: 0, - output: "NAME CREATED PHASE\nactive-peer 2026-08-25 Ready\n", - })); - const deps = harness.deps as SetupInferenceDeps; - deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; - deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName!; - - try { - releaseToNvidia(previousLocalOllamaRoute, deps); - - expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( - "nemoclaw-32665", - process.env, - ); - expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - } finally { - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("fails closed and records retry state when a successful inventory omits a matching peer", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-omitted-inventory-")); - vi.stubEnv("HOME", home); - const gatewayRoot = path.join(home, ".nemoclaw", "gateways", "32665"); - fs.mkdirSync(gatewayRoot, { recursive: true }); - const peer: SandboxEntry = { - name: "stale-peer", - provider: "ollama-local", - model: "qwen2.5:1.5b", - gatewayName: "nemoclaw-32665", - gatewayPort: 32665, - endpointUrl: "http://127.0.0.1:11434", - }; - fs.writeFileSync( - path.join(gatewayRoot, "sandboxes.json"), - JSON.stringify({ - defaultSandbox: null, - defaultSelectionRevision: 1, - sandboxes: { "stale-peer": peer }, - }), - ); - const harness = createOllamaCleanupHarness({ - useProductionPeerSource: true, - useProductionDiscovery: true, - }); - const captureOllamaOwnershipPhases = vi.fn(() => ({ - status: 0, - output: "NAME CREATED PHASE", - })); - const deps = harness.deps as SetupInferenceDeps; - deps.captureOllamaOwnershipPhases = captureOllamaOwnershipPhases; - deps.resolveOllamaOwnershipGateway = (sandbox) => sandbox.gatewayName ?? "default"; - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(captureOllamaOwnershipPhases).toHaveBeenCalledExactlyOnceWith( - "nemoclaw-32665", - process.env, - ); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); - } finally { - warning.mockRestore(); - vi.unstubAllEnvs(); - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("records a failed ownership probe for retry, then unloads only after a safe retry", () => { - const discovery = vi - .fn>() - .mockReturnValueOnce({ ok: false, message: "gateway unavailable" }) - .mockReturnValueOnce({ ok: true, activeSandboxNames: new Set(), gatewayChecks: [] }); - const harness = createOllamaCleanupHarness({ discovery }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("No model was unloaded")); - - releaseToNvidia({ ...previousLocalOllamaRoute, provider: "nvidia-prod" }, harness.deps); - - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.clearPendingOllamaModelCleanup).toHaveBeenCalledWith( - expect.objectContaining({ - name: "alpha", - gatewayName: "nemoclaw-32677", - gatewayPort: 32677, - lifecycleGeneration: "generation-alpha", - lifecycleLiveIdentityFingerprint: "a".repeat(64), - }), - ["qwen2.5:1.5b"], - ); - } finally { - warning.mockRestore(); - } - }); - - it("records the old model when identity changes after the new route commits", () => { - const harness = createOllamaCleanupHarness(); - const refusal = new Error("sandbox lifecycle changed"); - const attempt = () => - releaseSupersededOllamaModel( - previousLocalOllamaRoute, - "nvidia-prod", - "nvidia/test-model", - "https://integrate.api.nvidia.com/v1", - { ok: true }, - harness.deps, - () => { - throw refusal; - }, - ); - - expect(attempt).toThrow(refusal); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledExactlyOnceWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { - throw new Error("receipt write failed"); - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - try { - expect(attempt).toThrow(refusal); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining("Cleanup retry state could not be recorded"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("requires manual recovery when ownership failure cannot be recorded for retry", () => { - const discovery = vi.fn>( - () => ({ ok: false, message: "gateway unavailable" }), - ); - const harness = createOllamaCleanupHarness({ discovery }); - harness.localInference.persistPendingOllamaModelCleanup.mockImplementation(() => { - throw new Error( - "Cannot persist pending Ollama cleanup without complete sandbox ownership identity", - ); - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia( - { - ...previousLocalOllamaRoute, - lifecycleGeneration: undefined, - lifecycleLiveIdentityFingerprint: undefined, - }, - harness.deps, - ); - - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining( - "Manually verify that no active matching sandbox owns the model before releasing only qwen2.5:1.5b", - ), - ); - expect(warning).not.toHaveBeenCalledWith( - expect.stringContaining("Re-run onboarding to retry only"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("keeps the retry record when unloading the superseded model fails", () => { - const harness = createOllamaCleanupHarness({ - unloadResult: { - ok: false, - outcome: "still-resident", - endpoint: "http://127.0.0.1:11434", - selectedModels: ["qwen2.5:1.5b"], - discoveries: [], - requests: [], - }, - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - - try { - releaseToNvidia(previousLocalOllamaRoute, harness.deps); - - expect(harness.unloadOllamaModels).toHaveBeenCalledExactlyOnceWith(["qwen2.5:1.5b"]); - expect(harness.localInference.persistPendingOllamaModelCleanup).toHaveBeenCalledWith( - previousLocalOllamaRoute, - ["qwen2.5:1.5b"], - ); - expect(harness.localInference.clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining("Re-run onboarding or destroy 'alpha' to retry only"), - ); - } finally { - warning.mockRestore(); - } - }); - - it("does not probe or warn when the selected route still owns the same Ollama model", () => { - const harness = createOllamaCleanupHarness(); - - releaseSupersededOllamaModel( - previousLocalOllamaRoute, - "ollama-local", - "qwen2.5:1.5b", - "http://127.0.0.1:11434", - { ok: true }, - harness.deps, - ); - - expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - }); - - it("does not probe unrelated routes when there is no Ollama cleanup retry", () => { - const harness = createOllamaCleanupHarness({ - peers: [{ name: "ollama-peer", provider: "ollama-local", model: "qwen2.5:1.5b" }], - }); - - releaseToNvidia( - { name: "alpha", provider: "nvidia-prod", model: "nvidia/model" }, - harness.deps, - ); - - expect(harness.discoverActiveOllamaSandboxNames).not.toHaveBeenCalled(); - expect(harness.unloadOllamaModels).not.toHaveBeenCalled(); - expect(harness.localInference.clearPersistedOllamaHostIfUnused).not.toHaveBeenCalled(); - }); -}); - describe("recorded Pi local inference route", () => { it("rejects a changed selection before invoking a provider or gateway", async () => { const getSandbox = vi.fn(() => ({ From 2a6154f6554b28ee3f61be6dcf065bc1ef9ece20 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 20:22:24 -0700 Subject: [PATCH 32/44] test(destroy): model sibling phases in cross-root fixtures Align cross-root fixtures with the live sibling inventory required by fail-closed Ollama ownership checks, and correct the destroy documentation. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/reference/commands.mdx | 2 +- .../sandbox/destroy-cross-root.test.ts | 38 ++++++++++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 7529c9148ad..7685f42b21d 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2233,7 +2233,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` ### `$$nemoclaw destroy` -Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. After confirmed deletion, `destroy` removes the sandbox from the registry only when required cleanup and ownership checks succeed. If Ollama cleanup or ownership verification fails, it retains the registry entry; follow the reported recovery action and retry `destroy`. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. If `OPENSHELL_GATEWAY_ENDPOINT` is set, `destroy` refuses to probe or delete the sandbox; unset the variable and retry. For Ollama-backed sandboxes, `destroy` best-effort unloads only that sandbox's current Ollama model and any models recorded for a cleanup retry. It preserves a model still used by an active matching sandbox, and clears stale auth proxy state on a best-effort basis. +Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. After confirmed deletion, `destroy` removes the sandbox from the registry only when required cleanup and ownership checks succeed. If Ollama cleanup or ownership verification fails, it retains the registry entry; follow the reported recovery action and retry `destroy`. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. If `OPENSHELL_GATEWAY_ENDPOINT` is set, `destroy` refuses to probe or delete the sandbox; unset the variable and retry. For Ollama-backed sandboxes, `destroy` unloads only that sandbox's current Ollama model and any models recorded for a cleanup retry. It preserves a model still used by an active matching sandbox, and clears stale auth proxy state on a best-effort basis. `destroy` considers retirement of the host-global `nemoclaw-vllm` container for a sandbox with provider `vllm-local`, including Local NIM. It requires confirmed sandbox deletion and no remaining registered `vllm-local` consumer in any gateway state root. diff --git a/src/lib/actions/sandbox/destroy-cross-root.test.ts b/src/lib/actions/sandbox/destroy-cross-root.test.ts index 841de71aab1..d206f523e12 100644 --- a/src/lib/actions/sandbox/destroy-cross-root.test.ts +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createDestroyHarness, resetDestroyModuleCache, + sandboxListJson, } from "../../../../test/helpers/destroy-flow-test-harness"; import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; @@ -36,6 +37,25 @@ function writeGatewayRegistry(home: string, port: number, name: string): void { ); } +function keepSiblingVisibleAfterDelete(harness: ReturnType): void { + const runOpenshell = harness.runOpenshellSpy.getMockImplementation(); + let betaDeleted = false; + harness.runOpenshellSpy.mockImplementation((args: unknown, options: unknown) => { + const argv = Array.isArray(args) ? args.map(String) : []; + if (betaDeleted && argv[0] === "sandbox" && argv[1] === "list") { + return { status: 0, stdout: sandboxListJson(["alpha"]), stderr: "" }; + } + if (betaDeleted && argv[0] === "sandbox" && argv[1] === "get" && argv.at(-1) === "beta") { + return { status: 1, stdout: "", stderr: "Error: sandbox beta not found" }; + } + const result = runOpenshell?.(args, options) ?? { status: 0, stdout: "", stderr: "" }; + if (argv[0] === "sandbox" && argv[1] === "delete" && argv.at(-1) === "beta") { + betaDeleted = true; + } + return result; + }); +} + describe("destroySandbox cross-root registry authority", () => { let home: string; @@ -96,7 +116,14 @@ describe("destroySandbox cross-root registry authority", () => { it("cleans up the destroyed gateway while preserving a sandbox on another gateway", async () => { writeGatewayRegistry(home, 8244, "alpha"); writeGatewayRegistry(home, 8245, "beta"); - const harness = createDestroyHarness(); + const harness = createDestroyHarness({ + sandboxListResult: { + status: 0, + stdout: "NAME PHASE\nalpha Ready\nbeta Ready", + stderr: "", + }, + }); + keepSiblingVisibleAfterDelete(harness); await expect( harness.destroySandbox("beta", { yes: true, cleanupGateway: true }), @@ -120,7 +147,14 @@ describe("destroySandbox cross-root registry authority", () => { writeGatewayRegistry(home, 8244, "alpha"); writeGatewayRegistry(home, 8245, "beta"); const betaRegistryFile = path.join(home, ".nemoclaw", "gateways", "8245", "sandboxes.json"); - const harness = createDestroyHarness(); + const harness = createDestroyHarness({ + sandboxListResult: { + status: 0, + stdout: "NAME PHASE\nalpha Ready\nbeta Ready", + stderr: "", + }, + }); + keepSiblingVisibleAfterDelete(harness); harness.withGatewayRouteMutationLockSpy .mockImplementationOnce(async (_gatewayName: unknown, operation: unknown) => (operation as () => Promise)(), From b7b9c7aeec4ef0992b185255e09f82d81f99c3f5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 20:32:16 -0700 Subject: [PATCH 33/44] test(destroy): keep fixture branching in support harness Preserve cross-root destroy test behavior while satisfying the independent test conditional growth guardrail. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/destroy-cross-root.test.ts | 25 +++---------------- test/helpers/destroy-flow-test-harness.ts | 24 ++++++++++++++++++ 2 files changed, 27 insertions(+), 22 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-cross-root.test.ts b/src/lib/actions/sandbox/destroy-cross-root.test.ts index d206f523e12..aa649074bf1 100644 --- a/src/lib/actions/sandbox/destroy-cross-root.test.ts +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -9,9 +9,9 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { + configureSiblingSandboxAfterDelete, createDestroyHarness, resetDestroyModuleCache, - sandboxListJson, } from "../../../../test/helpers/destroy-flow-test-harness"; import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; @@ -37,25 +37,6 @@ function writeGatewayRegistry(home: string, port: number, name: string): void { ); } -function keepSiblingVisibleAfterDelete(harness: ReturnType): void { - const runOpenshell = harness.runOpenshellSpy.getMockImplementation(); - let betaDeleted = false; - harness.runOpenshellSpy.mockImplementation((args: unknown, options: unknown) => { - const argv = Array.isArray(args) ? args.map(String) : []; - if (betaDeleted && argv[0] === "sandbox" && argv[1] === "list") { - return { status: 0, stdout: sandboxListJson(["alpha"]), stderr: "" }; - } - if (betaDeleted && argv[0] === "sandbox" && argv[1] === "get" && argv.at(-1) === "beta") { - return { status: 1, stdout: "", stderr: "Error: sandbox beta not found" }; - } - const result = runOpenshell?.(args, options) ?? { status: 0, stdout: "", stderr: "" }; - if (argv[0] === "sandbox" && argv[1] === "delete" && argv.at(-1) === "beta") { - betaDeleted = true; - } - return result; - }); -} - describe("destroySandbox cross-root registry authority", () => { let home: string; @@ -123,7 +104,7 @@ describe("destroySandbox cross-root registry authority", () => { stderr: "", }, }); - keepSiblingVisibleAfterDelete(harness); + configureSiblingSandboxAfterDelete(harness, "beta", ["alpha"]); await expect( harness.destroySandbox("beta", { yes: true, cleanupGateway: true }), @@ -154,7 +135,7 @@ describe("destroySandbox cross-root registry authority", () => { stderr: "", }, }); - keepSiblingVisibleAfterDelete(harness); + configureSiblingSandboxAfterDelete(harness, "beta", ["alpha"]); harness.withGatewayRouteMutationLockSpy .mockImplementationOnce(async (_gatewayName: unknown, operation: unknown) => (operation as () => Promise)(), diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 7d350b9aef1..420396e215e 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -196,6 +196,30 @@ export function configureFailedGatewayList(harness: Pick, + deletedName: string, + remainingNames: string[], +): void { + const runOpenshell = harness.runOpenshellSpy.getMockImplementation(); + let deleted = false; + harness.runOpenshellSpy.mockImplementation((args: unknown, options: unknown) => { + const argv = Array.isArray(args) ? args.map(String) : []; + if (deleted && argv[0] === "sandbox" && argv[1] === "list") { + return { status: 0, stdout: sandboxListJson(remainingNames), stderr: "" }; + } + if (deleted && argv[0] === "sandbox" && argv[1] === "get" && argv.at(-1) === deletedName) { + return { status: 1, stdout: "", stderr: `Error: sandbox ${deletedName} not found` }; + } + const result = runOpenshell?.(args, options) ?? { status: 0, stdout: "", stderr: "" }; + if (argv[0] === "sandbox" && argv[1] === "delete" && argv.at(-1) === deletedName) { + deleted = true; + } + return result; + }); +} + export function traceDestroyBoundaryCalls( harness: Pick, trace: string[], From 60e636464f964143ffc1fc2623b4499007a05632 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 21:12:52 -0700 Subject: [PATCH 34/44] test(e2e): cover Ollama switch through re-onboarding Exercise the accepted provider-switch path through re-onboarding while preserving the existing live assertions. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/live/gpu-double-onboard.test.ts | 37 +++++++++--------------- 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 488c7733231..45a289cb446 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -211,7 +211,7 @@ test( "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", "the sandbox-owned native provider reaches Ollama after first onboard and re-onboard", "Ollama reports the selected model as active before the provider switch", - "nemoclaw inference set switches the sandbox to a local compatible endpoint", + "nemoclaw onboard switches the sandbox to a local compatible endpoint", "sandbox inference succeeds through the new provider and host ollama ps no longer reports the superseded model", ], }); @@ -412,7 +412,7 @@ exit "$status"`, model: SWITCH_MODEL, port: 8000, progress, - publicHost: "localhost", + publicHost: "host.openshell.internal", requireAuth: true, requireAuthModels: true, }); @@ -423,31 +423,20 @@ exit "$status"`, await fake.close(); } }); - // Inference set accepts this explicit sandbox-to-host bridge, while a raw - // localhost URL is deliberately rejected at its SSRF boundary. - const switchEndpointUrl = fake.baseUrl.replace("localhost", "host.openshell.internal"); progress.phase("switch inference to a non-Ollama provider"); const providerSwitch = await nemoclaw( host, - [ - "inference", - "set", - "--provider", - "compatible-endpoint", - "--model", - SWITCH_MODEL, - "--sandbox", - SANDBOX_NAME, - "--endpoint-url", - switchEndpointUrl, - "--credential-env", - "COMPATIBLE_API_KEY", - "--inference-api", - "openai-completions", - ], - "phase-8-inference-set-away-from-ollama", - { COMPATIBLE_API_KEY: SWITCH_API_KEY }, - execTimeout(5 * 60_000), + ["onboard", "--non-interactive", "--yes"], + "phase-8-reonboard-away-from-ollama", + { + COMPATIBLE_API_KEY: SWITCH_API_KEY, + NEMOCLAW_COMPAT_MODEL: SWITCH_MODEL, + NEMOCLAW_ENDPOINT_URL: fake.baseUrl, + NEMOCLAW_MODEL: SWITCH_MODEL, + NEMOCLAW_PREFERRED_API: "openai-completions", + NEMOCLAW_PROVIDER: "custom", + }, + execTimeout(30 * 60_000), [SWITCH_API_KEY], ); expect(providerSwitch.exitCode, resultText(providerSwitch)).toBe(0); From 886b3e87df41a21f692ca42ff45a28ae70645ddb Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 21:43:41 -0700 Subject: [PATCH 35/44] docs: clarify recovery for absent legacy Ollama model Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 88a747a7bc2..de9acad17cb 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -425,13 +425,15 @@ Before manually releasing a listed model, verify that no active sandbox on this 1. Run `openshell gateway list` and identify every NemoClaw gateway on the host. Do not assume the selected gateway is the only one. 2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. 3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= $$nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. -4. Only after every gateway and sandbox was checked successfully and no active sandbox uses the listed model, confirm the model appears in `ollama ps`. Run these commands against the same host Ollama daemon NemoClaw uses. Stop only the exact listed model, then verify that it is absent: +4. After every gateway and sandbox check succeeds and no active sandbox uses the listed model, run `ollama ps` against the host Ollama daemon NemoClaw uses. If the listed model is present, stop only that model and confirm it is absent: ```bash ollama stop '' ollama ps ``` + If the listed model is already absent, continue to step 5. + 5. After the ownership checks succeed and every listed model is confirmed absent from `ollama ps`, acknowledge the completed manual recovery by removing only that sandbox's legacy receipt: ```bash From 9376e205b545cf1c4989342551e3733e08a8e4b2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Tue, 27 Oct 2026 22:01:55 -0700 Subject: [PATCH 36/44] docs: match implicit Ollama latest tag during cleanup Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index de9acad17cb..07cc1e85372 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -425,14 +425,16 @@ Before manually releasing a listed model, verify that no active sandbox on this 1. Run `openshell gateway list` and identify every NemoClaw gateway on the host. Do not assume the selected gateway is the only one. 2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. 3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= $$nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. -4. After every gateway and sandbox check succeeds and no active sandbox uses the listed model, run `ollama ps` against the host Ollama daemon NemoClaw uses. If the listed model is present, stop only that model and confirm it is absent: +4. After every gateway and sandbox check succeeds and no active sandbox uses the listed model, run `ollama ps` against the host Ollama daemon NemoClaw uses. + Treat a listed model without a tag as its `:latest` variant when comparing with `ollama ps`. + If a matching model is present, stop only the matching `ollama ps` model and confirm it is absent: ```bash - ollama stop '' + ollama stop '' ollama ps ``` - If the listed model is already absent, continue to step 5. + If no matching model appears in `ollama ps`, continue to step 5. 5. After the ownership checks succeed and every listed model is confirmed absent from `ollama ps`, acknowledge the completed manual recovery by removing only that sandbox's legacy receipt: From 7909500d23dfeef5a2e2b4ed0e1726b2d5c9987c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 00:05:42 -0700 Subject: [PATCH 37/44] test(e2e): exercise ordinary provider switch after Ollama Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/live/gpu-double-onboard.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 45a289cb446..03c38329daa 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -435,6 +435,7 @@ exit "$status"`, NEMOCLAW_MODEL: SWITCH_MODEL, NEMOCLAW_PREFERRED_API: "openai-completions", NEMOCLAW_PROVIDER: "custom", + NEMOCLAW_RECREATE_SANDBOX: "0", }, execTimeout(30 * 60_000), [SWITCH_API_KEY], From 6e04e46b11e53786f8e69a53ecfba38b827b8cbc Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 00:55:18 -0700 Subject: [PATCH 38/44] test(e2e): keep Ollama model resident through provider switch Pin the active model beyond the switch timeout so post-switch absence proves unload rather than natural eviction. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/live/gpu-double-onboard.test.ts | 32 +++++++++++++++++------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 03c38329daa..2f6d654f29d 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -396,15 +396,6 @@ exit "$status"`, await expectSandboxInference42(sandbox, model, "phase-6-sandbox-inference-after-reonboard"); - progress.phase("verify the Ollama model is active before switching providers"); - const activeModelsBeforeSwitch = await host.command("ollama", ["ps"], { - artifactName: "phase-7-ollama-ps-before-provider-switch", - env: env(), - timeoutMs: 30_000, - }); - expect(activeModelsBeforeSwitch.exitCode, resultText(activeModelsBeforeSwitch)).toBe(0); - expect(activeModelsBeforeSwitch.stdout).toContain(model); - const fake = await startFakeOpenAiCompatibleServer({ apiKey: SWITCH_API_KEY, chatContent: "42", @@ -423,6 +414,29 @@ exit "$status"`, await fake.close(); } }); + progress.phase("verify the Ollama model is active before switching providers"); + const keepAlivePayload = JSON.stringify({ + model, + prompt: "Hello, reply in less than 5 words", + stream: false, + keep_alive: "45m", + options: { num_predict: 16 }, + }); + const activeModelsBeforeSwitch = await host.command( + "bash", + [ + "-lc", + `curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 -H 'Content-Type: application/json' -d ${shellQuote(keepAlivePayload)} http://127.0.0.1:11434/api/generate >/dev/null && ollama ps`, + ], + { + artifactName: "phase-7-ollama-ps-before-provider-switch", + env: env(), + timeoutMs: 150_000, + }, + ); + expect(activeModelsBeforeSwitch.exitCode, resultText(activeModelsBeforeSwitch)).toBe(0); + expect(activeModelsBeforeSwitch.stdout).toContain(model); + progress.phase("switch inference to a non-Ollama provider"); const providerSwitch = await nemoclaw( host, From 857dfdfd85cf56db5feb055aebc3545aa6e83e51 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 01:21:46 -0700 Subject: [PATCH 39/44] docs: clarify Ollama model aliases during manual cleanup Explain default namespace, host, and latest-tag aliases during ownership checks. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 07cc1e85372..12059e307d1 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -426,7 +426,7 @@ Before manually releasing a listed model, verify that no active sandbox on this 2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. 3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= $$nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. 4. After every gateway and sandbox check succeeds and no active sandbox uses the listed model, run `ollama ps` against the host Ollama daemon NemoClaw uses. - Treat a listed model without a tag as its `:latest` variant when comparing with `ollama ps`. + For ownership checks and `ollama ps`, treat an omitted `:latest` tag or default `registry.ollama.ai/library/` prefix as the same model. If a matching model is present, stop only the matching `ollama ps` model and confirm it is absent: ```bash From 237e65f21e8a82d1594449a77963f5814eedbe3e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 01:51:34 -0700 Subject: [PATCH 40/44] docs: distinguish sandbox and host-service Ollama cleanup Clarify the existing host-wide behavior of the two host-service stop commands while keeping sandbox cleanup scoped. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 12059e307d1..b551a7ffeb9 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -404,7 +404,8 @@ Windows-host Ollama does not receive this Linux recovery guidance. ## Release GPU Memory -When you destroy a sandbox or stop host services, NemoClaw asks Ollama to unload only that sandbox's current model and any models recorded for cleanup retry. Other models resident on the shared host daemon are left alone. +When you destroy a sandbox, NemoClaw asks Ollama to unload only that sandbox's current model and any models recorded for cleanup retry. Other models resident on the shared host daemon are left alone. +The host-service commands `nemoclaw stop` and `nemoclaw tunnel stop` run host-wide Ollama cleanup, which may unload unrelated resident models. When you stop a single Ollama-backed sandbox, NemoClaw unloads only that sandbox's own model. It leaves the model loaded only when OpenShell reports that another matching Ollama-backed sandbox is active. Stopped or incomplete sibling registry rows do not retain the model. From 661cdd9d87056db416fd822719aca6a2923c90ab Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 02:07:24 -0700 Subject: [PATCH 41/44] docs: clarify Ollama ownership and manual cleanup State fail-closed destroy ownership, lifecycle-scoped retry records, and the legacy receipt recovery boundary. Keep agent-specific host command names accurate. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index b551a7ffeb9..f2d46b5efbc 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -404,10 +404,10 @@ Windows-host Ollama does not receive this Linux recovery guidance. ## Release GPU Memory -When you destroy a sandbox, NemoClaw asks Ollama to unload only that sandbox's current model and any models recorded for cleanup retry. Other models resident on the shared host daemon are left alone. -The host-service commands `nemoclaw stop` and `nemoclaw tunnel stop` run host-wide Ollama cleanup, which may unload unrelated resident models. +When you destroy a sandbox, NemoClaw asks Ollama to unload its current model and models recorded for lifecycle-scoped cleanup retry, but only after verifying that no other active sandbox uses each model. If ownership cannot be verified, no model is unloaded. Other models resident on the shared host daemon are left alone. Legacy pending cleanup receipts require the manual recovery steps below. +The host-service commands `$$nemoclaw stop` and `$$nemoclaw tunnel stop` run host-wide Ollama cleanup, which may unload unrelated resident models. When you stop a single Ollama-backed sandbox, NemoClaw unloads only that sandbox's own model. -It leaves the model loaded only when OpenShell reports that another matching Ollama-backed sandbox is active. +It keeps the model loaded when OpenShell reports that another active sandbox uses the same local Ollama daemon and model. Stopped or incomplete sibling registry rows do not retain the model. If NemoClaw cannot verify sibling state, it does not unload the model and `stop` exits nonzero. When you re-onboard an Ollama-backed sandbox from the host Ollama route to a different model or provider, NemoClaw checks live ownership before releasing its previous model. @@ -419,7 +419,7 @@ This cleanup is best-effort and does not delete downloaded model files. ### Recover a legacy pending Ollama cleanup -A legacy cleanup receipt may list model names without recording the gateway and sandbox lifecycle that owned them. NemoClaw does not replay or clear those receipts because a reused sandbox name cannot establish ownership. The warning names the receipt's sandbox and each listed model; no model is unloaded automatically. +A legacy cleanup receipt may list model names without recording the gateway and sandbox lifecycle that owned them. NemoClaw does not replay or clear those receipts because a reused sandbox name cannot establish ownership. The warning names the receipt's sandbox and each listed model; the legacy receipt itself never triggers an automatic unload. Before manually releasing a listed model, verify that no active sandbox on this host still uses it: @@ -435,7 +435,7 @@ Before manually releasing a listed model, verify that no active sandbox on this ollama ps ``` - If no matching model appears in `ollama ps`, continue to step 5. + If `ollama ps` fails, keep the receipt and restore host Ollama access. If no matching model appears in a successful `ollama ps` result, continue to step 5. 5. After the ownership checks succeed and every listed model is confirmed absent from `ollama ps`, acknowledge the completed manual recovery by removing only that sandbox's legacy receipt: From 081f92d56e464c0fd23db8aa0fcc935603776fba Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 02:42:10 -0700 Subject: [PATCH 42/44] fix(ollama): keep legacy receipt recovery deferred Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 30 +----------------- .../inference/ollama/model-ownership.test.ts | 31 +------------------ src/lib/inference/ollama/model-ownership.ts | 2 +- 3 files changed, 3 insertions(+), 60 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index f2d46b5efbc..982d7977488 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -404,7 +404,7 @@ Windows-host Ollama does not receive this Linux recovery guidance. ## Release GPU Memory -When you destroy a sandbox, NemoClaw asks Ollama to unload its current model and models recorded for lifecycle-scoped cleanup retry, but only after verifying that no other active sandbox uses each model. If ownership cannot be verified, no model is unloaded. Other models resident on the shared host daemon are left alone. Legacy pending cleanup receipts require the manual recovery steps below. +When you destroy a sandbox, NemoClaw asks Ollama to unload its current model and models recorded for lifecycle-scoped cleanup retry, but only after verifying that no other active sandbox uses each model. If ownership cannot be verified, no model is unloaded. Other models resident on the shared host daemon are left alone. Legacy pending cleanup receipts lack ownership identity and are left untouched. The host-service commands `$$nemoclaw stop` and `$$nemoclaw tunnel stop` run host-wide Ollama cleanup, which may unload unrelated resident models. When you stop a single Ollama-backed sandbox, NemoClaw unloads only that sandbox's own model. It keeps the model loaded when OpenShell reports that another active sandbox uses the same local Ollama daemon and model. @@ -417,34 +417,6 @@ If the new route uses the same model through the same local daemon, NemoClaw kee If the unload cleanup fails, the new route remains active and NemoClaw attempts to record the model for cleanup retry. Rerun onboarding or run `$$nemoclaw destroy` to retry it; if the warning says the retry state could not be recorded, use its reported manual-release guidance instead. This cleanup is best-effort and does not delete downloaded model files. -### Recover a legacy pending Ollama cleanup - -A legacy cleanup receipt may list model names without recording the gateway and sandbox lifecycle that owned them. NemoClaw does not replay or clear those receipts because a reused sandbox name cannot establish ownership. The warning names the receipt's sandbox and each listed model; the legacy receipt itself never triggers an automatic unload. - -Before manually releasing a listed model, verify that no active sandbox on this host still uses it: - -1. Run `openshell gateway list` and identify every NemoClaw gateway on the host. Do not assume the selected gateway is the only one. -2. For each gateway port, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw list --json`. This lists that port's registered sandboxes and any entries recovered from its live gateway; it does not scan other gateway ports. -3. For every sandbox in each inventory, run `NEMOCLAW_GATEWAY_PORT= $$nemoclaw status --json` and `NEMOCLAW_GATEWAY_PORT= $$nemoclaw inference get --json`. Check the live phase and effective provider/model route. A sandbox that is active and uses the same local Ollama daemon and model owns it; do not stop that model. If any gateway, sandbox phase, or route cannot be inspected or is ambiguous, leave the model loaded and restore access or obtain recovery support before retrying. -4. After every gateway and sandbox check succeeds and no active sandbox uses the listed model, run `ollama ps` against the host Ollama daemon NemoClaw uses. - For ownership checks and `ollama ps`, treat an omitted `:latest` tag or default `registry.ollama.ai/library/` prefix as the same model. - If a matching model is present, stop only the matching `ollama ps` model and confirm it is absent: - - ```bash - ollama stop '' - ollama ps - ``` - - If `ollama ps` fails, keep the receipt and restore host Ollama access. If no matching model appears in a successful `ollama ps` result, continue to step 5. - -5. After the ownership checks succeed and every listed model is confirmed absent from `ollama ps`, acknowledge the completed manual recovery by removing only that sandbox's legacy receipt: - - ```bash - rm -- "$HOME/.nemoclaw/ollama-pending-model-cleanup/.json" - ``` - - Replace `` with the exact sandbox name printed in the warning. This only retires the obsolete warning receipt; it does not trigger cleanup. If any ownership check is incomplete or a listed model remains active, keep the receipt and do not stop a model owned by an active sandbox. Do not delete or edit the receipt to force an automatic retry. - ## Related Topics - [Choose a Local Inference Server](choose-local-inference-server) to compare local options. diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 39faf8b2031..f4475a720dd 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -436,13 +436,8 @@ describe("pending Ollama model cleanup", () => { ), ); expect(warning).toHaveBeenCalledWith( - expect.stringContaining("no active sandbox on any gateway"), + expect.stringContaining("model names do not establish ownership"), ); - expect(warning).toHaveBeenCalledWith( - expect.stringContaining("Recover a legacy pending Ollama cleanup"), - ); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("ollama stop ")); - expect(warning).toHaveBeenCalledWith(expect.stringContaining("ollama ps")); expect(warning).toHaveBeenCalledWith(expect.stringContaining("NemoClaw left it untouched")); clearPendingOllamaModelCleanup(owner, undefined, stateRoot); @@ -453,30 +448,6 @@ describe("pending Ollama model cleanup", () => { } }); - it("stops warning after a legacy receipt is manually retired following recovery", () => { - const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); - const owner = cleanupOwner(); - const legacyPath = join(stateRoot, "ollama-pending-model-cleanup", `${owner.name}.json`); - mkdirSync(join(stateRoot, "ollama-pending-model-cleanup"), { recursive: true, mode: 0o700 }); - writeFileSync( - legacyPath, - JSON.stringify({ schemaVersion: 1, sandboxName: owner.name, models: ["llama3"] }), - { mode: 0o600 }, - ); - const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); - try { - // The operator removes this receipt only after the documented cross-gateway - // ownership checks and manual Ollama release have succeeded. - rmSync(legacyPath); - - expect(loadPendingOllamaModelCleanup(owner, stateRoot)).toEqual([]); - expect(warning).not.toHaveBeenCalled(); - } finally { - warning.mockRestore(); - rmSync(stateRoot, { recursive: true, force: true }); - } - }); - it("fails closed when cleanup receipt lifecycle identity is incomplete", () => { const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); const owner = cleanupOwner(); diff --git a/src/lib/inference/ollama/model-ownership.ts b/src/lib/inference/ollama/model-ownership.ts index 97cf0a068fe..845433cb929 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -144,7 +144,7 @@ export function loadPendingOllamaModelCleanup( : []; if (legacyModels.length > 0) { console.warn( - ` Warning: legacy pending Ollama cleanup for '${owner.name}' lists ${legacyModels.join(", ")} but has no gateway/lifecycle identity. NemoClaw left it untouched. Verify no active sandbox on any gateway uses a listed model before release; see "Recover a legacy pending Ollama cleanup" in the Set Up Ollama guide for the ownership checks, 'ollama stop ', and 'ollama ps' verification.`, + ` Warning: legacy pending Ollama cleanup for '${owner.name}' lists ${legacyModels.join(", ")} but has no gateway/lifecycle identity. NemoClaw left it untouched because these model names do not establish ownership.`, ); } if (!identity) return []; From c42c6eae64ac2b5fd7771a0c2f45a9fb5b93958d Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 03:17:21 -0700 Subject: [PATCH 43/44] docs(ollama): correct recovery and E2E contract wording Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 2 +- test/e2e/live/gpu-double-onboard.test.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index 982d7977488..baa6ea5018b 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -412,7 +412,7 @@ Stopped or incomplete sibling registry rows do not retain the model. If NemoClaw cannot verify sibling state, it does not unload the model and `stop` exits nonzero. When you re-onboard an Ollama-backed sandbox from the host Ollama route to a different model or provider, NemoClaw checks live ownership before releasing its previous model. If another active sandbox uses the same local Ollama model, NemoClaw keeps it loaded. -If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model loaded and attempts to record cleanup for retry while leaving the new route active. If it reports that retry state could not be recorded, keep the model loaded and restore gateway access before retrying; do not unload it while ownership remains unverified. +If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model loaded and attempts to record cleanup for retry while leaving the new route active. If it reports that retry state could not be recorded, keep the model loaded until you manually verify that no active matching sandbox owns it, then release only the named model from the local Ollama host. If the new route uses the same model through the same local daemon, NemoClaw keeps the model loaded. If the unload cleanup fails, the new route remains active and NemoClaw attempts to record the model for cleanup retry. Rerun onboarding or run `$$nemoclaw destroy` to retry it; if the warning says the retry state could not be recorded, use its reported manual-release guidance instead. This cleanup is best-effort and does not delete downloaded model files. diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 2f6d654f29d..eecd77899ac 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -206,7 +206,6 @@ test( contracts: [ "GPU and runtime prerequisites are present", "install.sh onboards with the Ollama provider", - "sandbox inference.local reaches Ollama after first onboard", "nemoclaw onboard --non-interactive --yes recreates the sandbox", "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", "the sandbox-owned native provider reaches Ollama after first onboard and re-onboard", From 4e5ed96c7b70436d64c4dab682e137b1099a9495 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Wed, 28 Oct 2026 03:45:38 -0700 Subject: [PATCH 44/44] docs(ollama): name every model in cleanup guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/set-up-ollama.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/inference/set-up-ollama.mdx b/docs/inference/set-up-ollama.mdx index baa6ea5018b..03172261893 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -412,7 +412,7 @@ Stopped or incomplete sibling registry rows do not retain the model. If NemoClaw cannot verify sibling state, it does not unload the model and `stop` exits nonzero. When you re-onboard an Ollama-backed sandbox from the host Ollama route to a different model or provider, NemoClaw checks live ownership before releasing its previous model. If another active sandbox uses the same local Ollama model, NemoClaw keeps it loaded. -If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model loaded and attempts to record cleanup for retry while leaving the new route active. If it reports that retry state could not be recorded, keep the model loaded until you manually verify that no active matching sandbox owns it, then release only the named model from the local Ollama host. +If NemoClaw cannot verify whether another sandbox uses the model, it keeps the model loaded and attempts to record cleanup for retry while leaving the new route active. When NemoClaw reports that retry state could not be recorded, keep every listed model loaded until you manually verify that no active matching sandbox owns each one, then release only the listed models from the local Ollama host. If the new route uses the same model through the same local daemon, NemoClaw keeps the model loaded. If the unload cleanup fails, the new route remains active and NemoClaw attempts to record the model for cleanup retry. Rerun onboarding or run `$$nemoclaw destroy` to retry it; if the warning says the retry state could not be recorded, use its reported manual-release guidance instead. This cleanup is best-effort and does not delete downloaded model files.