diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 30a2dfb0725..c7ba3828d00 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 12b01e047b4..03172261893 100644 --- a/docs/inference/set-up-ollama.mdx +++ b/docs/inference/set-up-ollama.mdx @@ -404,14 +404,18 @@ 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, 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 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 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 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. ## Related Topics diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b3a3a02f119..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. 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. If `OPENSHELL_GATEWAY_ENDPOINT` is set, `destroy` refuses to probe or delete the sandbox; unset the variable and retry. 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. 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 67c2dea4279..aa649074bf1 100644 --- a/src/lib/actions/sandbox/destroy-cross-root.test.ts +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { + configureSiblingSandboxAfterDelete, createDestroyHarness, resetDestroyModuleCache, } from "../../../../test/helpers/destroy-flow-test-harness"; @@ -96,7 +97,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: "", + }, + }); + configureSiblingSandboxAfterDelete(harness, "beta", ["alpha"]); await expect( harness.destroySandbox("beta", { yes: true, cleanupGateway: true }), @@ -120,7 +128,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: "", + }, + }); + configureSiblingSandboxAfterDelete(harness, "beta", ["alpha"]); harness.withGatewayRouteMutationLockSpy .mockImplementationOnce(async (_gatewayName: unknown, operation: unknown) => (operation as () => Promise)(), @@ -232,7 +247,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 }), @@ -243,6 +264,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(); }); }); diff --git a/src/lib/actions/sandbox/destroy.test.ts b/src/lib/actions/sandbox/destroy.test.ts index 2eebeb64688..3316af77692 100644 --- a/src/lib/actions/sandbox/destroy.test.ts +++ b/src/lib/actions/sandbox/destroy.test.ts @@ -1,12 +1,21 @@ // 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 { 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"; +import { + createDestroyHarness, + resetDestroyModuleCache, +} from "../../../../test/helpers/destroy-flow-test-harness"; + +afterEach(() => vi.restoreAllMocks()); const SANDBOX = "mybox"; const mainPidDir = path.resolve("/tmp", `nemoclaw-services-${SANDBOX}`); @@ -21,7 +30,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 +130,365 @@ 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, + 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 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, + { 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(captureSandboxOwnershipPhases).toHaveBeenCalledWith("gateway-b", process.env); + expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(clearPendingOllamaModelCleanup).not.toHaveBeenCalled(); + }); + + it("fails closed when shared phase capture reports 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 captureSandboxOwnershipPhases = vi + .spyOn(openshellRuntime, "captureSandboxPhasesForGateway") + .mockReturnValue({ status: 1, output: "gateway unreachable" }); + const runOpenshell = vi.fn(() => ({ status: 0 })); + + 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(captureSandboxOwnershipPhases).toHaveBeenCalledWith("gateway-b", process.env); + 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 +508,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, @@ -308,3 +680,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/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 9f2e84ede62..2c0cc5f9072 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"; @@ -27,11 +28,14 @@ import { readPendingHostLocalVllmRetirement, } from "../../inference/local-model-profile/cleanup"; import { + discoverOllamaModelOwnership, isLocalOllamaRouteOwner, loadPersistedOllamaHost, + matchingOllamaModelPeers, type OllamaUnloadResult, withOllamaModelOwnershipTransaction, } from "../../inference/ollama/proxy"; +import type { OllamaModelCleanupOwner } from "../../inference/ollama/model-ownership"; import { CURRENT_RUNTIME_PROVIDER_BUNDLES, normalizeRuntimeProviderIdentity, @@ -223,11 +227,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; @@ -240,13 +250,22 @@ 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; 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; @@ -311,10 +330,12 @@ export async function cleanupSandboxServices( stopHostServices = false, channelStopTransport, gatewayPort, + sandboxSnapshot, }: { stopHostServices?: boolean; channelStopTransport?: RuntimeProviderChannelStopTransport; gatewayPort?: number; + sandboxSnapshot?: registry.SandboxEntry | null; } = {}, deps: CleanupSandboxServicesDeps = {}, ): Promise { @@ -327,7 +348,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: { @@ -358,19 +378,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 ?? @@ -458,25 +481,83 @@ export async function cleanupSandboxServices( } let ollamaCleanup: OllamaUnloadResult | void = undefined; + const cleanupScopedOllamaModels = () => { + const sb = sandboxSnapshot !== undefined ? sandboxSnapshot : getSandbox(validatedSandboxName); + const selectedHost = loadPersistedOllamaHost(); + const pending = sb ? loadPendingOllamaModelCleanup(sb) : []; + 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 ?? captureSandboxPhasesForGateway; + 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 peersByModel = candidates.map((model) => { + const holder = { + name: validatedSandboxName, + gatewayName: sb?.gatewayName ?? null, + gatewayPort: sb?.gatewayPort ?? gatewayPort ?? null, + provider: "ollama-local", + model, + endpointUrl: null, + }; + 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.", + ); + } + 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)); + if (activePeers.length === 0) releasable.push(model); + } + if (releasable.length === 0) return; + ollamaCleanup = unloadOllamaModels(releasable); + if ((!ollamaCleanup || ollamaCleanup.ok) && sb) { + clearPendingOllamaModelCleanup(sb, 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)) @@ -491,35 +572,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 = @@ -1266,33 +1319,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, - ...(destroyChannelStopTransport - ? { channelStopTransport: destroyChannelStopTransport } - : {}), - }, - { - getSandbox: getRegisteredSandbox, - listSandboxes: listRegisteredSandboxes, - 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/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index bb8fae3df46..5b2428df7b3 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -211,30 +211,15 @@ 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: SandboxEntry): string { +export function resolvePersistedSandboxOwnershipGateway( + sandbox: Pick, +): string { 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/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index ee9b381287b..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,20 +246,16 @@ 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"]), + activePeers: new Set([activePeer, transientPeer]), gatewayChecks: [ { activeSandboxes: ["active-peer", "transient-peer"], @@ -270,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/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/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts index 675f8fd06b7..e1e47f6a3b6 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,90 @@ 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 }); + } + }); + + 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", () => { 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 df2ef3e45dc..92542cfac79 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -15,7 +15,12 @@ import { runOpenshellCommand, } from "./command-execution"; import { cliOpenShellInstalledVersionObserver } from "./installed-version-cli"; -import { buildOpenShellSubprocessEnv, resolveOpenshellBinaryOrNull } from "./resolve-shared"; +import { assertNoOpenShellGatewayEndpointOverride } from "./gateway-scope"; +import { + buildOpenShellDiagnosticEnvironment, + buildOpenShellSubprocessEnv, + resolveOpenshellBinaryOrNull, +} from "./resolve-shared"; type CommandArgs = string[]; @@ -33,6 +38,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 = { @@ -110,6 +120,25 @@ 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 } { + // captureOpenshell also inherits ambient variables when it builds the child environment. + assertNoOpenShellGatewayEndpointOverride(); + assertNoOpenShellGatewayEndpointOverride(environment); + const result = captureOpenshell(["sandbox", "list", "-g", gatewayName], { + env: buildOpenShellDiagnosticEnvironment(environment), + replaceEnv: true, + 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(); diff --git a/src/lib/inference/ollama/model-ownership.test.ts b/src/lib/inference/ollama/model-ownership.test.ts index 557df044639..f4475a720dd 100644 --- a/src/lib/inference/ollama/model-ownership.test.ts +++ b/src/lib/inference/ollama/model-ownership.test.ts @@ -1,20 +1,22 @@ // 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, decideOllamaModelOwnership, - exclusivelyHeldOllamaModel, + discoverOllamaModelOwnership, loadPendingOllamaModelCleanup, + type OllamaHostRoute, + type OllamaModelCleanupOwner, type OllamaModelHolder, type OllamaModelRoute, persistPendingOllamaModelCleanup, - supersededOllamaModel, + supersededOllamaModelWithActivePeers, } from "./model-ownership"; import { isLocalOllamaRouteOwner } from "./model-ownership"; @@ -22,10 +24,38 @@ 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 }; } +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", @@ -57,9 +87,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([ @@ -68,72 +99,195 @@ 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 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(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( + releaseCandidate(previous, route("qwen2.5:1.5b"), [previous, activePeer], [activePeer]), + ).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(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(releaseCandidate(previous, route("qwen2.5:1.5b"), [peer], [peer])).toBeNull(); + }); + + it("preserves an active model selected through the same local daemon", () => { + const previous = holder(); + expect(releaseCandidate(previous, route("llama3:latest"), [previous])).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"] }); + }); + + 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", () => { it("returns the exclusive model and names stopped matching registry rows (#10074)", () => { const stoppedPeer = holder({ name: "stopped-peer" }); @@ -210,35 +364,113 @@ 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 models until verified release for the exact sandbox lifecycle", () => { + const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-pending-ollama-cleanup-")); + const owner = cleanupOwner(); + try { + 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 }); + } }); -}); -describe("pending Ollama model cleanup", () => { - it("persists exact sandbox-scoped models until verified release", () => { + 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("test-box", ["llama3", "llama3:latest"], stateRoot); - persistPendingOllamaModelCleanup("test-box", ["qwen3.5:9b"], stateRoot); + 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"]); - expect(loadPendingOllamaModelCleanup("test-box", stateRoot)).toEqual([ - "llama3", - "qwen3.5:9b", + 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( + "legacy pending Ollama cleanup for 'test-box' lists llama3 but has no gateway/lifecycle identity", + ), + ); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("model names do not establish ownership"), + ); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("NemoClaw left it untouched")); + + 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 84a3d69e5f6..845433cb929 100644 --- a/src/lib/inference/ollama/model-ownership.ts +++ b/src/lib/inference/ollama/model-ownership.ts @@ -1,9 +1,12 @@ // 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"; import type { SandboxEntry } from "../../state/registry"; +import { parseLiveSandboxEntries } from "../../runtime-recovery"; import { isLocalOllamaRouteOwner, readLocalAdapterJsonFile, @@ -19,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`); } @@ -37,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}' lists ${legacyModels.join(", ")} but has no gateway/lifecycle identity. NemoClaw left it untouched because these model names do not establish ownership.`, + ); + } + 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; @@ -61,42 +181,76 @@ 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; - 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" } | { @@ -114,11 +268,16 @@ 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. + * 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(); +} + export function matchingOllamaModelPeers( sandbox: OllamaModelHolder, peers: readonly T[], @@ -126,13 +285,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 +319,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,18 +345,83 @@ 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 exclusivelyHeldOllamaModel( - sandbox: OllamaModelHolder, +export function discoverOllamaModelOwnership( 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; + 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) { + 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") { + 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 }; } /** @@ -189,18 +436,27 @@ 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 supersededOllamaModel( +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; - const held = exclusivelyHeldOllamaModel(previous, peers, selectedHost); - if (!held) return null; - return isLocalOllamaRouteOwner(next, selectedHost) && ollamaModelRefsMatch(held, nextModel) + return isLocalOllamaRouteOwner(next, selectedHost) && + ollamaModelRefsMatch(ownership.model, nextModel) ? null - : held; + : ownership.model; } diff --git a/src/lib/inference/ollama/proxy.test.ts b/src/lib/inference/ollama/proxy.test.ts index 77e37995335..ee929972680 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,77 @@ 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]; + 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; + homedir.mockRestore(); + fs.rmSync(isolatedHome, { recursive: true, force: true }); + } + }, 15_000); +}); + 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 b22431e9809..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, @@ -134,12 +136,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 { @@ -1833,6 +1839,7 @@ export { buildOllamaAuthProxySpawnEnv, checkOllamaModelToolSupport, clearPendingOllamaModelCleanup, + discoverOllamaModelOwnership, ensureOllamaAuthProxy, getOllamaProxyToken, getOllamaPullTimeoutMs, @@ -1842,6 +1849,7 @@ export { killStaleProxyIfUnused, loadPendingOllamaModelCleanup, loadPersistedOllamaHost, + matchingOllamaModelPeers, noAuthProxy, ollamaModelRefsMatch, persistAndProbeOllamaProxy, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index d368b18c70b..e7b1da8b0df 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, @@ -2368,7 +2369,6 @@ const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxC promptOrDefault, }), }); - const stageSandboxCredentialProviders = ( input: import("./onboard/credential-provider-registration").StageSandboxCredentialProvidersInput, ) => diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index d654d69c62b..9ca6f17a050 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"; /** Process-local replacement prepared while the published legacy source stays intact. */ @@ -296,9 +297,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-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 0967327c988..cff449faf67 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -5,6 +5,7 @@ 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 { OllamaModelHolder } from "../inference/ollama/model-ownership"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { createProviderReviewDeps, @@ -18,6 +19,17 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); +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), +}; + describe("recorded Pi local inference route", () => { it("rejects a changed selection before invoking a provider or gateway", async () => { const getSandbox = vi.fn(() => ({ @@ -345,7 +357,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); @@ -360,7 +387,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, @@ -432,6 +480,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", @@ -737,3 +789,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 e97a726d3ee..040b589808b 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -60,11 +60,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, @@ -76,9 +81,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"; @@ -275,6 +281,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; @@ -557,7 +568,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, @@ -582,7 +593,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)) @@ -593,38 +604,95 @@ 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) { 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) { @@ -652,7 +720,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(); @@ -667,9 +735,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) { @@ -2071,24 +2159,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/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/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 c8f73b859b9..ad936e4431c 100644 --- a/src/lib/tunnel/services.test.ts +++ b/src/lib/tunnel/services.test.ts @@ -1283,28 +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 logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - stopAll({ - pidDir, - sandboxName: "test-box", - unloadOllamaModels: cleanup, - clearPendingOllamaModelCleanup, - }); - 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(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/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 786ee92beea..eecd77899ac 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -13,10 +13,11 @@ 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 { 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"; @@ -24,6 +25,8 @@ import type { ShellProbeResult } from "../fixtures/shell-probe.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); @@ -52,10 +55,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 +126,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,36 +139,40 @@ 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( - SANDBOX_NAME, - [ - "sh", - "-lc", - `${nativeLocalChatCommand(endpoint, chatRequest(model), "-fsS")} | ${parseReplyCommand()}`, - ], - { - artifactName, - env: env(), - timeoutMs: 150_000, - }, - ); + 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, + }); +} + +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 +183,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", ], }, @@ -198,10 +206,12 @@ 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", "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 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", ], }); @@ -339,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"); @@ -367,19 +364,11 @@ 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); + 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`, @@ -406,6 +395,98 @@ exit "$status"`, await expectSandboxInference42(sandbox, model, "phase-6-sandbox-inference-after-reonboard"); + const fake = await startFakeOpenAiCompatibleServer({ + apiKey: SWITCH_API_KEY, + chatContent: "42", + host: "0.0.0.0", + model: SWITCH_MODEL, + port: 8000, + progress, + publicHost: "host.openshell.internal", + 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(); + } + }); + 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, + ["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", + NEMOCLAW_RECREATE_SANDBOX: "0", + }, + execTimeout(30 * 60_000), + [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, + 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, + ); + 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(), + 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 +499,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 e640fe09653..057f4e1d15e 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -623,10 +623,16 @@ "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/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 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] >([ diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index b51ff8fc2ca..16bd5653b48 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -672,7 +672,7 @@ describe("E2E workflow plan", () => { }); }); - it("routes homogeneous GPU targets through the standard workflow matrix", () => { + 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(",") }); @@ -680,6 +680,7 @@ describe("E2E workflow plan", () => { expect(plan.catalogueMatrices.standard).toEqual( targetIds.map((id) => expect.objectContaining({ id, runner: expectedRunner })), ); + expect(plan.catalogueMatrices["nvidia-api"]).toEqual([]); expect(plan.catalogueMatrices.standard.find((row) => row.id === "gpu-e2e")).not.toHaveProperty( "selector", ); diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 1497578b0ca..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[], @@ -573,6 +597,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 ?? ""}`.trim(), + }; + }); const captureOpenshellSpy = vi.spyOn(runtime, "captureOpenshell").mockReturnValue({ status: 0, output: options.liveListOutput ?? "", diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 41b6630936b..62d7c3f66be 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, @@ -288,4 +289,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); }); diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index f05c9e41aec..bf990e810df 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"; @@ -1092,10 +1093,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; }) { @@ -1112,11 +1116,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 }), @@ -1169,7 +1170,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 }); @@ -1275,7 +1276,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([]); }); @@ -1403,9 +1407,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/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts index 475fe979c25..0546b1b2996 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,8 @@ 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 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; @@ -20,7 +20,6 @@ type StopAllOptions = { sandboxName: string; cleanupOllamaModels?: boolean; stopCloudflared?: boolean; - unloadOllamaModels?: () => OllamaUnloadResult | void; }; function buildDeps( @@ -31,7 +30,8 @@ function buildDeps( Pick< CleanupSandboxServicesDeps, | "getSandbox" - | "listSandboxes" + | "listOllamaModelOwnershipPeers" + | "discoverOllamaModelOwnership" | "stopAll" | "migrateLegacyCloudflaredState" | "unloadOllamaModels" @@ -63,13 +63,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 +90,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 +101,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 +110,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 +128,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 +142,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(); @@ -183,6 +182,28 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { 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" }, @@ -210,9 +231,10 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { 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 () => { 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"); }, ); 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 ba84c7160ee..4e285f49552 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -811,9 +811,9 @@ 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", + environmentOrInferenceEndpoint: "NVIDIA GPU runner; local Ollama and compatible endpoint", profile: "standard", runner: "linux-amd64-gpu-rtxpro6000-latest-1", podmanHostPackages: NATIVE_PODMAN_HOST_PACKAGES, @@ -821,7 +821,11 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ 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",