diff --git a/.github/workflows/e2e-standard-profile.yaml b/.github/workflows/e2e-standard-profile.yaml index 66294145683..97eac75e49c 100644 --- a/.github/workflows/e2e-standard-profile.yaml +++ b/.github/workflows/e2e-standard-profile.yaml @@ -508,6 +508,25 @@ jobs: -u NVIDIA_API_KEY -u NVIDIA_INFERENCE_API_KEY -u BRAVE_API_KEY -u GITHUB_TOKEN \ -u COMPATIBLE_API_KEY bash scripts/install-openshell.sh + - name: Prepare GPU launch-readiness runtime directory + id: gpu_runtime_directory + if: ${{ inputs.catalogue_id == 'gpu-e2e' && inputs.runtime_provider == 'docker' }} + shell: /bin/bash --noprofile --norc -e -o pipefail {0} + run: | + set -euo pipefail + uid="$(/usr/bin/id -u)" + unit="user@${uid}.service" + prior_state="$(/usr/bin/systemctl show "$unit" --property=ActiveState --value)" + if [[ "$prior_state" != "active" ]]; then + [[ "$prior_state" == "inactive" ]] + printf 'started=true\n' >> "$GITHUB_OUTPUT" + /usr/bin/sudo -n /usr/bin/systemctl start "$unit" + fi + /usr/bin/systemctl is-active --quiet "$unit" + runtime_directory="/run/user/$uid" + [[ -d "$runtime_directory" && ! -L "$runtime_directory" ]] + [[ "$(/usr/bin/stat -c '%u:%a' "$runtime_directory")" == "${uid}:700" ]] + - name: Run catalogue E2E target env: INSTALL_MODE: ${{ inputs.install_mode }} @@ -635,6 +654,14 @@ jobs: with: enabled: "true" + - name: Restore GPU launch-readiness runtime directory + if: ${{ always() && inputs.catalogue_id == 'gpu-e2e' && inputs.runtime_provider == 'docker' && steps.gpu_runtime_directory.outputs.started == 'true' }} + shell: /bin/bash --noprofile --norc -e -o pipefail {0} + run: | + set -euo pipefail + uid="$(/usr/bin/id -u)" + /usr/bin/sudo -n /usr/bin/systemctl stop "user@${uid}.service" + - name: Clean up Docker auth if: always() shell: bash diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 7550a03edf9..8389e456d1a 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -4878,50 +4878,43 @@ jobs: - id: runtime-bases name: Resolve digest-pinned amd64 runtime base images env: + CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} DCODE_BASE_REF: ${{ needs.base-image-publication.outputs.dcode_base_ref }} + HERMES_BASE_REF: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }} shell: bash run: | set -euo pipefail work_dir="$(mktemp -d "${RUNNER_TEMP}/nemoclaw-runtime-bases.XXXXXX")" trap 'rm -rf -- "$work_dir"' EXIT - resolve_base() { - local output_name="$1" - local alias="$2" - local repository="$3" - local alias_raw="$work_dir/${output_name}-alias.raw" - local exact_raw="$work_dir/${output_name}-exact.raw" - docker buildx imagetools inspect "$alias" --raw > "$alias_raw" - local digest - digest="$( - jq -er ' - if ( - .mediaType == "application/vnd.oci.image.index.v1+json" or - .mediaType == "application/vnd.docker.distribution.manifest.list.v2+json" - ) then - [.manifests[] | select(.platform.os == "linux" and .platform.architecture == "amd64")] - | if length == 1 then .[0].digest else error("not one exact amd64 descriptor") end - else - error("base alias is not a platform index") - end - ' "$alias_raw" - )" - [[ "$digest" =~ ^sha256:[a-f0-9]{64}$ ]] || { - echo "::error::${output_name} base alias returned an invalid digest" >&2 - exit 1 - } - local reference="${repository}@${digest}" - docker buildx imagetools inspect "$reference" --raw > "$exact_raw" - [[ "sha256:$(sha256sum "$exact_raw" | awk '{print $1}')" == "$digest" ]] || { - echo "::error::${output_name} exact base bytes do not match the selected digest" >&2 - exit 1 - } - printf '%s=%s\n' "$output_name" "$reference" >> "$GITHUB_OUTPUT" + # The mutable base alias can move after the startup job prepared this cache. + # Reuse that job's exact OpenClaw base and preserve the other identity checks. + prepared_inputs="$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/prepared-inputs" + [[ -f "$prepared_inputs" && ! -L "$prepared_inputs" ]] || { + echo "::error::protected build cache has no safe prepared-input identity" >&2 + exit 1 } - - resolve_base openclaw \ - ghcr.io/nvidia/nemoclaw/sandbox-base:latest \ - ghcr.io/nvidia/nemoclaw/sandbox-base + read -r cached_revision cached_platform cached_openclaw cached_hermes cached_dcode extra < "$prepared_inputs" + [[ -z "$extra" && + "$cached_revision" == "$CHECKOUT_SHA" && + "$cached_platform" == "linux/amd64" && + "$cached_hermes" == "$HERMES_BASE_REF" && + "$cached_dcode" == "$DCODE_BASE_REF" && + "$(cat "$prepared_inputs")" == "$cached_revision $cached_platform $cached_openclaw $cached_hermes $cached_dcode" ]] || { + echo "::error::protected build-cache identity does not match this run" >&2 + exit 1 + } + [[ "$cached_openclaw" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]] || { + echo "::error::prepared OpenClaw base is not an exact approved image reference" >&2 + exit 1 + } + openclaw_digest="${cached_openclaw##*@}" + docker buildx imagetools inspect "$cached_openclaw" --raw > "$work_dir/openclaw-exact.raw" + [[ "sha256:$(sha256sum "$work_dir/openclaw-exact.raw" | awk '{print $1}')" == "$openclaw_digest" ]] || { + echo "::error::OpenClaw exact base bytes do not match the prepared digest" >&2 + exit 1 + } + printf 'openclaw=%s\n' "$cached_openclaw" >> "$GITHUB_OUTPUT" [[ "$DCODE_BASE_REF" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || { echo "::error::dcode base publication returned an invalid exact reference" >&2 exit 1 diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 5f4490e6763..af77410a72b 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,25 +15,25 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1278, - "matcherAssertions": 1257, + "expectCalls": 1275, + "matcherAssertions": 1254, "nodeAssertions": 104, "namedAssertionHelpers": 436, "failCalls": 0, "throwGuards": 60, - "objectFieldAssertions": 163, + "objectFieldAssertions": 166, "assertionPoints": 2020, "generatedProbeBlocks": 91, "generatedProbeConditions": 221 }, "unique": { - "expectCalls": 1703, - "matcherAssertions": 1677, + "expectCalls": 1700, + "matcherAssertions": 1674, "nodeAssertions": 127, "namedAssertionHelpers": 681, "failCalls": 1, "throwGuards": 540, - "objectFieldAssertions": 240, + "objectFieldAssertions": 243, "assertionPoints": 3266, "generatedProbeBlocks": 213, "generatedProbeConditions": 726 @@ -63,7 +63,7 @@ "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,31,28,61,7], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], - "test/e2e/live/gpu-e2e.test.ts": [39,44,72,90,3], + "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 225aaed4eba..f40fc26e70b 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -30,7 +30,7 @@ "src/lib/runner.ts": 80, "src/lib/sandbox-name-contract.ts": 20, "src/lib/security/redact.ts": 50, - "src/lib/state/mcp-lifecycle-lock.ts": 20, + "src/lib/state/mcp-lifecycle-lock.ts": 19, "src/lib/state/onboard-session.ts": 35, "src/lib/state/registry.ts": 87, "src/lib/state/state-root.ts": 21, diff --git a/docs/inference/set-up-vllm.mdx b/docs/inference/set-up-vllm.mdx index b69581e9b0f..acf359a429b 100644 --- a/docs/inference/set-up-vllm.mdx +++ b/docs/inference/set-up-vllm.mdx @@ -21,6 +21,11 @@ The vLLM `/v1/responses` endpoint does not run the configured tool-call parser, Local vLLM does not require authentication by default. Existing-server and single-host managed-vLLM paths use `NEMOCLAW_VLLM_PORT`, which defaults to `8000`, on host loopback for validation and on the OpenShell Docker bridge for sandbox traffic. +After onboarding, `status` and `doctor` probe an authenticated managed single-host vLLM container on its published loopback port. +For a bearerless server, they use the port in the sandbox's recorded `http://host.openshell.internal:/v1` route. +When that route is valid, no later port environment override is required. +For vLLM, `connect` runs these host probes only when it repairs the route. +A missing or invalid recorded route makes a bearerless probe fall back to `NEMOCLAW_VLLM_PORT`, which defaults to `8000`. Use a host firewall with default-deny inbound rules. Allow the configured TCP port only from the OpenShell Docker subnet to its gateway address, keep loopback access, and deny the port on every other interface. Do not expose the port to your LAN or the internet. @@ -152,7 +157,13 @@ $$nemoclaw onboard --profile --vllm-gpu-device #### Handle a Running vLLM Server The single-host managed vLLM runtime is host-global. -Destroying a sandbox does not stop it, and the container remains available for other sandboxes. +`$$nemoclaw destroy` keeps the container while any registered sandbox in any gateway state root reports provider `vllm-local`. +Local NIM uses the same provider identifier and counts as a possible consumer. +After the last such sandbox is destroyed, an eligible `destroy` removes the verified NemoClaw-managed container and frees its GPU memory. +When ownership or Docker state cannot be verified, NemoClaw retains recovery state and reports the reason instead of claiming completed retirement. +Resolve the cause, then rerun the same `destroy` command. +Pass `--keep-vllm` or set `NEMOCLAW_KEEP_VLLM=1` to preserve the container for a later sandbox. +Refer to [CLI Commands](../../reference/commands) for the cleanup conditions. Later standard onboarding normally reuses a server that is already listening on the configured vLLM port instead of replacing it automatically. When a managed GPU selection accompanies explicit managed-install intent, NemoClaw preserves that intent and reports the running-server conflict. @@ -189,7 +200,7 @@ Choose one action: ``` Accept the result when onboarding completes and `$$nemoclaw list` reports the new sandbox with provider `vllm-local` and the expected model. -NemoClaw does not stop or recreate a running vLLM server automatically because another sandbox can use it. +Onboarding does not stop or recreate a running vLLM server automatically because another sandbox can use it. NemoClaw requires a resumed session to reuse the recorded GPU selector. A legacy in-progress session cannot add one, and a resumed session cannot change one. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 46ccd722d57..91ba3d9d0f7 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2000,7 +2000,33 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` ### `$$nemoclaw destroy` -Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. This removes the sandbox from the registry. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. For Ollama-backed sandboxes, `destroy` also asks Ollama to unload currently loaded models and clears stale auth proxy state on a best-effort basis. For Model Router sandboxes, `destroy` keeps the process and recovery identity when another sandbox uses the port or when session, process, or absence checks are inconclusive. It also preserves a replacement onboarding session when the captured session identity changed. If the captured session uses the destroyed sandbox name with another router port, `destroy` clears only the sandbox association and preserves that router's recovery identity. For lock order, same-port peer handling, and cleanup checks, refer to [Set Up Model Router](../inference/hosted-inference/set-up-model-router#router-and-sandbox-lifecycle-locks). +Stop managed local inference resources, remove runtime-provider-owned resources created during onboarding, and delete the sandbox. This removes the sandbox from the registry. NemoClaw resolves the registry that owns the sandbox before it starts cleanup, even when another local OpenShell gateway is active. For Ollama-backed sandboxes, `destroy` also asks Ollama to unload currently loaded models and clears stale auth proxy state on a best-effort basis. + +`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. +Sandboxes with a runtime-provider host-local inference receipt use that provider's cleanup instead. +`destroy` removes a verified NemoClaw-managed container by its inspected ID and frees any GPU memory it held. +Pass `--keep-vllm` or set `NEMOCLAW_KEEP_VLLM=1` to preserve the container for a later sandbox. + +`destroy` does not claim that retirement completed when: + +- Another registered sandbox uses provider `vllm-local`. +- The container lacks the NemoClaw managed label. +- The container carries distributed vLLM labels but has no matching ownership receipt. +- An authenticated container does not match its persisted API key and receipt. +- A distributed vLLM receipt owns the container. +- NemoClaw cannot read every gateway sandbox registry. +- Docker is unavailable or cannot confirm whether the container exists. +- Container removal or private-state cleanup fails. + +Before eligible registry removal, `destroy` writes the sandbox name to `~/.nemoclaw/host-local-vllm-pending-retirement.json`. +This record supports a same-name retry after the registry entry is gone. +If the write fails and no matching record can be read, `destroy` preserves the registry entry and exits with an error. +Unfinished retirement retains the pending record. +Resolve the reported cause, then rerun the same `destroy` command to finish cleanup. +A completed retirement or a decision to keep the container for a consumer, preservation option, or distributed owner clears the record. + +For Model Router sandboxes, `destroy` keeps the process and recovery identity when another sandbox uses the port or when session, process, or absence checks are inconclusive. It also preserves a replacement onboarding session when the captured session identity changed. If the captured session uses the destroyed sandbox name with another router port, `destroy` clears only the sandbox association and preserves that router's recovery identity. For lock order, same-port peer handling, and cleanup checks, refer to [Set Up Model Router](../inference/hosted-inference/set-up-model-router#router-and-sandbox-lifecycle-locks). If `destroy` warns that it could not identify or stop a listener for the deleted sandbox: @@ -2104,7 +2130,7 @@ Retry after the recorded gateway is available. An MCP source that cannot be safely inspected disables the local-only fallback. ```bash -$$nemoclaw my-assistant destroy [--yes|-y|--force] [--cleanup-gateway|--no-cleanup-gateway] +$$nemoclaw my-assistant destroy [--yes|-y|--force] [--cleanup-gateway|--no-cleanup-gateway] [--keep-vllm] ``` After OpenShell confirms deletion of a sandbox that owns managed llama.cpp, `destroy` revalidates the exact container, internal network, lifecycle journal, and gateway-scoped receipt. It removes those resources by inspected ID, then removes the API key and managed ownership state. It preserves the shared `~/.cache/huggingface/` cache. If exact cleanup fails, `destroy` preserves the sandbox registry entry and ownership state so you can correct the reported conflict and retry. @@ -4589,6 +4615,7 @@ The following flags change defaults for commands that manage existing sandboxes. | Variable | Format | Effect | | --- | --- | --- | | `NEMOCLAW_CLEANUP_GATEWAY` | `1`, `true`, or `yes` to enable; `0`, `false`, or `no` to disable | Overrides the platform default (macOS unattended: cleanup; Linux/Windows: preserve) for whether `$$nemoclaw destroy` removes the shared gateway when destroying the last sandbox. Command-line `--cleanup-gateway` and `--no-cleanup-gateway` still take precedence. | +| `NEMOCLAW_KEEP_VLLM` | `1`, `true`, or `yes` to keep; `0`, `false`, or `no` to remove | Keeps the NemoClaw-managed `nemoclaw-vllm` container running when `$$nemoclaw destroy` deletes the last registered sandbox that uses Local vLLM. By default, that destroy removes the container. Command-line `--keep-vllm` has the same effect. | | `NEMOCLAW_CONFIG_ACCEPT_NEW_PATH` | Exactly `"1"` to opt in (`true`, `yes`, `on` are not accepted) | Allows `nemohermes config set` to write a dotpath that does not already exist in the sandbox config, without the interactive confirmation. Equivalent to passing `--config-accept-new-path`, and it takes precedence over `NEMOCLAW_NON_INTERACTIVE=1`. Without it, a run without a TTY refuses the write instead. | diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index d203fff1731..8944911fdda 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -48,8 +48,9 @@ Share redacted diagnostics only. | `~/.nemoclaw/ollama-backend` | Host-global legacy route URL used to restart the Ollama auth proxy and retained for compatibility with earlier releases. | No while any gateway uses the shared proxy. Rerun onboarding if this file is missing or damaged. | | `~/.nemoclaw/ollama-backend.json` | Mode-`0600`, versioned descriptor that identifies whether the matching legacy route fronts Ollama or a compatible endpoint. Recovery trusts its kind only when both files contain the same URL. | Yes, but recovery uses neutral remediation until onboarding recreates the descriptor. | | `~/.nemoclaw/ollama-proxy-port` | Host-global port used by the Ollama auth proxy and every Local Ollama sandbox route on the host. A command with a different `NEMOCLAW_OLLAMA_PROXY_PORT` stops before changing the shared proxy. | No while any gateway uses Local Ollama. Full uninstall uses this file to find the proxy and removes it with the other shared proxy state. | -| `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by authenticated NemoClaw-managed vLLM profiles. | No while any managed vLLM runtime uses it. Full uninstall removes it only after matching runtime cleanup succeeds and no sibling gateway remains. | -| `~/.nemoclaw/host-local-vllm-runtime.json` | Owner-only, credential-free receipt for a catalog-selected single-host vLLM runtime. It binds the immutable catalog, preset, and recipe digests to the container ID and API-key fingerprint. | No while that runtime exists. Recovery and full uninstall fail closed if its profile labels do not match this receipt, and uninstall removes it only after container cleanup succeeds. | +| `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by authenticated NemoClaw-managed vLLM profiles. | No while a managed vLLM runtime uses it. An eligible `destroy` removes it only after the authenticated single-host container is removed or confirmed absent and no registered `vllm-local` consumer remains. Preservation options and distributed ownership keep it. Full uninstall removes it only after matching runtime cleanup succeeds and no sibling gateway remains. | +| `~/.nemoclaw/host-local-vllm-runtime.json` | Owner-only, credential-free receipt for a catalog-selected single-host vLLM runtime. It binds the immutable catalog, preset, and recipe digests to the container ID and API-key fingerprint. | No while that runtime exists. Recovery, destroy, and full uninstall fail closed if its profile labels do not match this receipt, and destroy or uninstall removes it only after container cleanup succeeds. | +| `~/.nemoclaw/host-local-vllm-pending-retirement.json` | Owner-only, credential-free record of one eligible `vllm-local` sandbox name whose managed `nemoclaw-vllm` retirement is pending. Written before registry removal; a later eligible `destroy` replaces it. | No while retirement is pending. After registry removal, preserve it for a `destroy` retry with the same sandbox name. A settled retry clears the record, including when another `vllm-local` consumer remains, a distributed receipt owns the runtime, or `--keep-vllm` is requested. Full uninstall removes it with the other host-global state. | | `~/.nemoclaw/managed-llama-cpp/api-key` | Owner-only bearer API key mounted read-only into the managed llama.cpp container. It is absent from process arguments, logs, receipts, sandbox registry state, and status output. | No while the managed llama.cpp runtime exists. A retry reuses the same key. Destroy or full uninstall removes it only after runtime cleanup succeeds. | | `~/.nemoclaw/managed-llama-cpp/owner.json` | Owner-only, credential-free binding from one gateway to the sandbox, recipe, catalog digest, preset digest, and recipe digest that owns the managed llama.cpp runtime. | No while the managed llama.cpp runtime exists. Destroy or full uninstall removes it only after cleanup succeeds. | | `~/.nemoclaw/managed-llama-cpp/receipt.json` | Owner-only runtime receipt that binds the Docker authority, container ID, network, image digest, model identity, and lifecycle generation. It contains no API key. | No while the managed llama.cpp runtime exists. Recovery and cleanup use it and preserve it when ownership cannot be proved. | diff --git a/src/commands/sandbox/destroy.ts b/src/commands/sandbox/destroy.ts index 2de6df1ca46..4e05af6756d 100644 --- a/src/commands/sandbox/destroy.ts +++ b/src/commands/sandbox/destroy.ts @@ -12,11 +12,14 @@ export default class DestroyCliCommand extends NemoClawCommand { static strict = true; static summary = "Stop NIM and delete sandbox"; static description = "Destroy a sandbox and remove its local registry entry."; - static usage = [" [--yes|-y|--force] [--cleanup-gateway|--no-cleanup-gateway]"]; + static usage = [ + " [--yes|-y|--force] [--cleanup-gateway|--no-cleanup-gateway] [--keep-vllm]", + ]; static examples = [ "<%= config.bin %> sandbox destroy alpha", "<%= config.bin %> sandbox destroy alpha --yes", "<%= config.bin %> sandbox destroy alpha --yes --cleanup-gateway", + "<%= config.bin %> sandbox destroy alpha --yes --keep-vllm", ]; static args = { sandboxName: Args.string({ name: "sandbox", description: "Sandbox name", required: true }), @@ -29,6 +32,10 @@ export default class DestroyCliCommand extends NemoClawCommand { "When destroying the last sandbox, also tear down the shared NemoClaw gateway. Default: preserve on Linux; cleanup for unattended macOS destroys. NEMOCLAW_CLEANUP_GATEWAY overrides the platform default.", allowNo: true, }), + "keep-vllm": Flags.boolean({ + description: + "Keep the managed vLLM container running after destroying the last sandbox that uses Local vLLM. NEMOCLAW_KEEP_VLLM=1 has the same effect.", + }), }; public async run(): Promise { @@ -38,6 +45,7 @@ export default class DestroyCliCommand extends NemoClawCommand { force: flags.force === true, yes: flags.yes === true, ...(cleanupGatewayFlag === undefined ? {} : { cleanupGateway: cleanupGatewayFlag }), + ...(flags["keep-vllm"] === true ? { keepVllm: true } : {}), }); } } diff --git a/src/lib/actions/sandbox/connect-route-repair.test.ts b/src/lib/actions/sandbox/connect-route-repair.test.ts index 6f9f803d0df..4ba744083df 100644 --- a/src/lib/actions/sandbox/connect-route-repair.test.ts +++ b/src/lib/actions/sandbox/connect-route-repair.test.ts @@ -307,7 +307,11 @@ function makeResetDeps( overrides: Partial = {}, ) { const calls = { - localChecks: [] as Array<{ provider: string; quiet?: boolean }>, + localChecks: [] as Array<{ + provider: string; + quiet?: boolean; + recordedEndpointUrl?: string | null; + }>, inferenceSets: [] as Array<{ provider: string; model: string }>, unrecoverable: [] as Array<{ sandboxName: string; detail: string }>, logs: [] as string[], @@ -317,7 +321,11 @@ function makeResetDeps( const queue = [...probes]; const deps: ManagedInferenceRouteResetDeps = { verifyLocalInferenceRouteDependencies: vi.fn((provider, options) => { - calls.localChecks.push({ provider, quiet: options.quiet }); + calls.localChecks.push({ + provider, + quiet: options.quiet, + recordedEndpointUrl: options.recordedEndpointUrl, + }); return true; }), runInferenceSet: vi.fn((provider, model) => { @@ -351,13 +359,42 @@ describe("managed inference route reset unit flow", () => { expect(result).toBe(true); expect(calls.localChecks).toEqual([ - { provider: "ollama-local", quiet: false }, - { provider: "ollama-local", quiet: false }, + { provider: "ollama-local", quiet: false, recordedEndpointUrl: undefined }, + { provider: "ollama-local", quiet: false, recordedEndpointUrl: undefined }, ]); expect(calls.inferenceSets).toEqual([{ provider: "ollama-local", model: "qwen3:0.6b" }]); expect(calls.logs).toContain(" inference.local route repaired."); }); + it("verifies local vLLM dependencies against the sandbox's recorded route endpoint", async () => { + const { calls, deps } = makeResetDeps([healthy()]); + + const result = await resetManagedInferenceRouteWithDeps( + "demo", + sandbox({ + provider: "vllm-local", + model: "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + endpointUrl: "http://host.openshell.internal:46145/v1", + }), + { detail: "BROKEN 503" }, + deps, + ); + + expect(result).toBe(true); + expect(calls.localChecks).toEqual([ + { + provider: "vllm-local", + quiet: false, + recordedEndpointUrl: "http://host.openshell.internal:46145/v1", + }, + { + provider: "vllm-local", + quiet: false, + recordedEndpointUrl: "http://host.openshell.internal:46145/v1", + }, + ]); + }); + it("probes route health after a non-zero inference set and accepts a healthy route", async () => { const { calls, deps } = makeResetDeps([healthy()], { runInferenceSet: vi.fn((provider, model) => { diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index ca2a129cee7..2c0872769f5 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -255,7 +255,7 @@ export type SandboxInferenceRouteRepairDeps = { export type ManagedInferenceRouteResetDeps = { verifyLocalInferenceRouteDependencies: ( provider: string, - options: { quiet?: boolean }, + options: { quiet?: boolean; recordedEndpointUrl?: string | null }, ) => boolean; runInferenceSet: (provider: string, model: string) => { status: number | null }; probe: ( @@ -1550,7 +1550,10 @@ async function repairSandboxInferenceRouteIfNeeded( function verifyLocalInferenceRouteDependencies( provider: string, - { quiet = false }: { quiet?: boolean } = {}, + { + quiet = false, + recordedEndpointUrl, + }: { quiet?: boolean; recordedEndpointUrl?: string | null } = {}, ): boolean { const isOllamaLocal = provider === "ollama-local"; if (isOllamaLocal) { @@ -1562,6 +1565,7 @@ function verifyLocalInferenceRouteDependencies( } const localHealth = probeLocalProviderHealth(provider, { skipOllamaAuthProxySubprobe: isOllamaLocal, + recordedEndpointUrl, }); if (!localHealth) return true; if (!localHealth.ok) { @@ -1627,14 +1631,15 @@ export async function resetManagedInferenceRouteWithDeps( return false; }; - if (!deps.verifyLocalInferenceRouteDependencies(provider, { quiet })) { + const dependencyOptions = { quiet, recordedEndpointUrl: sb.endpointUrl }; + if (!deps.verifyLocalInferenceRouteDependencies(provider, dependencyOptions)) { return fail(detail); } if (!quiet) log(` Resetting inference route to ${route}.`); const resetResult = deps.runInferenceSet(provider, model); const resetFailed = resetResult.status !== 0; - if (!resetFailed && !deps.verifyLocalInferenceRouteDependencies(provider, { quiet })) { + if (!resetFailed && !deps.verifyLocalInferenceRouteDependencies(provider, dependencyOptions)) { return fail(detail); } diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index a96bca2e0d9..73c76a59bc7 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -575,29 +575,27 @@ describe("destroySandbox flow", () => { await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow("process.exit(1)"); - expect(harness.lifecycleLockEvents).toEqual([ - "acquired", - "acquired", - "released", - "released", - "process-exit", - ]); + const exitIndex = harness.lifecycleLockEvents.indexOf("process-exit"); + const firstAttemptLockEvents = harness.lifecycleLockEvents.slice(0, exitIndex); + expect(exitIndex).toBeGreaterThan(0); + expect(firstAttemptLockEvents.filter((event) => event === "acquired").length).toBeGreaterThan( + 0, + ); + expect(firstAttemptLockEvents.filter((event) => event === "released")).toHaveLength( + firstAttemptLockEvents.filter((event) => event === "acquired").length, + ); + expect(firstAttemptLockEvents.at(-1)).toBe("released"); expect(harness.events).not.toContain("delete"); expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); expect(harness.retirePortableLifecycleReceiptSpy).not.toHaveBeenCalled(); await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); - expect(harness.lifecycleLockEvents).toEqual([ - "acquired", - "acquired", - "released", - "released", - "process-exit", - "acquired", - "acquired", - "released", - "released", - ]); + const retryLockEvents = harness.lifecycleLockEvents.slice(exitIndex + 1); + expect(retryLockEvents.filter((event) => event === "acquired").length).toBeGreaterThan(0); + expect(retryLockEvents.filter((event) => event === "released")).toHaveLength( + retryLockEvents.filter((event) => event === "acquired").length, + ); + expect(retryLockEvents.at(-1)).toBe("released"); expect(harness.events.filter((event) => event === "delete")).toHaveLength(1); expect(harness.removeSandboxSpy).toHaveBeenCalledOnce(); expect(harness.retirePortableLifecycleReceiptSpy).toHaveBeenCalledOnce(); diff --git a/src/lib/actions/sandbox/destroy-managed-vllm-flow.test.ts b/src/lib/actions/sandbox/destroy-managed-vllm-flow.test.ts new file mode 100644 index 00000000000..ae26ba06c74 --- /dev/null +++ b/src/lib/actions/sandbox/destroy-managed-vllm-flow.test.ts @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + createDestroyHarness, + resetDestroyModuleCache, +} from "../../../../test/helpers/destroy-flow-test-harness"; + +const LOCAL_VLLM_SANDBOX = { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:46145/v1", +}; + +function loggedLines(harness: ReturnType): string { + return harness.logSpy.mock.calls.map((call) => String(call[0])).join("\n"); +} + +describe("destroySandbox managed vLLM retirement", () => { + beforeEach(() => { + vi.stubEnv("NEMOCLAW_KEEP_VLLM", ""); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + resetDestroyModuleCache(); + }); + + it( + "retires the managed vLLM container after the last Local vLLM sandbox is destroyed", + { timeout: 30_000 }, + async () => { + const containerId = "b".repeat(64); + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + const retirementOrder: string[] = []; + harness.withCurrentPortableHostFenceSpy.mockImplementation(async (operation) => { + retirementOrder.push("host-fence-enter"); + try { + return await operation(); + } finally { + retirementOrder.push("host-fence-exit"); + } + }); + harness.listHostGatewayRegistryEntriesSpy.mockImplementation(() => { + retirementOrder.push("inventory"); + return []; + }); + harness.retireHostLocalVllmRuntimeSpy.mockImplementation(() => { + retirementOrder.push("retire"); + return { + status: "removed", + containerId, + removed: [`container:${containerId}`], + }; + }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.retireHostLocalVllmRuntimeSpy).toHaveBeenCalledOnce(); + expect(harness.recordPendingVllmRetirementSpy).toHaveBeenCalledWith( + "alpha", + expect.any(String), + ); + expect(harness.recordPendingVllmRetirementSpy.mock.invocationCallOrder[0]).toBeLessThan( + harness.removeSandboxSpy.mock.invocationCallOrder[0], + ); + expect(harness.removeSandboxSpy.mock.invocationCallOrder[0]).toBeLessThan( + harness.retireHostLocalVllmRuntimeSpy.mock.invocationCallOrder[0], + ); + expect(harness.clearPendingVllmRetirementSpy.mock.invocationCallOrder[0]).toBeGreaterThan( + harness.retireHostLocalVllmRuntimeSpy.mock.invocationCallOrder[0], + ); + expect(harness.pendingVllmRetirement.sandboxName).toBeNull(); + expect(retirementOrder).toEqual([ + "host-fence-enter", + "host-fence-enter", + "inventory", + "retire", + "host-fence-exit", + "host-fence-exit", + ]); + expect(loggedLines(harness)).toContain( + `Removed managed vLLM container 'nemoclaw-vllm' (${containerId.slice(0, 12)})`, + ); + }, + ); + + it("keeps the managed vLLM container while another gateway registers a Local vLLM sandbox", async () => { + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + harness.listHostGatewayRegistryEntriesSpy.mockReturnValue([ + { + entry: { name: "beta", provider: "vllm-local" }, + gatewayPort: 8091, + registryFile: "/home/user/.nemoclaw/gateways/8091/sandboxes.json", + stateRoot: "/home/user/.nemoclaw/gateways/8091", + }, + ]); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.retireHostLocalVllmRuntimeSpy).not.toHaveBeenCalled(); + expect(loggedLines(harness)).toContain( + "preserved: 1 other registered sandbox(es) use provider 'vllm-local'", + ); + }); + + it("keeps the managed vLLM container when the destroy passes --keep-vllm", async () => { + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + + await expect( + harness.destroySandbox("alpha", { yes: true, keepVllm: true }), + ).resolves.toBeUndefined(); + + expect(harness.retireHostLocalVllmRuntimeSpy).not.toHaveBeenCalled(); + expect(harness.recordPendingVllmRetirementSpy).not.toHaveBeenCalled(); + expect(loggedLines(harness)).toContain("preserved (--keep-vllm)"); + }); + + it("keeps the managed vLLM container when NEMOCLAW_KEEP_VLLM=1 is set", async () => { + vi.stubEnv("NEMOCLAW_KEEP_VLLM", "1"); + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.retireHostLocalVllmRuntimeSpy).not.toHaveBeenCalled(); + expect(loggedLines(harness)).toContain("preserved (--keep-vllm)"); + }); + + it("does not touch the managed vLLM container for a sandbox that uses another provider", async () => { + const harness = createDestroyHarness({ provider: "nvidia-prod" }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.listHostGatewayRegistryEntriesSpy).not.toHaveBeenCalled(); + expect(harness.retireHostLocalVllmRuntimeSpy).not.toHaveBeenCalled(); + }); + + it("does not retire the managed vLLM container when registry removal does not complete", async () => { + const harness = createDestroyHarness({ ...LOCAL_VLLM_SANDBOX, removeSandboxResult: false }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.removeSandboxSpy).toHaveBeenCalledWith("alpha"); + expect(harness.retireHostLocalVllmRuntimeSpy).not.toHaveBeenCalled(); + expect(harness.pendingVllmRetirement.sandboxName).toBe("alpha"); + }); + + it("preserves the registry row when pending retirement cannot be recorded", async () => { + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + harness.recordPendingVllmRetirementSpy.mockImplementation(() => { + throw new Error("retirement record write failed"); + }); + + await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow( + 'process.exit unexpectedly called with "1"', + ); + + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + expect(harness.pendingVllmRetirement.sandboxName).toBeNull(); + expect(harness.errorSpy).toHaveBeenCalledWith( + expect.stringContaining("registry entry was preserved"), + ); + }); + + it("continues when a failed retirement write left a readable matching record", async () => { + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + harness.recordPendingVllmRetirementSpy.mockImplementation((sandboxName: unknown) => { + harness.pendingVllmRetirement.sandboxName = String(sandboxName); + throw new Error("retirement record fsync failed"); + }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.removeSandboxSpy).toHaveBeenCalledWith("alpha"); + expect(harness.retireHostLocalVllmRuntimeSpy).toHaveBeenCalledOnce(); + expect(harness.pendingVllmRetirement.sandboxName).toBeNull(); + }); + + it("warns and leaves the managed vLLM container in place when its ownership cannot be proven", async () => { + const harness = createDestroyHarness(LOCAL_VLLM_SANDBOX); + harness.retireHostLocalVllmRuntimeSpy.mockReturnValue({ + status: "preserved", + reason: "the container does not carry the NemoClaw managed vLLM label", + removed: [], + }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.warnSpy).toHaveBeenCalledWith( + expect.stringContaining("does not carry the NemoClaw managed vLLM label"), + ); + expect(harness.clearPendingVllmRetirementSpy).not.toHaveBeenCalled(); + expect(harness.pendingVllmRetirement.sandboxName).toBe("alpha"); + expect(loggedLines(harness)).toContain("Sandbox 'alpha' destroyed"); + }); + + it("retires the managed vLLM container on a retry whose registry row is already gone", async () => { + const containerId = "c".repeat(64); + const harness = createDestroyHarness({ + pendingVllmRetirement: "alpha", + registryEntryPresent: false, + sandboxPresent: false, + }); + harness.retireHostLocalVllmRuntimeSpy.mockReturnValue({ + status: "removed", + containerId, + removed: [`container:${containerId}`], + }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.recordPendingVllmRetirementSpy).not.toHaveBeenCalled(); + expect(harness.listHostGatewayRegistryEntriesSpy).toHaveBeenCalledOnce(); + expect(harness.retireHostLocalVllmRuntimeSpy).toHaveBeenCalledOnce(); + expect(harness.pendingVllmRetirement.sandboxName).toBeNull(); + expect(loggedLines(harness)).toContain( + `Removed managed vLLM container 'nemoclaw-vllm' (${containerId.slice(0, 12)})`, + ); + }); + + it("does not touch the managed vLLM container on a retry without a pending retirement", async () => { + const harness = createDestroyHarness({ registryEntryPresent: false, sandboxPresent: false }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.listHostGatewayRegistryEntriesSpy).not.toHaveBeenCalled(); + expect(harness.retireHostLocalVllmRuntimeSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/destroy-managed-vllm.test.ts b/src/lib/actions/sandbox/destroy-managed-vllm.test.ts new file mode 100644 index 00000000000..78dcda081fb --- /dev/null +++ b/src/lib/actions/sandbox/destroy-managed-vllm.test.ts @@ -0,0 +1,389 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + clearPendingHostLocalVllmRetirement, + HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE, + type HostLocalVllmRetirementResult, + readPendingHostLocalVllmRetirement, + recordPendingHostLocalVllmRetirement, +} from "../../inference/local-model-profile/cleanup"; +import type { HostGatewayRegistryEntry } from "../../state/gateway-registry"; +import type { SandboxEntry } from "../../state/registry"; +import { + type ManagedVllmDestroyDeps, + type ManagedVllmDestroyOutcome, + recordManagedVllmRetirementPending, + reportManagedVllmDestroyOutcome, + retireManagedVllmForDestroyedSandbox, +} from "./destroy-preflight"; + +const CONTAINER_ID = "a".repeat(64); +const REMOVED: HostLocalVllmRetirementResult = { + status: "removed", + containerId: CONTAINER_ID, + removed: [`container:${CONTAINER_ID}`], +}; + +function sandbox(overrides: Partial = {}): SandboxEntry { + return { + name: "alpha", + provider: "vllm-local", + model: "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + endpointUrl: "http://host.openshell.internal:46145/v1", + ...overrides, + }; +} + +function registryEntry( + name: string, + provider: string, + gatewayPort = 8080, +): HostGatewayRegistryEntry { + return { + entry: { name, provider }, + gatewayPort, + registryFile: `/home/user/.nemoclaw/${String(gatewayPort)}/sandboxes.json`, + stateRoot: `/home/user/.nemoclaw/${String(gatewayPort)}`, + }; +} + +function makeDeps( + remaining: HostGatewayRegistryEntry[], + retirement: HostLocalVllmRetirementResult = REMOVED, + pending: string | null = null, +) { + const listHostRegistryEntries = vi.fn(() => remaining); + const retireRuntime = vi.fn(() => retirement); + const clearPendingRetirement = vi.fn(); + const hostLifecycleLockState = { calls: 0 }; + const withHostLifecycleLock: NonNullable< + ManagedVllmDestroyDeps["withHostLifecycleLock"] + > = async (operation: () => Promise | T): Promise => { + hostLifecycleLockState.calls += 1; + return await operation(); + }; + return { + clearPendingRetirement, + hostLifecycleLockState, + listHostRegistryEntries, + retireRuntime, + withHostLifecycleLock, + deps: { + clearPendingRetirement, + listHostRegistryEntries, + readPendingRetirement: () => pending, + retireRuntime, + resolveHomeDir: () => "/home/user", + withHostLifecycleLock, + }, + }; +} + +describe("managed vLLM retirement after sandbox destroy", () => { + it("retires the container when the destroyed sandbox was the last Local vLLM consumer", async () => { + const { clearPendingRetirement, deps, hostLifecycleLockState, retireRuntime } = makeDeps([ + registryEntry("beta", "nvidia-prod"), + ]); + + expect(await retireManagedVllmForDestroyedSandbox("alpha", sandbox(), deps)).toEqual({ + kind: "retirement", + ...REMOVED, + }); + expect(hostLifecycleLockState.calls).toBe(1); + expect(retireRuntime).toHaveBeenCalledWith({ homeDir: "/home/user" }); + expect(clearPendingRetirement).toHaveBeenCalledWith("/home/user"); + }); + + it("keeps the container while another gateway state root still registers a Local vLLM sandbox", async () => { + const { clearPendingRetirement, deps, retireRuntime } = makeDeps([ + registryEntry("beta", "nvidia-prod"), + registryEntry("gamma", "vllm-local", 8091), + ]); + + expect(await retireManagedVllmForDestroyedSandbox("alpha", sandbox(), deps)).toEqual({ + kind: "kept", + reason: "consumers", + consumers: 1, + }); + expect(retireRuntime).not.toHaveBeenCalled(); + expect(clearPendingRetirement).toHaveBeenCalledWith("/home/user"); + }); + + it("keeps the container when the destroy requested --keep-vllm", async () => { + const { deps, hostLifecycleLockState, listHostRegistryEntries, retireRuntime } = makeDeps([]); + + expect( + await retireManagedVllmForDestroyedSandbox("alpha", sandbox(), { ...deps, keepVllm: true }), + ).toEqual({ kind: "kept", reason: "option" }); + expect(hostLifecycleLockState.calls).toBe(0); + expect(listHostRegistryEntries).not.toHaveBeenCalled(); + expect(retireRuntime).not.toHaveBeenCalled(); + }); + + it.each([ + { label: "no registry row and no pending retirement", entry: null, pending: null }, + { label: "a pending retirement for another sandbox", entry: null, pending: "beta" }, + { label: "a hosted provider", entry: sandbox({ provider: "nvidia-prod" }), pending: null }, + { label: "Local Ollama", entry: sandbox({ provider: "ollama-local" }), pending: null }, + { + label: "a runtime-provider host-local inference receipt", + entry: sandbox({ hostLocalInferenceReceipt: '{"schemaVersion":2}' }), + pending: null, + }, + ])("does not apply to a destroyed sandbox with $label", async ({ entry, pending }) => { + const { clearPendingRetirement, deps, hostLifecycleLockState, retireRuntime } = makeDeps( + [], + REMOVED, + pending, + ); + + expect(await retireManagedVllmForDestroyedSandbox("alpha", entry, deps)).toEqual({ + kind: "not-applicable", + }); + expect(hostLifecycleLockState.calls).toBe(0); + expect(deps.listHostRegistryEntries).not.toHaveBeenCalled(); + expect(retireRuntime).not.toHaveBeenCalled(); + expect(clearPendingRetirement).not.toHaveBeenCalled(); + }); + + it("retires the container on a retry whose registry row is gone but whose retirement is pending", async () => { + const { clearPendingRetirement, deps, hostLifecycleLockState, retireRuntime } = makeDeps( + [], + REMOVED, + "alpha", + ); + + expect(await retireManagedVllmForDestroyedSandbox("alpha", null, deps)).toEqual({ + kind: "retirement", + ...REMOVED, + }); + expect(hostLifecycleLockState.calls).toBe(1); + expect(retireRuntime).toHaveBeenCalledOnce(); + expect(clearPendingRetirement).toHaveBeenCalledWith("/home/user"); + }); + + it("preserves the container when a gateway registry cannot be read", async () => { + const retireRuntime = vi.fn(); + const clearPendingRetirement = vi.fn(); + + expect( + await retireManagedVllmForDestroyedSandbox("alpha", sandbox(), { + clearPendingRetirement, + listHostRegistryEntries: () => { + throw new Error("sandboxes.json is not owner-only"); + }, + resolveHomeDir: () => "/home/user", + retireRuntime: retireRuntime as never, + withHostLifecycleLock: async (operation) => await operation(), + }), + ).toEqual({ kind: "inventory-failed", detail: "sandboxes.json is not owner-only" }); + expect(retireRuntime).not.toHaveBeenCalled(); + expect(clearPendingRetirement).not.toHaveBeenCalled(); + }); + + it("preserves the container when the host lifecycle fence cannot be acquired", async () => { + const { deps, listHostRegistryEntries, retireRuntime } = makeDeps([]); + + expect( + await retireManagedVllmForDestroyedSandbox("alpha", sandbox(), { + ...deps, + withHostLifecycleLock: async () => { + throw new Error("lock unavailable"); + }, + }), + ).toEqual({ kind: "inventory-failed", detail: "lock unavailable" }); + expect(listHostRegistryEntries).not.toHaveBeenCalled(); + expect(retireRuntime).not.toHaveBeenCalled(); + }); + + it.each<{ label: string; retirement: HostLocalVllmRetirementResult }>([ + { + label: "preserved", + retirement: { + status: "preserved", + reason: "the container does not carry the NemoClaw managed vLLM label", + removed: [], + }, + }, + { + label: "partial", + retirement: { + status: "partial", + containerId: CONTAINER_ID, + reason: "host-local-vllm-runtime.json: permission denied", + remaining: ["host-local-vllm-runtime.json"], + removed: [`container:${CONTAINER_ID}`], + }, + }, + ])( + "passes a $label runtime result through and keeps the retirement pending", + async ({ retirement }) => { + const { clearPendingRetirement, deps } = makeDeps([], retirement); + + expect(await retireManagedVllmForDestroyedSandbox("alpha", sandbox(), deps)).toEqual({ + kind: "retirement", + ...retirement, + }); + expect(clearPendingRetirement).not.toHaveBeenCalled(); + }, + ); +}); + +describe("pending managed vLLM retirement record", () => { + const temporaryHomes: string[] = []; + + afterEach(() => { + for (const home of temporaryHomes.splice(0)) fs.rmSync(home, { force: true, recursive: true }); + }); + + function temporaryHome(): string { + const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pending-vllm-"))); + temporaryHomes.push(home); + return home; + } + + it("records the destroyed Local vLLM sandbox before its registry row is removed", () => { + const recordPendingRetirement = vi.fn(); + const deps = { recordPendingRetirement, resolveHomeDir: () => "/home/user" }; + + expect(recordManagedVllmRetirementPending(sandbox(), deps)).toBe(true); + expect(recordPendingRetirement).toHaveBeenCalledWith("alpha", "/home/user"); + }); + + it.each([ + { label: "--keep-vllm", entry: sandbox(), keepVllm: true }, + { label: "no registry row", entry: null, keepVllm: false }, + { label: "a hosted provider", entry: sandbox({ provider: "nvidia-prod" }), keepVllm: false }, + { + label: "a runtime-provider host-local inference receipt", + entry: sandbox({ hostLocalInferenceReceipt: '{"schemaVersion":2}' }), + keepVllm: false, + }, + ])("records nothing for $label", ({ entry, keepVllm }) => { + const recordPendingRetirement = vi.fn(); + + expect(recordManagedVllmRetirementPending(entry, { keepVllm, recordPendingRetirement })).toBe( + false, + ); + expect(recordPendingRetirement).not.toHaveBeenCalled(); + }); + + it("round-trips the sandbox name through an owner-only file and clears it", () => { + const home = temporaryHome(); + const filePath = path.join(home, ".nemoclaw", HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE); + + expect(readPendingHostLocalVllmRetirement(home)).toBeNull(); + recordPendingHostLocalVllmRetirement("alpha", home); + expect(fs.statSync(filePath).mode & 0o777).toBe(0o600); + expect(readPendingHostLocalVllmRetirement(home)).toBe("alpha"); + recordPendingHostLocalVllmRetirement("beta", home); + expect(readPendingHostLocalVllmRetirement(home)).toBe("beta"); + clearPendingHostLocalVllmRetirement(home); + expect(fs.existsSync(filePath)).toBe(false); + expect(readPendingHostLocalVllmRetirement(home)).toBeNull(); + expect(() => clearPendingHostLocalVllmRetirement(home)).not.toThrow(); + }); + + it.each(["", "null", "{}", '{"sandboxName":""}', '{"sandboxName":7}', "not json"])( + "treats the record %j as no pending retirement", + (contents) => { + const home = temporaryHome(); + fs.mkdirSync(path.join(home, ".nemoclaw"), { mode: 0o700, recursive: true }); + fs.writeFileSync( + path.join(home, ".nemoclaw", HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE), + contents, + ); + + expect(readPendingHostLocalVllmRetirement(home)).toBeNull(); + }, + ); +}); + +describe("managed vLLM retirement report", () => { + function render(outcome: ManagedVllmDestroyOutcome) { + const logs: string[] = []; + const warnings: string[] = []; + reportManagedVllmDestroyOutcome(outcome, { + log: (message) => logs.push(message), + warn: (message) => warnings.push(message), + }); + return { logs, warnings }; + } + + it("prints nothing when retirement does not apply or no container exists", () => { + expect(render({ kind: "not-applicable" })).toEqual({ logs: [], warnings: [] }); + expect(render({ kind: "retirement", status: "absent" })).toEqual({ logs: [], warnings: [] }); + }); + + it("names the removed container and the option that keeps it next time", () => { + const { logs, warnings } = render({ + kind: "retirement", + status: "removed", + containerId: CONTAINER_ID, + removed: [`container:${CONTAINER_ID}`], + }); + + expect(warnings).toEqual([]); + expect(logs[0]).toContain(`'nemoclaw-vllm' (${CONTAINER_ID.slice(0, 12)})`); + expect(logs[1]).toContain("--keep-vllm"); + expect(logs[1]).toContain("NEMOCLAW_KEEP_VLLM=1"); + }); + + it("reports remaining consumers, the keep option, or distributed ownership as preservation", () => { + expect(render({ kind: "kept", reason: "consumers", consumers: 2 }).logs).toEqual([ + " Managed vLLM container 'nemoclaw-vllm' preserved: 2 other registered sandbox(es) use provider 'vllm-local'.", + ]); + expect(render({ kind: "kept", reason: "option" }).logs).toEqual([ + " Managed vLLM container 'nemoclaw-vllm' preserved (--keep-vllm).", + ]); + const distributed = render({ + kind: "retirement", + status: "kept", + reason: "a distributed vLLM receipt owns it until full uninstall", + }); + expect(distributed.warnings).toEqual([]); + expect(distributed.logs).toEqual([ + " Managed vLLM container 'nemoclaw-vllm' preserved: a distributed vLLM receipt owns it until full uninstall.", + ]); + }); + + it("warns with the reason and an inspection hint when the container was left in place", () => { + const preserved = render({ + kind: "retirement", + status: "preserved", + reason: "Docker is unavailable", + removed: [], + }); + const inventory = render({ kind: "inventory-failed", detail: "registry unreadable" }); + + expect(preserved.logs).toEqual([]); + expect(preserved.warnings[0]).toContain("Docker is unavailable"); + expect(preserved.warnings[0]).toContain("docker container inspect nemoclaw-vllm"); + expect(inventory.warnings[0]).toContain("registry unreadable"); + expect(inventory.warnings[0]).toContain("docker container inspect nemoclaw-vllm"); + }); + + it("reports a removed container with retryable private state separately", () => { + const partial = render({ + kind: "retirement", + status: "partial", + containerId: CONTAINER_ID, + reason: "host-local-vllm-runtime.json: permission denied", + remaining: ["host-local-vllm-runtime.json"], + removed: [`container:${CONTAINER_ID}`], + }); + + expect(partial.logs).toEqual([]); + expect(partial.warnings[0]).toContain(`was removed (${CONTAINER_ID.slice(0, 12)})`); + expect(partial.warnings[0]).toContain("private state cleanup is incomplete"); + expect(partial.warnings[0]).toContain("rerun the same destroy command"); + expect(partial.warnings[0]).not.toContain("uninstall"); + }); +}); diff --git a/src/lib/actions/sandbox/destroy-preflight.ts b/src/lib/actions/sandbox/destroy-preflight.ts index 68ed2ba0570..49e29ff8154 100644 --- a/src/lib/actions/sandbox/destroy-preflight.ts +++ b/src/lib/actions/sandbox/destroy-preflight.ts @@ -8,6 +8,14 @@ import { buildSelectedOpenShellSubprocessEnv } from "../../adapters/openshell/co import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { withModelRouterPortLifecycleLock } from "../../inference/gateway-route-mutation-lock"; +import { + clearPendingHostLocalVllmRetirement, + HOST_LOCAL_VLLM_CONTAINER_NAME, + type HostLocalVllmRetirementResult, + readPendingHostLocalVllmRetirement, + recordPendingHostLocalVllmRetirement, + retireHostLocalVllmRuntime, +} from "../../inference/local-model-profile/cleanup"; import { DEFAULT_MODEL_ROUTER_PORT, isRoutedInferenceProvider } from "../../onboard/model-router"; import { doesModelRouterProcessOwnPort, @@ -22,6 +30,7 @@ import type { releaseOnboardLock, Session, } from "../../state/onboard-session"; +import { withCurrentPortableHostFence } from "../../state/portable-uninstall-retirement"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { @@ -134,6 +143,164 @@ export function stopSandboxInferenceResources( } } +const LOCAL_VLLM_PROVIDER = "vllm-local"; +const MANAGED_VLLM_INSPECT_HINT = `Inspect it with 'docker container inspect ${HOST_LOCAL_VLLM_CONTAINER_NAME}' before you stop it, or resolve the cause and rerun this destroy to retire it.`; + +export type ManagedVllmDestroyOutcome = + | { kind: "not-applicable" } + | { kind: "kept"; reason: "option" } + | { kind: "kept"; reason: "consumers"; consumers: number } + | { kind: "inventory-failed"; detail: string } + | ({ kind: "retirement" } & HostLocalVllmRetirementResult); + +export type ManagedVllmDestroyDeps = { + keepVllm?: boolean; + clearPendingRetirement?: typeof clearPendingHostLocalVllmRetirement; + listHostRegistryEntries?: typeof listHostGatewayRegistryEntries; + readPendingRetirement?: typeof readPendingHostLocalVllmRetirement; + recordPendingRetirement?: typeof recordPendingHostLocalVllmRetirement; + resolveHomeDir?: () => string; + retireRuntime?: typeof retireHostLocalVllmRuntime; + withHostLifecycleLock?: typeof withCurrentPortableHostFence; +}; + +function resolveDestroyHomeDir(deps: ManagedVllmDestroyDeps): string { + return (deps.resolveHomeDir ?? (() => process.env.HOME || os.homedir()))(); +} + +/** A sandbox whose runtime provider owns a host-local inference receipt retires its runtime through that provider. */ +function consumesManagedVllm(sandbox: SandboxEntry | null): sandbox is SandboxEntry { + return ( + sandbox !== null && + sandbox.provider === LOCAL_VLLM_PROVIDER && + typeof sandbox.hostLocalInferenceReceipt !== "string" + ); +} + +/** + * Record the pending retirement before the registry row is removed. The row is + * the only proof that the sandbox used the container, so a destroy retry after + * an interrupted or preserved retirement needs this record to retire it. + */ +export function recordManagedVllmRetirementPending( + sandbox: SandboxEntry | null, + deps: ManagedVllmDestroyDeps = {}, +): boolean { + if (deps.keepVllm === true || !consumesManagedVllm(sandbox)) return false; + (deps.recordPendingRetirement ?? recordPendingHostLocalVllmRetirement)( + sandbox.name, + resolveDestroyHomeDir(deps), + ); + return true; +} + +/** A settled outcome leaves no retirement for a retry to finish. */ +function managedVllmRetirementSettled(outcome: ManagedVllmDestroyOutcome): boolean { + return ( + outcome.kind === "kept" || + (outcome.kind === "retirement" && + outcome.status !== "preserved" && + outcome.status !== "partial") + ); +} + +/** + * Retire the host-global managed vLLM container after the destroyed sandbox's + * registry row is gone and no registered sandbox in any gateway state root + * still uses Local vLLM. A retry whose row is already gone owns the retirement + * only through the pending record for the same sandbox name. + */ +export async function retireManagedVllmForDestroyedSandbox( + sandboxName: string, + sandbox: SandboxEntry | null, + deps: ManagedVllmDestroyDeps = {}, +): Promise { + const home = resolveDestroyHomeDir(deps); + if ( + !consumesManagedVllm(sandbox) && + (deps.readPendingRetirement ?? readPendingHostLocalVllmRetirement)(home) !== sandboxName + ) { + return { kind: "not-applicable" }; + } + const outcome = await decideManagedVllmRetirement(home, deps); + if (managedVllmRetirementSettled(outcome)) { + (deps.clearPendingRetirement ?? clearPendingHostLocalVllmRetirement)(home); + } + return outcome; +} + +async function decideManagedVllmRetirement( + home: string, + deps: ManagedVllmDestroyDeps, +): Promise { + if (deps.keepVllm === true) return { kind: "kept", reason: "option" }; + try { + return await (deps.withHostLifecycleLock ?? withCurrentPortableHostFence)(() => { + const consumers = (deps.listHostRegistryEntries ?? listHostGatewayRegistryEntries)( + home, + ).filter(({ entry }) => entry.provider === LOCAL_VLLM_PROVIDER).length; + if (consumers > 0) return { kind: "kept", reason: "consumers", consumers }; + return { + kind: "retirement", + ...(deps.retireRuntime ?? retireHostLocalVllmRuntime)({ homeDir: home }), + }; + }); + } catch (error) { + return { + kind: "inventory-failed", + detail: error instanceof Error ? error.message : String(error), + }; + } +} + +/** Report the retirement outcome; a preserved container is a warning because the sandbox is already gone. */ +export function reportManagedVllmDestroyOutcome( + outcome: ManagedVllmDestroyOutcome, + output: { log: (message: string) => void; warn: (message: string) => void }, +): void { + const name = HOST_LOCAL_VLLM_CONTAINER_NAME; + switch (outcome.kind) { + case "not-applicable": + return; + case "kept": + output.log( + outcome.reason === "option" + ? ` Managed vLLM container '${name}' preserved (--keep-vllm).` + : ` Managed vLLM container '${name}' preserved: ${String(outcome.consumers)} other registered sandbox(es) use provider '${LOCAL_VLLM_PROVIDER}'.`, + ); + return; + case "inventory-failed": + output.warn( + `Sandbox deletion succeeded, but NemoClaw could not safely confirm across the host that no sandbox still uses provider '${LOCAL_VLLM_PROVIDER}': ${outcome.detail}. The managed vLLM container '${name}' was left in place. ${MANAGED_VLLM_INSPECT_HINT}`, + ); + return; + case "retirement": + break; + } + switch (outcome.status) { + case "absent": + return; + case "kept": + output.log(` Managed vLLM container '${name}' preserved: ${outcome.reason}.`); + return; + case "removed": + output.log( + ` Removed managed vLLM container '${name}' (${outcome.containerId.slice(0, 12)}); no registered sandbox uses provider '${LOCAL_VLLM_PROVIDER}'.`, + ); + output.log(" Pass '--keep-vllm' or set NEMOCLAW_KEEP_VLLM=1 to keep it running next time."); + return; + case "preserved": + output.warn( + `Sandbox deletion succeeded, but the managed vLLM container '${name}' was left in place: ${outcome.reason}. ${MANAGED_VLLM_INSPECT_HINT}`, + ); + return; + case "partial": + output.warn( + `Sandbox deletion succeeded and the managed vLLM container '${name}' ${outcome.containerId ? `was removed (${outcome.containerId.slice(0, 12)})` : "is absent"}, but its private state cleanup is incomplete: ${outcome.reason}. Remaining state: ${outcome.remaining.join(", ")}. Resolve the cause, then rerun the same destroy command to finish cleanup.`, + ); + } +} + export type StopModelRouterForDestroyedSandboxDeps = { acquireOnboardLock: typeof acquireOnboardLock; compareAndSwapSession: typeof compareAndSwapSession; diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 42e1670a104..f470f80dab4 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -22,7 +22,10 @@ import { parseHttpsPinRouteId, revokeHttpsPinRuntimeAdapterRoute, } from "../../inference/https-pin-runtime-adapter"; -import { prepareManagedLlamaCppRuntimeCleanupForSandbox } from "../../inference/local-model-profile/cleanup"; +import { + prepareManagedLlamaCppRuntimeCleanupForSandbox, + readPendingHostLocalVllmRetirement, +} from "../../inference/local-model-profile/cleanup"; import { isLocalOllamaRouteOwner, loadPersistedOllamaHost, @@ -44,7 +47,6 @@ import { removeManagedAgentStateVolumes, } from "../../onboard/sandbox-provider-cleanup"; import { validateName } from "../../runner"; -import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock"; import { enforceRemovedImmutabilityMigrationBoundary, retireRemovedImmutabilityStateRecord, @@ -77,11 +79,15 @@ import { isSameDestroyContainerIdentityProof, observeDestroyContainerIdentity, } from "./destroy-presence"; +import { withSandboxLifecycleLock } from "./lifecycle/lock"; import { prepareSandboxDestroy, + recordManagedVllmRetirementPending, + reportManagedVllmDestroyOutcome, resolveSandboxDestroyRegistryAuthority, resolveSandboxDestroyGatewayName, resolveSandboxDestroyRuntimeSelection, + retireManagedVllmForDestroyedSandbox, stopModelRouterForDestroyedSandbox, stopSandboxInferenceResources, teardownSandboxDashboardForward, @@ -658,7 +664,7 @@ export async function destroySandbox( } = {}, ): Promise { try { - return await withMcpLifecycleLock(sandboxName, () => { + return await withSandboxLifecycleLock(sandboxName, () => { const removedImmutabilityMigration = enforceRemovedImmutabilityMigrationBoundary( sandboxName, { allowStateRecord: true }, @@ -1162,6 +1168,21 @@ async function destroySandboxUnlocked( if (deleteSucceededOrAlreadyGone && retireRemovedImmutabilityState) { retireRemovedImmutabilityStateRecord(sandboxName, "sandbox-destroyed"); } + if (deleteSucceededOrAlreadyGone) { + try { + recordManagedVllmRetirementPending(sandbox, { keepVllm: normalized.keepVllm }); + } catch (error) { + defaultDestroyWarn( + `Could not record the pending managed vLLM retirement for '${sandboxName}': ${redactDestroyError(error)}. A destroy retry cannot retire the container if this retirement does not complete.`, + ); + if (readPendingHostLocalVllmRetirement() !== sandboxName) { + console.error( + " The sandbox registry entry was preserved so exact managed vLLM retirement can be retried.", + ); + requestSandboxDestroyExit(1); + } + } + } const removalOutcome = removeSandboxRegistryEntryOutcome(sandboxName, { removeImage: (name) => removeSandboxImage(name, { getSandbox: getRegisteredSandbox }), removeSandbox: registryAuthority.removeSandbox, @@ -1250,6 +1271,17 @@ async function destroySandboxUnlocked( ); } } + // The registry row is gone, so every remaining Local vLLM row in any gateway + // state root is a peer that still needs the host-global container. A retry + // that finds no row owns the retirement only through its pending record. + if (deleteSucceededOrAlreadyGone && (removed || (!sandbox && registryEntryAbsent))) { + reportManagedVllmDestroyOutcome( + await retireManagedVllmForDestroyedSandbox(sandboxName, sandbox, { + keepVllm: normalized.keepVllm, + }), + { log: console.log, warn: defaultDestroyWarn }, + ); + } const retainedRecoveryOwnsDestroySession = retainedRecoveryAuthority ? onboardSession.retainedSandboxRecoveryMatchesSession( retainedRecoveryAuthority, diff --git a/src/lib/actions/sandbox/doctor-inference.test.ts b/src/lib/actions/sandbox/doctor-inference.test.ts index d5fdbfc5e07..9ca9b25a8fe 100644 --- a/src/lib/actions/sandbox/doctor-inference.test.ts +++ b/src/lib/actions/sandbox/doctor-inference.test.ts @@ -289,4 +289,27 @@ describe("doctor inference checks", () => { expect(probe).toHaveBeenCalledWith("ollama-local", { model: "nemotron-mini:latest" }); }); + + it("passes the recorded route endpoint to direct provider diagnostics", async () => { + const probe = vi.fn(() => upstream()); + + await collectInferenceChecks( + "alpha", + { + provider: "vllm-local", + model: "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + recordedEndpointUrl: "http://host.openshell.internal:46145/v1", + }, + true, + { + probeProviderHealthImpl: probe, + probeSandboxInferenceGatewayHealthImpl: async () => gateway(true), + }, + ); + + expect(probe).toHaveBeenCalledWith("vllm-local", { + model: "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + recordedEndpointUrl: "http://host.openshell.internal:46145/v1", + }); + }); }); diff --git a/src/lib/actions/sandbox/doctor-inference.ts b/src/lib/actions/sandbox/doctor-inference.ts index e635f1c6e08..b45a7a2801d 100644 --- a/src/lib/actions/sandbox/doctor-inference.ts +++ b/src/lib/actions/sandbox/doctor-inference.ts @@ -16,6 +16,8 @@ export type DoctorInferenceRoute = { model: string; provider: string; effectiveReasoningEffort?: EffectiveReasoningEffort | null; + /** Sandbox route endpoint recorded at onboard; selects the bearerless local vLLM host port. */ + recordedEndpointUrl?: string | null; }; type ManagedLlamaCppDoctorDeps = { @@ -184,15 +186,18 @@ function unavailableProviderHealthDiagnostic(detail: string): ProviderHealthStat } function collectProviderHealthDiagnostics( - provider: string, - model: string, + route: DoctorInferenceRoute, probe: typeof probeProviderHealth, ): ProviderHealthStatus[] { + const { provider, model, recordedEndpointUrl } = route; if (provider === "unknown") { return [unavailableProviderHealthDiagnostic("provider route is unknown")]; } try { - const health = probe(provider, { model }); + const health = probe(provider, { + model, + ...(typeof recordedEndpointUrl === "string" ? { recordedEndpointUrl } : {}), + }); if (!health) { return [ unavailableProviderHealthDiagnostic(`no direct health probe registered for ${provider}`), @@ -223,8 +228,7 @@ export async function collectInferenceChecks( ); pushInferenceHealthCheck(checks, gatewayProbe, { label: "Inference route (gateway)" }); for (const diagnostic of collectProviderHealthDiagnostics( - route.provider, - route.model, + route, deps.probeProviderHealthImpl ?? probeProviderHealth, )) { pushInferenceHealthCheck(checks, diagnostic, { authoritative: false }); diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index e41da9262b4..29bc524f928 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -400,6 +400,7 @@ async function resolveInferenceRoute( model: live?.model || sb?.model || "unknown", provider: live?.provider || sb?.provider || "unknown", effectiveReasoningEffort: resolveDoctorReasoningEffort(sb), + recordedEndpointUrl: sb?.endpointUrl, }; } diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 45384e9faf9..9fa1b670048 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -97,10 +97,12 @@ export function getSandboxStatusInferenceHealth( currentProvider: unknown, currentModel: unknown, probeProviderHealthImpl: ProbeProviderHealth = probeProviderHealth, + recordedEndpointUrl?: unknown, ): ProviderHealthStatus | null { if (!gatewayPresent || typeof currentProvider !== "string") return null; return probeProviderHealthImpl(currentProvider, { model: typeof currentModel === "string" ? currentModel : undefined, + ...(typeof recordedEndpointUrl === "string" ? { recordedEndpointUrl } : {}), }); } @@ -117,6 +119,7 @@ export function maybeGetSandboxStatusInferenceHealth( currentProvider: unknown, currentModel: unknown, probeProviderHealthImpl?: ProbeProviderHealth, + recordedEndpointUrl?: unknown, ): ProviderHealthStatus | null { if (suppressInferenceProbe) return null; return getSandboxStatusInferenceHealth( @@ -124,6 +127,7 @@ export function maybeGetSandboxStatusInferenceHealth( currentProvider, currentModel, probeProviderHealthImpl, + recordedEndpointUrl, ); } @@ -637,6 +641,7 @@ export async function collectSandboxStatusSnapshot( (live && live.provider) || currentProvider, (live && live.model) || currentModel, opts.deps?.probeProviderHealthImpl, + sb?.endpointUrl, ); } catch { providerHealth = { diff --git a/src/lib/actions/sandbox/status.test.ts b/src/lib/actions/sandbox/status.test.ts index b2a43f1d17f..4cbb39bf71b 100644 --- a/src/lib/actions/sandbox/status.test.ts +++ b/src/lib/actions/sandbox/status.test.ts @@ -177,6 +177,43 @@ describe("sandbox status inference health", () => { }); }); + it("passes the recorded sandbox route endpoint to the provider probe", () => { + let observed: ProviderHealthProbeOptions | undefined; + + getSandboxStatusInferenceHealth( + true, + "vllm-local", + "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + (_provider, options) => { + observed = options; + return null; + }, + "http://host.openshell.internal:46145/v1", + ); + + expect(observed).toEqual({ + model: "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + recordedEndpointUrl: "http://host.openshell.internal:46145/v1", + }); + }); + + it("omits the recorded endpoint from the probe options when the registry records none", () => { + let observed: ProviderHealthProbeOptions | undefined; + + getSandboxStatusInferenceHealth( + true, + "vllm-local", + "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8", + (_provider, options) => { + observed = options; + return null; + }, + null, + ); + + expect(observed).toEqual({ model: "nvidia/NVIDIA-Nemotron-3-Nano-4B-FP8" }); + }); + it("does not probe when the sandbox gateway is not present", () => { let called = false; diff --git a/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts b/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts index 1b6977f566e..285e3430bdb 100644 --- a/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts +++ b/src/lib/actions/uninstall/run-plan-local-model-profile.test.ts @@ -705,4 +705,61 @@ describe("uninstall local model profile cleanup", () => { expect(errors.join("\n")).toContain("Host-local model runtime cleanup did not complete"); expect(runDocker.mock.calls.some(([args]) => args[0] === "rm")).toBe(false); }); + + it("removes an orphaned bearerless vLLM container before managed llama.cpp cleanup when no vLLM state remains", async () => { + const containerId = "d".repeat(64); + const runDocker = dockerResults( + new Map([[JSON.stringify(ORPHANED_VLLM_INSPECT_ARGS), ok(`${containerId} true\n`)]]), + ); + const runLocalModelRuntimeCleanup = vi.fn(() => ok()); + + const result = await runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: (command) => command === "openshell" || command === "docker", + env: { HOME: "/tmp/nemoclaw-uninstall-llama-and-bearerless-vllm" } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).endsWith("/.nemoclaw/managed-llama-cpp"), + isTty: false, + log: () => {}, + run: vi.fn(okWithKnownGatewayList), + runDocker, + runLocalModelRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(0); + expect(runDocker).toHaveBeenCalledWith( + ["rm", "-f", containerId], + expect.objectContaining({ timeout: 10_000 }), + ); + expect(runLocalModelRuntimeCleanup).toHaveBeenCalledOnce(); + expect(runDocker.mock.invocationCallOrder[0]).toBeLessThan( + runLocalModelRuntimeCleanup.mock.invocationCallOrder[0], + ); + }); + + it("routes a host-local vLLM runtime receipt through validated cleanup instead of label-only removal", async () => { + const runDocker = dockerResults( + new Map([[JSON.stringify(ORPHANED_VLLM_INSPECT_ARGS), ok(`${"e".repeat(64)} true\n`)]]), + ); + const runLocalModelRuntimeCleanup = vi.fn(() => ok()); + + const result = await runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: (command) => command === "openshell" || command === "docker", + env: { HOME: "/tmp/nemoclaw-uninstall-vllm-receipt-only" } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).endsWith("/.nemoclaw/host-local-vllm-runtime.json"), + isTty: false, + log: () => {}, + run: vi.fn(okWithKnownGatewayList), + runDocker, + runLocalModelRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(0); + expect(runLocalModelRuntimeCleanup).toHaveBeenCalledOnce(); + expect(runDocker.mock.calls.some(([args]) => args[0] === "rm")).toBe(false); + }); }); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index f4c096c67f1..b8f04c4e035 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -35,6 +35,7 @@ import { cleanupManagedLlamaCppRuntimeForSandbox, HOST_LOCAL_VLLM_CONTAINER_NAME, HOST_LOCAL_VLLM_MANAGED_LABEL, + HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE, type ManagedLlamaCppCleanupTarget, resolveManagedLlamaCppCleanupTarget, } from "../../inference/local-model-profile/cleanup"; @@ -2197,17 +2198,24 @@ function removeManagedDistributedVllmRuntime( function removeHostLocalModelRuntimes(paths: UninstallPaths, runtime: UninstallRuntime): boolean { const sharedRoot = path.dirname(paths.managedSwapMarkerPath); const hasLlamaState = runtime.existsSync(path.join(sharedRoot, "managed-llama-cpp")); - const hasManagedKey = runtime.existsSync(path.join(sharedRoot, MANAGED_VLLM_API_KEY_FILE)); + const hasHostLocalVllmState = [ + MANAGED_VLLM_API_KEY_FILE, + HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE, + ].some((name) => runtime.existsSync(path.join(sharedRoot, name))); const hasDistributedReceipt = [ MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, ].some((name) => runtime.existsSync(path.join(sharedRoot, name))); - if (!hasLlamaState && (!hasManagedKey || hasDistributedReceipt)) { - if (!hasManagedKey && !hasDistributedReceipt && !removeOrphanedManagedHostLocalVllm(runtime)) { - return false; - } - return true; + // A bearerless managed container leaves no key or receipt, and the runtime + // cleanup inspects Docker only for recorded vLLM state. + if ( + !hasHostLocalVllmState && + !hasDistributedReceipt && + !removeOrphanedManagedHostLocalVllm(runtime) + ) { + return false; } + if (!hasLlamaState && (!hasHostLocalVllmState || hasDistributedReceipt)) return true; const result = runtime.runLocalModelRuntimeCleanup({ env: runtime.env, stdio: "inherit", diff --git a/src/lib/cli/public-display-defaults.ts b/src/lib/cli/public-display-defaults.ts index 74cef1d3446..19f7ab2964b 100644 --- a/src/lib/cli/public-display-defaults.ts +++ b/src/lib/cli/public-display-defaults.ts @@ -249,7 +249,7 @@ const PUBLIC_DISPLAY_LAYOUT: Record = { group: "Sandbox Management", order: 15, description: "Stop NIM + delete sandbox", - flags: "[--yes|-y|--force] [--cleanup-gateway|--no-cleanup-gateway]", + flags: "[--yes|-y|--force] [--cleanup-gateway|--no-cleanup-gateway] [--keep-vllm]", }, ], "sandbox:download": [ diff --git a/src/lib/domain/lifecycle/options.test.ts b/src/lib/domain/lifecycle/options.test.ts index b75650bb545..8a308367d8d 100644 --- a/src/lib/domain/lifecycle/options.test.ts +++ b/src/lib/domain/lifecycle/options.test.ts @@ -139,6 +139,55 @@ describe("lifecycle option normalization", () => { ); }); + describe("destroy keepVllm resolution", () => { + const ENV_KEY = "NEMOCLAW_KEEP_VLLM"; + + beforeEach(() => { + vi.stubEnv(ENV_KEY, undefined); + }); + + it("leaves keepVllm unset by default so destroy retires the last managed vLLM container", () => { + expect(normalizeDestroySandboxOptions(["--yes"])).toEqual({ force: false, yes: true }); + expect(normalizeDestroySandboxOptions({ yes: true })).toEqual({ yes: true }); + }); + + it("threads --keep-vllm through argv", () => { + expect(normalizeDestroySandboxOptions(["--yes", "--keep-vllm"])).toEqual({ + force: false, + yes: true, + keepVllm: true, + }); + }); + + it("falls back to NEMOCLAW_KEEP_VLLM when no flag is passed", () => { + vi.stubEnv(ENV_KEY, "1"); + expect(normalizeDestroySandboxOptions(["--yes"])).toEqual({ + force: false, + yes: true, + keepVllm: true, + }); + expect(normalizeDestroySandboxOptions({ yes: true })).toEqual({ yes: true, keepVllm: true }); + }); + + it("explicit option object wins over env var", () => { + vi.stubEnv(ENV_KEY, "1"); + expect(normalizeDestroySandboxOptions({ yes: true, keepVllm: false })).toEqual({ + yes: true, + keepVllm: false, + }); + }); + + it.each(["0", "false", "No"])("recognises falsy NEMOCLAW_KEEP_VLLM spelling %#", (value) => { + vi.stubEnv(ENV_KEY, value); + expect(normalizeDestroySandboxOptions({}).keepVllm).toBe(false); + }); + + it.each(["", "maybe"])("ignores unrecognized NEMOCLAW_KEEP_VLLM spelling %#", (value) => { + vi.stubEnv(ENV_KEY, value); + expect(normalizeDestroySandboxOptions({}).keepVllm).toBeUndefined(); + }); + }); + it("preserves typed rebuild options and still accepts compatibility argv", () => { expect( normalizeRebuildSandboxOptions({ diff --git a/src/lib/domain/lifecycle/options.ts b/src/lib/domain/lifecycle/options.ts index 93572fa0da4..573947576b1 100644 --- a/src/lib/domain/lifecycle/options.ts +++ b/src/lib/domain/lifecycle/options.ts @@ -28,15 +28,30 @@ export interface DestroySandboxOptions { * decide whether to prompt. */ cleanupGateway?: boolean; + /** + * Keep the host-global managed vLLM container running after destroying + * the last registered sandbox that uses Local vLLM. Resolution order during + * normalization: explicit option, then the `--keep-vllm` argv flag, then + * `NEMOCLAW_KEEP_VLLM=1`. Anything else retires the container. + */ + keepVllm?: boolean; } -function readCleanupGatewayEnv(): boolean | undefined { - const raw = (process.env.NEMOCLAW_CLEANUP_GATEWAY ?? "").trim().toLowerCase(); +function readBooleanEnv(name: string): boolean | undefined { + const raw = (process.env[name] ?? "").trim().toLowerCase(); if (raw === "1" || raw === "true" || raw === "yes") return true; if (raw === "0" || raw === "false" || raw === "no") return false; return undefined; } +function readCleanupGatewayEnv(): boolean | undefined { + return readBooleanEnv("NEMOCLAW_CLEANUP_GATEWAY"); +} + +function readKeepVllmEnv(): boolean | undefined { + return readBooleanEnv("NEMOCLAW_KEEP_VLLM"); +} + export interface RebuildSandboxOptions { dcodeAutoApprovalMode?: DcodeAutoApprovalMode; force?: boolean; @@ -62,16 +77,19 @@ export function normalizeDestroySandboxOptions( options: string[] | DestroySandboxOptions = {}, ): DestroySandboxOptions { const envCleanupGateway = readCleanupGatewayEnv(); + const envKeepVllm = readKeepVllmEnv(); const nonInteractive = isNonInteractiveEnv(); if (Array.isArray(options)) { const yesIdx = options.lastIndexOf("--cleanup-gateway"); const noIdx = options.lastIndexOf("--no-cleanup-gateway"); const cleanupGateway: boolean | undefined = yesIdx === -1 && noIdx === -1 ? envCleanupGateway : yesIdx > noIdx; + const keepVllm: boolean | undefined = options.includes("--keep-vllm") ? true : envKeepVllm; return { force: options.includes("--force"), yes: options.includes("--yes") || nonInteractive, ...(cleanupGateway === undefined ? {} : { cleanupGateway }), + ...(keepVllm === undefined ? {} : { keepVllm }), }; } return { @@ -80,6 +98,9 @@ export function normalizeDestroySandboxOptions( ...(options.cleanupGateway === undefined && envCleanupGateway !== undefined ? { cleanupGateway: envCleanupGateway } : {}), + ...(options.keepVllm === undefined && envKeepVllm !== undefined + ? { keepVllm: envKeepVllm } + : {}), }; } diff --git a/src/lib/inference/health.ts b/src/lib/inference/health.ts index 36009bd0445..ecc444771a0 100644 --- a/src/lib/inference/health.ts +++ b/src/lib/inference/health.ts @@ -60,6 +60,8 @@ export interface ProviderHealthProbeOptions { model?: string | null; getCredentialImpl?: (envName: string) => string | null | undefined; isWsl?: boolean; + /** Sandbox route endpoint recorded at onboard; selects the bearerless local vLLM host port. */ + recordedEndpointUrl?: string | null; } export type OllamaHostInventoryProbeOptions = { @@ -738,6 +740,7 @@ export function probeProviderHealth( const localOptions: LocalProviderHealthProbeOptions = { model: options.model, runCurlProbeImpl: options.runCurlProbeImpl, + recordedEndpointUrl: options.recordedEndpointUrl, }; const local = probeLocalProviderHealth(provider, localOptions); if (local) { diff --git a/src/lib/inference/local-model-profile/cleanup-vllm-absence.test.ts b/src/lib/inference/local-model-profile/cleanup-vllm-absence.test.ts new file mode 100644 index 00000000000..53546960f4d --- /dev/null +++ b/src/lib/inference/local-model-profile/cleanup-vllm-absence.test.ts @@ -0,0 +1,196 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { MANAGED_VLLM_API_KEY_FILE } from "../serving/managed-runtime-receipts"; +import { runtimeAuthFingerprint } from "../serving/runtime-auth-fingerprint"; +import { + HOST_LOCAL_VLLM_CONTAINER_NAME, + HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE, + persistHostLocalVllmRuntimeReceipt, +} from "../serving/vllm-host-local-lifecycle"; +import { managedVllmStateDir } from "../vllm-api-key"; +import { + HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE, + readPendingHostLocalVllmRetirement, + recordPendingHostLocalVllmRetirement, + cleanupLocalModelRuntimes, + retireHostLocalVllmRuntime, + type LocalModelRuntimeCleanupOptions, +} from "./cleanup"; + +type Capture = NonNullable["capture"]>; +const homes: string[] = []; +const inventoryArgs = [ + "container", + "ls", + "--all", + "--no-trunc", + "--filter", + `name=^/${HOST_LOCAL_VLLM_CONTAINER_NAME}$`, + "--format", + "{{.ID}}", +]; + +afterEach(() => { + for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); +}); + +function temporaryHome(): string { + const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-vllm-absence-"))); + homes.push(home); + return home; +} + +function privateState() { + const homeDir = temporaryHome(); + const stateDir = managedVllmStateDir(homeDir); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + const apiKey = "a".repeat(64); + const keyPath = path.join(stateDir, MANAGED_VLLM_API_KEY_FILE); + fs.writeFileSync(keyPath, `${apiKey}\n`, { mode: 0o600 }); + persistHostLocalVllmRuntimeReceipt( + { + containerId: "f".repeat(64), + authFingerprint: runtimeAuthFingerprint(apiKey), + serving: { + catalogDigest: `sha256:${"1".repeat(64)}`, + presetId: "vllm.dgx-spark-gb10.single.example", + presetDigest: `sha256:${"2".repeat(64)}`, + recipeId: "vllm.dgx-spark-gb10.single.example", + recipeDigest: `sha256:${"3".repeat(64)}`, + }, + }, + stateDir, + ); + const receiptPath = path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE); + return { + homeDir, + keyPath, + receiptPath, + keyContent: fs.readFileSync(keyPath, "utf8"), + receiptContent: fs.readFileSync(receiptPath, "utf8"), + }; +} + +const inventoryCases = [ + { + name: "unavailable", + capture: () => + vi + .fn() + .mockReturnValueOnce("") + .mockImplementationOnce(() => { + throw new Error("Docker container inventory failed"); + }), + }, + { + name: "present", + capture: () => vi.fn().mockReturnValueOnce("").mockReturnValueOnce("f".repeat(64)), + }, +] as const; + +const operations = [ + { + name: "destroy", + cleanup: retireHostLocalVllmRuntime, + refusal: { status: "preserved" }, + absent: { status: "absent" }, + }, + { + name: "uninstall", + cleanup: cleanupLocalModelRuntimes, + refusal: { ok: false }, + absent: { ok: true }, + }, +] as const; + +describe.each(operations)("$name managed vLLM absence", ({ cleanup, refusal, absent }) => { + it.each(inventoryCases)( + "preserves private state when container inventory is $name", + ({ capture: createCapture }) => { + const state = privateState(); + const capture = createCapture(); + const forceRm = vi.fn(() => ({ status: 0 }) as never); + const result = cleanup({ + homeDir: state.homeDir, + deps: { + capture, + forceRm, + run: vi.fn(() => ({ status: 0 }) as never), + }, + }); + expect(result).toMatchObject({ ...refusal, removed: [] }); + expect(forceRm).not.toHaveBeenCalled(); + expect(fs.readFileSync(state.keyPath, "utf8")).toBe(state.keyContent); + expect(fs.readFileSync(state.receiptPath, "utf8")).toBe(state.receiptContent); + expect(capture).toHaveBeenLastCalledWith(inventoryArgs, { + ignoreError: false, + timeout: 10_000, + }); + }, + ); + + it("removes private state only after an empty successful container inventory", () => { + const state = privateState(); + const capture = vi.fn().mockReturnValueOnce("").mockReturnValueOnce(""); + const forceRm = vi.fn(() => ({ status: 0 }) as never); + const result = cleanup({ + homeDir: state.homeDir, + deps: { + capture, + forceRm, + run: vi.fn(() => ({ status: 0 }) as never), + }, + }); + expect(result).toMatchObject(absent); + expect(capture).toHaveBeenLastCalledWith(inventoryArgs, { + ignoreError: false, + timeout: 10_000, + }); + expect(forceRm).not.toHaveBeenCalled(); + expect(fs.existsSync(state.keyPath)).toBe(false); + expect(fs.existsSync(state.receiptPath)).toBe(false); + }); +}); + +it.each(inventoryCases)( + "preserves bearerless retirement when container inventory is $name", + ({ capture: createCapture }) => { + const capture = createCapture(); + const forceRm = vi.fn(() => ({ status: 0 }) as never); + const result = retireHostLocalVllmRuntime({ + homeDir: temporaryHome(), + deps: { + capture, + forceRm, + run: vi.fn(() => ({ status: 0 }) as never), + }, + }); + expect(result).toMatchObject({ status: "preserved", removed: [] }); + expect(forceRm).not.toHaveBeenCalled(); + expect(capture).toHaveBeenLastCalledWith(inventoryArgs, { + ignoreError: false, + timeout: 10_000, + }); + }, +); + +it("records pending vLLM retirement without overwriting a linked host file", () => { + const home = temporaryHome(); + const stateDir = managedVllmStateDir(home); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + const unrelatedFile = path.join(home, "unrelated.json"); + fs.writeFileSync(unrelatedFile, "untouched", { mode: 0o600 }); + fs.symlinkSync(unrelatedFile, path.join(stateDir, HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE)); + + recordPendingHostLocalVllmRetirement("alpha", home); + + expect({ + unrelated: fs.readFileSync(unrelatedFile, "utf8"), + pending: readPendingHostLocalVllmRetirement(home), + }).toEqual({ unrelated: "untouched", pending: "alpha" }); +}); diff --git a/src/lib/inference/local-model-profile/cleanup.test.ts b/src/lib/inference/local-model-profile/cleanup.test.ts index 5bfa189c7b1..a33ddd54e32 100644 --- a/src/lib/inference/local-model-profile/cleanup.test.ts +++ b/src/lib/inference/local-model-profile/cleanup.test.ts @@ -42,6 +42,7 @@ import { prepareManagedLlamaCppLifecycleCleanup, prepareManagedLlamaCppRuntimeCleanupForSandbox, resolveManagedLlamaCppCleanupTarget, + retireHostLocalVllmRuntime, } from "./cleanup"; import { createManagedState, @@ -79,6 +80,306 @@ function ownedContainer( return JSON.stringify([{ Id: id, Name: `/${name}`, Config: { Env: env, Labels: labels } }]); } +describe("managed vLLM retirement after the last Local vLLM sandbox", () => { + const containerId = "f".repeat(64); + const serving = { + catalogDigest: `sha256:${"1".repeat(64)}`, + presetId: "vllm.dgx-spark-gb10.single.example", + presetDigest: `sha256:${"2".repeat(64)}`, + recipeId: "vllm.dgx-spark-gb10.single.example", + recipeDigest: `sha256:${"3".repeat(64)}`, + } as const; + + function retirementDeps( + inspection: string, + overrides: { forceRmStatus?: number; dockerStatus?: number } = {}, + ) { + const forceRm = vi.fn(() => ({ status: overrides.forceRmStatus ?? 0 }) as never); + const capture = vi.fn((argv: readonly string[]) => + argv[0] === "container" && argv[2] === HOST_LOCAL_VLLM_CONTAINER_NAME ? inspection : "", + ); + return { + capture, + forceRm, + deps: { + capture: capture as never, + forceRm: forceRm as never, + run: vi.fn(() => ({ status: overrides.dockerStatus ?? 0 }) as never), + }, + }; + } + + it("removes a bearerless managed vLLM container by its inspected ID", () => { + const homeDir = temporaryHome(); + const { deps, forceRm } = retirementDeps( + ownedContainer(HOST_LOCAL_VLLM_CONTAINER_NAME, containerId, { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + }), + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "removed", + containerId, + removed: [`container:${containerId}`], + }); + expect(forceRm).toHaveBeenCalledWith(containerId, { ignoreError: true, suppressOutput: true }); + }); + + it("reports an absent container without calling Docker removal", () => { + const homeDir = temporaryHome(); + const { deps, forceRm } = retirementDeps(""); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ status: "absent" }); + expect(forceRm).not.toHaveBeenCalled(); + }); + + it("removes a host-global key that outlives an absent container", () => { + const homeDir = temporaryHome(); + const keyPath = path.join(managedVllmStateDir(homeDir), "dual-station-vllm-api-key"); + fs.mkdirSync(path.dirname(keyPath), { mode: 0o700, recursive: true }); + fs.writeFileSync(keyPath, `${"e".repeat(64)}\n`, { mode: 0o600 }); + const { deps, forceRm } = retirementDeps(""); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ status: "absent" }); + expect(forceRm).not.toHaveBeenCalled(); + expect(fs.existsSync(keyPath)).toBe(false); + }); + + it.each<{ reason: string; labels: Record }>([ + { + reason: "the container does not carry the NemoClaw managed vLLM label", + labels: { "com.example.owner": "operator" }, + }, + { + reason: "the container belongs to a distributed vLLM runtime", + labels: { [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", "com.nvidia.nemoclaw.vllm-role": "head" }, + }, + { + reason: "the container is bearer-protected but its persisted API key is missing", + labels: { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + [HOST_LOCAL_VLLM_AUTH_LABEL]: "0".repeat(64), + }, + }, + ])("preserves the container when $reason", ({ reason, labels }) => { + const homeDir = temporaryHome(); + const { deps, forceRm } = retirementDeps( + ownedContainer(HOST_LOCAL_VLLM_CONTAINER_NAME, containerId, labels), + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "preserved", + reason, + removed: [], + }); + expect(forceRm).not.toHaveBeenCalled(); + }); + + it("preserves the container when Docker is unavailable", () => { + const homeDir = temporaryHome(); + const { deps, forceRm } = retirementDeps( + ownedContainer(HOST_LOCAL_VLLM_CONTAINER_NAME, containerId, { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + }), + { dockerStatus: 1 }, + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "preserved", + reason: "Docker is unavailable", + removed: [], + }); + expect(forceRm).not.toHaveBeenCalled(); + }); + + it("reports a failed Docker removal as a preserved container", () => { + const homeDir = temporaryHome(); + const { deps } = retirementDeps( + ownedContainer(HOST_LOCAL_VLLM_CONTAINER_NAME, containerId, { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + }), + { forceRmStatus: 1 }, + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "preserved", + reason: "Docker could not remove the container", + removed: [], + }); + }); + + it.each([ + { + label: "a host-local runtime receipt", + prepare: (stateDir: string) => + fs.writeFileSync(path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE), "{}\n", { + mode: 0o600, + }), + env: [] as string[], + }, + { + label: "a VLLM_API_KEY environment entry", + prepare: (_stateDir: string) => undefined, + env: [`VLLM_API_KEY=${"a".repeat(64)}`], + }, + ])("preserves a nominally bearerless container that retains $label", ({ prepare, env }) => { + const homeDir = temporaryHome(); + const stateDir = managedVllmStateDir(homeDir); + fs.mkdirSync(stateDir, { mode: 0o700, recursive: true }); + prepare(stateDir); + const { deps, forceRm } = retirementDeps( + ownedContainer( + HOST_LOCAL_VLLM_CONTAINER_NAME, + containerId, + { [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true" }, + env, + ), + ); + + const result = retireHostLocalVllmRuntime({ homeDir, deps }); + + expect(result).toMatchObject({ status: "preserved", removed: [] }); + expect(forceRm).not.toHaveBeenCalled(); + }); + + it("keeps the container for full uninstall while a distributed vLLM receipt exists", () => { + const homeDir = temporaryHome(); + const stateDir = managedVllmStateDir(homeDir); + fs.mkdirSync(stateDir, { mode: 0o700, recursive: true }); + fs.writeFileSync(path.join(stateDir, "dual-station-vllm-runtime.json"), "{}\n", { + mode: 0o600, + }); + const { deps, forceRm } = retirementDeps( + ownedContainer(HOST_LOCAL_VLLM_CONTAINER_NAME, containerId, { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + }), + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "kept", + reason: "a distributed vLLM receipt owns it until full uninstall", + }); + expect(forceRm).not.toHaveBeenCalled(); + }); + + it("removes an authenticated managed vLLM container with its key and receipt", () => { + const homeDir = temporaryHome(); + const stateDir = managedVllmStateDir(homeDir); + fs.mkdirSync(stateDir, { mode: 0o700, recursive: true }); + const apiKey = "e".repeat(64); + fs.writeFileSync(path.join(stateDir, "dual-station-vllm-api-key"), `${apiKey}\n`, { + mode: 0o600, + }); + persistHostLocalVllmRuntimeReceipt( + { containerId, authFingerprint: runtimeAuthFingerprint(apiKey), serving }, + stateDir, + ); + const { deps, forceRm } = retirementDeps( + ownedContainer( + HOST_LOCAL_VLLM_CONTAINER_NAME, + containerId, + { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + [HOST_LOCAL_VLLM_AUTH_LABEL]: runtimeAuthFingerprint(apiKey), + [HOST_LOCAL_VLLM_CATALOG_LABEL]: serving.catalogDigest, + [HOST_LOCAL_VLLM_PRESET_LABEL]: serving.presetId, + [HOST_LOCAL_VLLM_PRESET_DIGEST_LABEL]: serving.presetDigest, + [HOST_LOCAL_VLLM_RECIPE_LABEL]: serving.recipeId, + [HOST_LOCAL_VLLM_RECIPE_DIGEST_LABEL]: serving.recipeDigest, + }, + [`VLLM_API_KEY=${apiKey}`], + ), + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "removed", + containerId, + removed: [`container:${containerId}`], + }); + expect(forceRm).toHaveBeenCalledWith(containerId, { ignoreError: true, suppressOutput: true }); + expect(fs.existsSync(path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE))).toBe(false); + expect(fs.existsSync(path.join(stateDir, "dual-station-vllm-api-key"))).toBe(false); + }); + + it("reports partial state cleanup after removal and finishes it safely when the container is absent", () => { + const homeDir = temporaryHome(); + const stateDir = managedVllmStateDir(homeDir); + fs.mkdirSync(stateDir, { mode: 0o700, recursive: true }); + const apiKey = "e".repeat(64); + fs.writeFileSync(path.join(stateDir, "dual-station-vllm-api-key"), `${apiKey}\n`, { + mode: 0o600, + }); + persistHostLocalVllmRuntimeReceipt( + { containerId, authFingerprint: runtimeAuthFingerprint(apiKey), serving }, + stateDir, + ); + const { capture, deps } = retirementDeps( + ownedContainer( + HOST_LOCAL_VLLM_CONTAINER_NAME, + containerId, + { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + [HOST_LOCAL_VLLM_AUTH_LABEL]: runtimeAuthFingerprint(apiKey), + [HOST_LOCAL_VLLM_CATALOG_LABEL]: serving.catalogDigest, + [HOST_LOCAL_VLLM_PRESET_LABEL]: serving.presetId, + [HOST_LOCAL_VLLM_PRESET_DIGEST_LABEL]: serving.presetDigest, + [HOST_LOCAL_VLLM_RECIPE_LABEL]: serving.recipeId, + [HOST_LOCAL_VLLM_RECIPE_DIGEST_LABEL]: serving.recipeDigest, + }, + [`VLLM_API_KEY=${apiKey}`], + ), + ); + const unlink = vi + .fn<(filePath: fs.PathLike) => void>() + .mockImplementationOnce((filePath) => fs.unlinkSync(filePath)) + .mockImplementationOnce(() => { + throw new Error("permission denied"); + }); + + expect(retireHostLocalVllmRuntime({ homeDir, deps: { ...deps, unlink } })).toEqual({ + status: "partial", + containerId, + reason: `${HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE}: permission denied`, + remaining: [HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE], + removed: [`container:${containerId}`], + }); + expect(fs.existsSync(path.join(stateDir, "dual-station-vllm-api-key"))).toBe(false); + expect(fs.existsSync(path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE))).toBe(true); + + capture.mockReturnValue(""); + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ status: "absent" }); + expect(fs.existsSync(path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE))).toBe(false); + }); + + it("preserves an authenticated container whose key does not match the persisted state", () => { + const homeDir = temporaryHome(); + const stateDir = managedVllmStateDir(homeDir); + fs.mkdirSync(stateDir, { mode: 0o700, recursive: true }); + fs.writeFileSync(path.join(stateDir, "dual-station-vllm-api-key"), `${"e".repeat(64)}\n`, { + mode: 0o600, + }); + const { deps, forceRm } = retirementDeps( + ownedContainer( + HOST_LOCAL_VLLM_CONTAINER_NAME, + containerId, + { + [HOST_LOCAL_VLLM_MANAGED_LABEL]: "true", + [HOST_LOCAL_VLLM_AUTH_LABEL]: runtimeAuthFingerprint("a".repeat(64)), + }, + [`VLLM_API_KEY=${"a".repeat(64)}`], + ), + ); + + expect(retireHostLocalVllmRuntime({ homeDir, deps })).toEqual({ + status: "preserved", + reason: "host-local vLLM ownership or authentication does not match persisted state", + removed: [], + }); + expect(forceRm).not.toHaveBeenCalled(); + expect(fs.existsSync(path.join(stateDir, "dual-station-vllm-api-key"))).toBe(true); + }); +}); + describe("host-local model cleanup", () => { it("treats an absent home as no managed runtime state", () => { const homeDir = path.join(temporaryHome(), "absent-home"); diff --git a/src/lib/inference/local-model-profile/cleanup.ts b/src/lib/inference/local-model-profile/cleanup.ts index f497040fc67..ab985ae4736 100644 --- a/src/lib/inference/local-model-profile/cleanup.ts +++ b/src/lib/inference/local-model-profile/cleanup.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { writeConfigFile } from "../../state/config-io"; import type { ContainerEngine } from "../../adapters/container-engine"; import { dockerCapture, dockerForceRm, dockerRun } from "../../adapters/docker/local-model-runtime"; import { @@ -67,7 +68,11 @@ import { } from "../serving/vllm-host-local-lifecycle"; import { loadManagedVllmApiKey, managedVllmStateDir } from "../vllm-api-key"; -export { HOST_LOCAL_VLLM_CONTAINER_NAME, HOST_LOCAL_VLLM_MANAGED_LABEL }; +export { + HOST_LOCAL_VLLM_CONTAINER_NAME, + HOST_LOCAL_VLLM_MANAGED_LABEL, + HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE, +}; const LLAMA_MANAGED_LABEL = "io.nvidia.nemoclaw.host-local-inference.managed"; const LLAMA_PROVIDER_LABEL = "io.nvidia.nemoclaw.host-local-inference.provider"; @@ -89,6 +94,7 @@ interface CleanupDeps { currentUserId: number | null; forceRm: typeof dockerForceRm; run: typeof dockerRun; + unlink: typeof fs.unlinkSync; } export interface LocalModelRuntimeCleanupOptions { @@ -131,7 +137,23 @@ function inspectOwnedResource( ignoreError: true, timeout: 10_000, }).trim(); - if (!source) return { kind: "absent" }; + if (!source) { + const inventory = capture( + [ + kind, + "ls", + ...(kind === "container" ? ["--all"] : []), + "--no-trunc", + "--filter", + `name=^${kind === "container" ? "/" : ""}${name}$`, + "--format", + "{{.ID}}", + ], + { ignoreError: false, timeout: 10_000 }, + ).trim(); + if (inventory) throw new Error(`${kind} ${name} absence could not be proven`); + return { kind: "absent" }; + } let parsed: unknown; try { parsed = JSON.parse(source); @@ -174,7 +196,48 @@ function distributedReceiptPresent(stateDir: string): boolean { ); } -function cleanupHostLocalVllm(stateDir: string, deps: CleanupDeps, removed: string[]): void { +function hostLocalVllmStatePaths(stateDir: string): readonly string[] { + return [ + path.join(stateDir, MANAGED_VLLM_API_KEY_FILE), + path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE), + ]; +} + +function cleanupRetiredHostLocalVllmState( + stateDir: string, + deps: CleanupDeps, +): { ok: true } | { ok: false; reason: string; remaining: string[] } { + const failures: string[] = []; + for (const filePath of hostLocalVllmStatePaths(stateDir)) { + if (!fs.existsSync(filePath)) continue; + try { + deps.unlink(filePath); + } catch (error) { + failures.push( + `${path.basename(filePath)}: ${error instanceof Error ? error.message : String(error)}`, + ); + // The runtime receipt is last and remains durable authority whenever an + // earlier cleanup step fails. A destroy retry or later uninstall can + // finish cleanup after the container is already absent. + break; + } + } + const remaining = hostLocalVllmStatePaths(stateDir) + .filter((filePath) => fs.existsSync(filePath)) + .map((filePath) => path.basename(filePath)); + if (failures.length === 0 && remaining.length === 0) return { ok: true }; + return { + ok: false, + reason: failures.join("; ") || "private state remained after cleanup", + remaining, + }; +} + +function cleanupHostLocalVllm( + stateDir: string, + deps: CleanupDeps, + removed: string[], +): HostLocalVllmRetirementResult { const hasDistributedReceipt = distributedReceiptPresent(stateDir); const inspected = inspectOwnedResource( "container", @@ -183,7 +246,20 @@ function cleanupHostLocalVllm(stateDir: string, deps: CleanupDeps, removed: stri "true", deps.capture, ); - if (inspected.kind === "absent") return; + if (inspected.kind === "absent") { + // The key and receipt belong to this container alone; a key that outlives + // the container is a credential with no runtime. + const cleanup = cleanupRetiredHostLocalVllmState(stateDir, deps); + return cleanup.ok + ? { status: "absent" } + : { + status: "partial", + containerId: null, + reason: cleanup.reason, + remaining: cleanup.remaining, + removed, + }; + } if (inspected.kind === "foreign") { throw new Error("host-local vLLM container name is foreign while managed key state remains"); } @@ -192,7 +268,9 @@ function cleanupHostLocalVllm(stateDir: string, deps: CleanupDeps, removed: stri const authFingerprint = labels?.[HOST_LOCAL_VLLM_AUTH_LABEL]; const dualRole = labels?.["com.nvidia.nemoclaw.vllm-role"]; if (dualRole === "head" || dualRole === "worker") { - if (hasDistributedReceipt) return; + if (hasDistributedReceipt) { + return { status: "kept", reason: "distributed vLLM receipt remains" }; + } throw new Error("distributed vLLM container exists without its ownership receipt"); } const apiKey = loadManagedVllmApiKey({ stateDir }); @@ -208,17 +286,23 @@ function cleanupHostLocalVllm(stateDir: string, deps: CleanupDeps, removed: stri ) { throw new Error("host-local vLLM ownership or authentication does not match persisted state"); } - const servingIdentity = validateHostLocalVllmRuntimeReceipt( + validateHostLocalVllmRuntimeReceipt( { containerId: inspected.id, labels: labels ?? {}, authFingerprint }, stateDir, ); const removal = deps.forceRm(inspected.id, { ignoreError: true, suppressOutput: true }); if (removal.status !== 0) throw new Error("host-local vLLM container removal failed"); removed.push(`container:${inspected.id}`); - if (servingIdentity) { - fs.unlinkSync(path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE)); - } - fs.unlinkSync(path.join(stateDir, MANAGED_VLLM_API_KEY_FILE)); + const cleanup = cleanupRetiredHostLocalVllmState(stateDir, deps); + return cleanup.ok + ? { status: "removed", containerId: inspected.id, removed } + : { + status: "partial", + containerId: inspected.id, + reason: cleanup.reason, + remaining: cleanup.remaining, + removed, + }; } function requirePrivateManagedState(paths: ManagedLlamaCppStatePaths, uid: number | null): void { @@ -1363,6 +1447,7 @@ function cleanupManagedLlamaCppRuntimeForSandboxInternal( : options.deps.currentUserId, forceRm: options.deps?.forceRm ?? dockerForceRm, run: options.deps?.run ?? dockerRun, + unlink: options.deps?.unlink ?? fs.unlinkSync, }; const removed: string[] = []; const preserved: string[] = []; @@ -1413,21 +1498,151 @@ export function cleanupManagedLlamaCppRuntimeForSandbox( return cleanupManagedLlamaCppRuntimeForSandboxInternal(sandboxName, options); } -/** Remove only exact owned host-local runtime resources before uninstall deletes state. */ -export function cleanupLocalModelRuntimes( - options: LocalModelRuntimeCleanupOptions, -): LocalModelRuntimeCleanupResult { - const deps: CleanupDeps = { - capture: options.deps?.capture ?? dockerCapture, +function resolveCleanupDeps(overrides: Partial = {}): CleanupDeps { + return { + capture: overrides.capture ?? dockerCapture, currentUserId: - options.deps?.currentUserId === undefined + overrides.currentUserId === undefined ? typeof process.getuid === "function" ? process.getuid() : null - : options.deps.currentUserId, - forceRm: options.deps?.forceRm ?? dockerForceRm, - run: options.deps?.run ?? dockerRun, + : overrides.currentUserId, + forceRm: overrides.forceRm ?? dockerForceRm, + run: overrides.run ?? dockerRun, + unlink: overrides.unlink ?? fs.unlinkSync, }; +} + +const DISTRIBUTED_VLLM_LABEL_PREFIX = "com.nvidia.nemoclaw.vllm-"; + +export type HostLocalVllmRetirementResult = + | { status: "absent" } + | { status: "kept"; reason: string } + | { status: "removed"; containerId: string; removed: string[] } + | { + status: "partial"; + containerId: string | null; + reason: string; + remaining: string[]; + removed: string[]; + } + | { status: "preserved"; reason: string; removed: string[] }; + +function removeUnauthenticatedHostLocalVllm( + stateDir: string, + deps: CleanupDeps, + removed: string[], +): HostLocalVllmRetirementResult { + const inspected = inspectOwnedResource( + "container", + HOST_LOCAL_VLLM_CONTAINER_NAME, + HOST_LOCAL_VLLM_MANAGED_LABEL, + "true", + deps.capture, + ); + if (inspected.kind === "absent") return { status: "absent" }; + if (inspected.kind === "foreign") { + throw new Error("the container does not carry the NemoClaw managed vLLM label"); + } + const config = inspected.row.Config as { Env?: unknown; Labels?: unknown } | undefined; + const labels = (config?.Labels ?? {}) as Record; + if (Object.keys(labels).some((label) => label.startsWith(DISTRIBUTED_VLLM_LABEL_PREFIX))) { + throw new Error("the container belongs to a distributed vLLM runtime"); + } + if (labels[HOST_LOCAL_VLLM_AUTH_LABEL] !== undefined) { + throw new Error("the container is bearer-protected but its persisted API key is missing"); + } + const env = Array.isArray(config?.Env) ? config.Env : []; + if ( + fs.existsSync(path.join(stateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE)) || + env.some((value) => typeof value === "string" && value.startsWith("VLLM_API_KEY=")) + ) { + throw new Error("the container retains authenticated vLLM ownership evidence"); + } + const removal = deps.forceRm(inspected.id, { ignoreError: true, suppressOutput: true }); + if (removal.status !== 0) throw new Error("Docker could not remove the container"); + removed.push(`container:${inspected.id}`); + return { status: "removed", containerId: inspected.id, removed }; +} + +/** + * Retire the NemoClaw-managed single-host vLLM container once no registered + * sandbox uses it. An authenticated container must match its persisted key and + * receipt; a bearerless container must carry the managed label and no + * distributed or bearer labels. A distributed receipt keeps its container for + * full uninstall; any other container is left in place with the reason. + */ +export function retireHostLocalVllmRuntime( + options: { homeDir?: string; deps?: Partial } = {}, +): HostLocalVllmRetirementResult { + const deps = resolveCleanupDeps(options.deps); + const removed: string[] = []; + try { + const homeDir = canonicalCleanupHomeDir(options.homeDir ?? os.homedir()); + const vllmStateDir = managedVllmStateDir(homeDir); + if (distributedReceiptPresent(vllmStateDir)) { + return { status: "kept", reason: "a distributed vLLM receipt owns it until full uninstall" }; + } + if (deps.run(["info"], { ignoreError: true, suppressOutput: true }).status !== 0) { + return { status: "preserved", reason: "Docker is unavailable", removed }; + } + if ( + !fs.existsSync(path.join(vllmStateDir, MANAGED_VLLM_API_KEY_FILE)) && + !fs.existsSync(path.join(vllmStateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE)) + ) { + return removeUnauthenticatedHostLocalVllm(vllmStateDir, deps, removed); + } + return cleanupHostLocalVllm(vllmStateDir, deps, removed); + } catch (error) { + return { status: "preserved", reason: (error as Error).message, removed }; + } +} + +export const HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE = + "host-local-vllm-pending-retirement.json" as const; + +function pendingHostLocalVllmRetirementPath(homeDir: string | undefined): string { + return path.join( + managedVllmStateDir(canonicalCleanupHomeDir(homeDir ?? os.homedir())), + HOST_LOCAL_VLLM_PENDING_RETIREMENT_FILE, + ); +} + +/** + * Record that a destroyed Local vLLM sandbox leaves the host-global container + * without a registry row. The row is the only proof that the sandbox used the + * container, so a destroy retry after an interrupted or preserved retirement + * reads this record instead. + */ +export function recordPendingHostLocalVllmRetirement(sandboxName: string, homeDir?: string): void { + const filePath = pendingHostLocalVllmRetirementPath(homeDir); + writeConfigFile(filePath, { sandboxName }); +} + +/** Sandbox name whose managed vLLM retirement is pending, or null. */ +export function readPendingHostLocalVllmRetirement(homeDir?: string): string | null { + try { + const parsed = JSON.parse( + fs.readFileSync(pendingHostLocalVllmRetirementPath(homeDir), "utf-8"), + ) as { sandboxName?: unknown } | null; + return typeof parsed?.sandboxName === "string" && parsed.sandboxName !== "" + ? parsed.sandboxName + : null; + } catch { + return null; + } +} + +/** One settled retirement decision covers the single host-global container, whichever sandbox recorded it. */ +export function clearPendingHostLocalVllmRetirement(homeDir?: string): void { + fs.rmSync(pendingHostLocalVllmRetirementPath(homeDir), { force: true }); +} + +/** Remove only exact owned host-local runtime resources before uninstall deletes state. */ +export function cleanupLocalModelRuntimes( + options: LocalModelRuntimeCleanupOptions, +): LocalModelRuntimeCleanupResult { + const deps = resolveCleanupDeps(options.deps); const removed: string[] = []; const preserved: string[] = []; try { @@ -1438,7 +1653,8 @@ export function cleanupLocalModelRuntimes( requirePrivateManagedState(llamaPaths, deps.currentUserId); } const vllmStateRequiresDocker = - fs.existsSync(path.join(vllmStateDir, MANAGED_VLLM_API_KEY_FILE)) && + (fs.existsSync(path.join(vllmStateDir, MANAGED_VLLM_API_KEY_FILE)) || + fs.existsSync(path.join(vllmStateDir, HOST_LOCAL_VLLM_RUNTIME_RECEIPT_FILE))) && !distributedReceiptPresent(vllmStateDir); if (vllmStateRequiresDocker) { const dockerReady = @@ -1446,7 +1662,12 @@ export function cleanupLocalModelRuntimes( if (!dockerReady) { throw new Error("Docker is unavailable while host-local vLLM ownership state remains"); } - cleanupHostLocalVllm(vllmStateDir, deps, removed); + const vllmCleanup = cleanupHostLocalVllm(vllmStateDir, deps, removed); + if (vllmCleanup.status === "partial") { + throw new Error( + `host-local vLLM private state cleanup is incomplete: ${vllmCleanup.reason}`, + ); + } } if (statePathExists(llamaPaths.stateDir)) { cleanupLlamaCpp(homeDir, deps, removed, { diff --git a/src/lib/inference/local.test.ts b/src/lib/inference/local.test.ts index 8243cda82fc..0563fc5b6e4 100644 --- a/src/lib/inference/local.test.ts +++ b/src/lib/inference/local.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; // Import source directly so tests cannot pass against a stale build. +import { VLLM_PORT } from "../core/ports"; import { OLLAMA_MODEL_REGISTRY } from "./ollama-model-registry"; // Derive the "large enough to fit every registry entry" memory threshold @@ -608,6 +609,60 @@ describe("local inference helpers", () => { expect(result?.ok).toBe(expected); }); + it("probes the host port recorded in the sandbox route for a bearerless local vLLM server", () => { + const probedEndpoints: string[] = []; + + const result = probeLocalProviderHealth("vllm-local", { + recordedEndpointUrl: "http://host.openshell.internal:46145/v1", + runCurlProbeImpl: (argv) => { + probedEndpoints.push(argv.at(-1) ?? ""); + return { + ok: true, + httpStatus: 200, + curlStatus: 0, + body: '{"data":[]}', + stderr: "", + message: "HTTP 200", + }; + }, + }); + + expect(result?.ok).toBe(true); + expect(result?.endpoint).toBe("http://127.0.0.1:46145/v1/models"); + expect(probedEndpoints).toEqual(["http://127.0.0.1:46145/v1/models"]); + }); + + it.each([ + { endpoint: null, reason: "no recorded route" }, + { endpoint: "https://inference.local/v1", reason: "an in-sandbox route" }, + { endpoint: "http://host.openshell.internal/v1", reason: "no port" }, + { endpoint: "http://host.openshell.internal:80/v1", reason: "a privileged port" }, + { endpoint: "http://example.com:46145/v1", reason: "a foreign host" }, + { endpoint: "http://user:secret@host.openshell.internal:46145/v1", reason: "userinfo" }, + { endpoint: "http://host.openshell.internal:46145/v1?probe=1", reason: "a query string" }, + { endpoint: "http://host.openshell.internal:46145/v1#probe", reason: "a fragment" }, + { endpoint: "http://host.openshell.internal:46145/v1/chat", reason: "a non-route path" }, + { endpoint: "http://host.openshell.internal:46145/v1/", reason: "a non-canonical path" }, + { endpoint: "not a url", reason: "a malformed URL" }, + ])( + "keeps the configured local vLLM port when the recorded route has $reason", + ({ endpoint: recordedEndpointUrl }) => { + const result = probeLocalProviderHealth("vllm-local", { + recordedEndpointUrl, + runCurlProbeImpl: () => ({ + ok: false, + httpStatus: 0, + curlStatus: 7, + body: "", + stderr: "Failed to connect", + message: "curl failed (exit 7)", + }), + }); + + expect(result?.endpoint).toBe(`http://127.0.0.1:${VLLM_PORT}/v1/models`); + }, + ); + it("reports a clear local provider outage when the host probe cannot connect", () => { const result = probeLocalProviderHealth("ollama-local", { runCurlProbeImpl: () => ({ diff --git a/src/lib/inference/local.ts b/src/lib/inference/local.ts index b54a1c0325e..f0a550fed99 100644 --- a/src/lib/inference/local.ts +++ b/src/lib/inference/local.ts @@ -811,6 +811,40 @@ export interface LocalProviderHealthProbeOptions { getManagedVllmBaseUrlImpl?: ManagedStationVllmBaseUrlResolver; /** Recovers a receipt-owned managed cluster endpoint. */ recoverManagedClusterVllmEndpointImpl?: ManagedClusterVllmEndpointResolver; + /** + * Sandbox route endpoint recorded at onboard. A bearerless managed vLLM + * container leaves no receipt, so this URL is the only durable record of + * the host port that a NEMOCLAW_VLLM_PORT override selected. + */ + recordedEndpointUrl?: string | null; +} + +/** + * Host port from a recorded local vLLM route such as + * `http://host.openshell.internal:/v1`, or null when the URL does not + * name a usable one. + */ +export function recordedLocalVllmHostPort(endpointUrl: string | null | undefined): number | null { + if (!endpointUrl) return null; + let parsed: URL; + try { + parsed = new URL(endpointUrl); + } catch { + return null; + } + if ( + parsed.protocol !== "http:" || + parsed.hostname !== "host.openshell.internal" || + parsed.username || + parsed.password || + parsed.pathname !== "/v1" || + parsed.search || + parsed.hash + ) { + return null; + } + const port = Number(parsed.port); + return Number.isSafeInteger(port) && port >= 1024 && port <= 65_535 ? port : null; } function defaultLoadOllamaProxyToken(): string | null { @@ -1522,7 +1556,7 @@ export function probeLocalProviderHealth( const endpoint = managedValidationBaseUrl ? `${managedValidationBaseUrl}/models` : provider === "vllm-local" - ? `http://127.0.0.1:${VLLM_PORT}/v1/models` + ? `http://127.0.0.1:${recordedLocalVllmHostPort(options.recordedEndpointUrl) ?? VLLM_PORT}/v1/models` : getLocalProviderHealthEndpoint(provider); if (!endpoint) return null; diff --git a/test/e2e/README.md b/test/e2e/README.md index 4c12d14efb2..ff917af5da2 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1624,6 +1624,19 @@ Validate phase coverage without executing test bodies with: npm run test:e2e-phases:check ``` +### Managed vLLM final-consumer lifecycle + +The existing `gpu-e2e` target runs its managed vLLM case twice. Each cycle onboards +the supported fixed profile on port 18000, exports its configuration, then checks +status, doctor, and connect with the port override cleared. Normal cleanup destroys +the final sandbox and checks actual container and listener absence before any +fixture fallback cleanup. The second cycle proves that onboarding can reacquire +the released GPU resources. + +Source tests own shared-consumer retention, receipt ownership, invalid recorded +routes, and interrupted-cleanup recovery. The physical Spark Express test retains +its existing platform-specific qualification. + ### DGX Spark Express vLLM `spark-express-vllm.test.ts` is a physical-host qualification for the second DGX Spark Express inference option, the catalog-backed fixed vLLM profile. diff --git a/test/e2e/live/gpu-e2e.test.ts b/test/e2e/live/gpu-e2e.test.ts index 0e01ecbc9c9..08f0f7321df 100644 --- a/test/e2e/live/gpu-e2e.test.ts +++ b/test/e2e/live/gpu-e2e.test.ts @@ -5,10 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { EXPORTED_VLLM_PROFILE_ID } from "../../../src/lib/config/model.ts"; -import type { - V1Alpha1OllamaProxyService, - V1Alpha1VllmService, -} from "../../../src/lib/config/v1alpha1-export.ts"; +import type { V1Alpha1OllamaProxyService } from "../../../src/lib/config/v1alpha1-export.ts"; import { cleanupLocalModelRuntimes } from "../../../src/lib/inference/local-model-profile/cleanup.ts"; import { HOST_LOCAL_VLLM_CONTAINER_NAME } from "../../../src/lib/inference/serving/vllm-host-local-lifecycle.ts"; import { loadManagedVllmApiKey } from "../../../src/lib/inference/vllm-api-key.ts"; @@ -154,19 +151,14 @@ test( await artifacts.writeText("install-gpu-ollama.log", resultText(install)); progress.phase("validate GPU runtime status"); - const status = await host.command("node", [CLI, SANDBOX_NAME, "status"], { + await host.command("node", [CLI, SANDBOX_NAME, "status"], { artifactName: "status-gpu-ollama", env: env(), timeoutMs: 120_000, }); - expect(resultText(status)).toContain("Sandbox GPU: enabled"); - expect(resultText(status)).toContain("CUDA verified"); const installLog = resultText(install); assertGpuInstallProofs(installLog); - expect(installLog).not.toMatch( - /Recreating OpenShell Docker sandbox container with NVIDIA GPU access|Docker GPU mode selected/u, - ); const sandboxContainers = await runtimeProvider.command( [ @@ -311,7 +303,6 @@ exit 1`, { artifactName: "ollama-daemon-restart-unloaded", env: env(), timeoutMs: 90_000 }, ); const restartLines = restart.stdout.trim().split("\n"); - expect(restartLines[0]).toMatch(/^restart_mode=(system|user|manual)$/u); expect(loadedOllamaModels(restartLines.slice(1).join("\n"))).toEqual([]); const recovered = await host.nemoclaw( @@ -558,7 +549,6 @@ exec ollama pull qwen2.5:0.5b`, const firstYaml = fs.readFileSync(firstPath, "utf8"); const first = parseConfigExport(firstYaml); const service = first.spec.services?.["ollama-auth"] as V1Alpha1OllamaProxyService | undefined; - expect(service?.image).toBeNull(); expect(service?.upstream.model.digest).toBe(model!.digest.replace(/^sha256:/u, "")); const proxyToken = readTokenFileChecked(ollamaProxyTokenFile()).token; artifacts.addRedactionValues([proxyToken]); @@ -570,8 +560,8 @@ exec ollama pull qwen2.5:0.5b`, }, ); -test( - "OpenClaw exports the fixed managed vLLM profile through a named service (#12012)", +test.for(["initial", "after retirement"])( + "Managed vLLM %s: recorded-port health, export, and final-consumer retirement (#12012, #11374)", { timeout: VLLM_EXPORT_TIMEOUT_MS, meta: { @@ -579,12 +569,13 @@ test( "qualify the managed vLLM export host", "onboard the fixed managed vLLM profile", "export the managed vLLM configuration", + "verify the recorded custom port without the onboarding override", ], }, }, - async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox }) => { + async (cycle, { artifacts, cleanup, host, progress, runtimeProvider, sandbox }) => { const exportEnv = vllmExportEnv(); - let managedVllmOnboarded = false; + const statusEnv = { ...exportEnv, NEMOCLAW_VLLM_PORT: "" }; await artifacts.target.declare({ id: "gpu-e2e", boundary: @@ -592,6 +583,7 @@ test( credentialBoundary: "The managed vLLM bearer key remains in owner-only host state and is registered with the artifact redactor before evidence publication.", profileId: EXPORTED_VLLM_PROFILE_ID, + cycle, sandboxName: SANDBOX_NAME, }); @@ -615,15 +607,40 @@ test( ).toMatch(/^1\n[\s\S]*no such (?:object|container)/iu); await cleanupGpu(host, sandbox); - cleanup.trackDisposable("remove the exact managed vLLM runtime", () => { - const result = cleanupLocalModelRuntimes({ env: exportEnv, sandboxName: SANDBOX_NAME }); - expect( - result.ok && - (!managedVllmOnboarded || - result.removed.some((resource) => resource.startsWith("container:"))), - JSON.stringify(result), - ).toBe(true); + cleanup.trackDisposable("verify final-consumer vLLM retirement", async () => { + try { + const remaining = await host.command( + "docker", + [ + "container", + "ls", + "--all", + "--quiet", + "--filter", + `name=^/${HOST_LOCAL_VLLM_CONTAINER_NAME}$`, + ], + { artifactName: "vllm-retired-inventory", env: exportEnv, timeoutMs: 30_000 }, + ); + const listener = await host.command("ss", ["-H", "-ltn", "sport = :18000"], { + artifactName: "vllm-retired-listener", + env: exportEnv, + timeoutMs: 30_000, + }); + expect( + { + inventoryExit: remaining.exitCode, + containers: remaining.stdout.trim(), + listenerExit: listener.exitCode, + listeners: listener.stdout.trim(), + }, + `${resultText(remaining)}\n${resultText(listener)}`, + ).toEqual({ inventoryExit: 0, containers: "", listenerExit: 0, listeners: "" }); + } finally { + // Preserve failed retirement evidence before the fixture attempts best-effort cleanup. + cleanupLocalModelRuntimes({ env: exportEnv, sandboxName: SANDBOX_NAME }); + } }); + cleanup.trackGateway(host, "nemoclaw", { artifactName: "vllm-export-cleanup-gateway", env: exportEnv, @@ -662,7 +679,6 @@ test( }, ); expect(onboard.exitCode, resultText(onboard)).toBe(0); - managedVllmOnboarded = true; const apiKey = loadManagedVllmApiKey(); artifacts.addRedactionValues([apiKey ?? ""]); @@ -684,10 +700,45 @@ test( ); expect(exported.exitCode, resultText(exported)).toBe(0); const yaml = fs.readFileSync(outputPath, "utf8"); - const document = parseConfigExport(yaml); - const service = document.spec.services?.vllm as V1Alpha1VllmService | undefined; - expect(service?.image).toBeNull(); + parseConfigExport(yaml); expect(apiKey && yaml.includes(apiKey)).toBe(false); await artifacts.writeText("vllm-config-export.yaml", yaml); + + progress.phase("verify the recorded custom port without the onboarding override"); + const status = await host.command("node", [CLI, SANDBOX_NAME, "status", "--json"], { + artifactName: "vllm-recorded-port-status", + cwd: REPO_ROOT, + env: statusEnv, + timeoutMs: 180_000, + }); + const health = JSON.parse(status.stdout) as { + inferenceHealth: { subprobes: Array<{ endpoint: string; ok: boolean }> }; + }; + expect( + health.inferenceHealth.subprobes.find( + (probe) => probe.endpoint === "http://127.0.0.1:18000/v1/models", + )?.ok, + ).toBe(true); + const doctor = await host.command("node", [CLI, SANDBOX_NAME, "doctor", "--json"], { + artifactName: "vllm-recorded-port-doctor", + cwd: REPO_ROOT, + env: statusEnv, + timeoutMs: 180_000, + }); + const diagnosis = JSON.parse(doctor.stdout) as { + checks: Array<{ detail: string; status: string }>; + }; + expect( + diagnosis.checks.find( + (check) => check.detail === "http://127.0.0.1:18000/v1/models reachable", + )?.status, + ).toBe("ok"); + const connect = await host.command("node", [CLI, SANDBOX_NAME, "connect", "--probe-only"], { + artifactName: "vllm-recorded-port-connect", + cwd: REPO_ROOT, + env: statusEnv, + timeoutMs: 300_000, + }); + expect(connect.exitCode, resultText(connect)).toBe(0); }, ); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 8a63a42a0b0..1dc1da56c3f 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -604,7 +604,14 @@ "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/workflow-plan.test.ts", - "test/helpers/e2e-answer-assertions.test.ts" + "test/helpers/e2e-answer-assertions.test.ts", + "src/lib/actions/sandbox/connect-route-repair.test.ts", + "src/lib/actions/sandbox/destroy-managed-vllm-flow.test.ts", + "src/lib/actions/sandbox/destroy-managed-vllm.test.ts", + "src/lib/actions/sandbox/doctor-inference.test.ts", + "src/lib/actions/sandbox/status.test.ts", + "src/lib/inference/local.test.ts", + "src/lib/inference/local-model-profile/cleanup-vllm-absence.test.ts" ] }, { diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 2624b762811..6b4867f145d 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -40,8 +40,13 @@ export type DestroyHarness = { gatewayPinsAtSandboxList: Array; killStaleProxySpy: MockInstance; lifecycleLockEvents: string[]; + listHostGatewayRegistryEntriesSpy: MockInstance; logSpy: MockInstance; mcpRuntimeSelectionSpy: MockInstance; + /** In-memory pending managed vLLM retirement record; null when none is recorded. */ + pendingVllmRetirement: { sandboxName: string | null }; + clearPendingVllmRetirementSpy: MockInstance; + recordPendingVllmRetirementSpy: MockInstance; prepareMcpBridgesForAbsentSandboxDestroySpy: MockInstance; prepareMcpBridgesForDestroySpy: MockInstance; prepareManagedLlamaCppRuntimeCleanupSpy: MockInstance; @@ -53,6 +58,7 @@ export type DestroyHarness = { reconstructRetainedSandboxRecoverySpy: MockInstance; resolveRetainedSandboxRecoverySpy: MockInstance; resolveGatewayRuntimeProviderIdSpy: MockInstance; + retireHostLocalVllmRuntimeSpy: MockInstance; retireRemovedImmutabilityStateRecordSpy: MockInstance; retirePortableLifecycleReceiptSpy: MockInstance; portableDestroyRevalidateSpy: MockInstance; @@ -79,6 +85,7 @@ export type DestroyHarness = { updateSessionSpy: MockInstance; warnSpy: MockInstance; withGatewayRouteMutationLockSpy: MockInstance; + withCurrentPortableHostFenceSpy: MockInstance; withModelRouterPortLifecycleLockSpy: MockInstance; }; @@ -123,6 +130,7 @@ type DestroyHarnessOptions = { workspace: string; }; openshellDriver?: string; + pendingVllmRetirement?: string; portableCommandError?: string; portableDestroyAuthority?: boolean; portableDestroyPrepareError?: string; @@ -227,6 +235,12 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const portableHostFence = requireSource( + "../../state/portable-uninstall-retirement.js", + ) as typeof import("../../src/lib/state/portable-uninstall-retirement"); + const withCurrentPortableHostFenceSpy = vi + .spyOn(portableHostFence, "withCurrentPortableHostFence") + .mockImplementation(async (operation) => await operation()); const resolve = requireSource("../../adapters/openshell/resolve.js"); const runtime = requireSource("../../adapters/openshell/runtime.js"); @@ -300,7 +314,6 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr } }, ); - const executeSandboxDestroySpy = vi.spyOn(destroyExecution, "executeSandboxDestroy"); if (options.executeSandboxDestroyResult) { executeSandboxDestroySpy.mockResolvedValue(options.executeSandboxDestroyResult); @@ -425,7 +438,26 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr .mockImplementation(async (_port: unknown, operation: unknown) => (operation as () => Promise)(), ); - vi.spyOn(gatewayRegistry, "listHostGatewayRegistryEntries").mockReturnValue([]); + const listHostGatewayRegistryEntriesSpy = vi + .spyOn(gatewayRegistry, "listHostGatewayRegistryEntries") + .mockReturnValue([]); + const retireHostLocalVllmRuntimeSpy = vi + .spyOn(localModelProfileCleanup, "retireHostLocalVllmRuntime") + .mockReturnValue({ status: "absent" }); + const pendingVllmRetirement = { sandboxName: options.pendingVllmRetirement ?? null }; + const recordPendingVllmRetirementSpy = vi + .spyOn(localModelProfileCleanup, "recordPendingHostLocalVllmRetirement") + .mockImplementation((sandboxName: unknown) => { + pendingVllmRetirement.sandboxName = String(sandboxName); + }); + vi.spyOn(localModelProfileCleanup, "readPendingHostLocalVllmRetirement").mockImplementation( + () => pendingVllmRetirement.sandboxName, + ); + const clearPendingVllmRetirementSpy = vi + .spyOn(localModelProfileCleanup, "clearPendingHostLocalVllmRetirement") + .mockImplementation(() => { + pendingVllmRetirement.sandboxName = null; + }); vi.spyOn(modelRouterProcess, "doesModelRouterProcessOwnPort").mockReturnValue(false); vi.spyOn(modelRouterProcess, "inspectModelRouterProcessForPort").mockReturnValue({ status: "absent", @@ -746,8 +778,12 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr gatewayPinsAtSandboxList, killStaleProxySpy, lifecycleLockEvents, + listHostGatewayRegistryEntriesSpy, logSpy, mcpRuntimeSelectionSpy, + pendingVllmRetirement, + clearPendingVllmRetirementSpy, + recordPendingVllmRetirementSpy, prepareMcpBridgesForAbsentSandboxDestroySpy, prepareMcpBridgesForDestroySpy, prepareManagedLlamaCppRuntimeCleanupSpy, @@ -761,6 +797,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr reconstructRetainedSandboxRecoverySpy, resolveRetainedSandboxRecoverySpy, resolveGatewayRuntimeProviderIdSpy, + retireHostLocalVllmRuntimeSpy, retireRemovedImmutabilityStateRecordSpy, retirePortableLifecycleReceiptSpy, revokeHttpsPinRuntimeAdapterRouteSpy, @@ -790,6 +827,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr updateSessionSpy, warnSpy, withGatewayRouteMutationLockSpy, + withCurrentPortableHostFenceSpy, withModelRouterPortLifecycleLockSpy, }; } diff --git a/test/platform/images/protected-managed-image-contract.test.ts b/test/platform/images/protected-managed-image-contract.test.ts index bdf50ac5a65..96f4c1c5bef 100644 --- a/test/platform/images/protected-managed-image-contract.test.ts +++ b/test/platform/images/protected-managed-image-contract.test.ts @@ -80,6 +80,16 @@ function runBaseResolution(jobId: string, stepName: string) { mkdirSync(fakeBin); mkdirSync(runnerTemp); writeFileSync(outputPath, ""); + writeFileSync( + path.join(fixture, "prepared-inputs"), + [ + HEAD_SHA, + "linux/amd64", + `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, + `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, + DCODE_BASE_REF, + ].join(" ") + "\n", + ); writeFileSync( path.join(fixture, "agents", "hermes", "Dockerfile"), `ARG BASE_IMAGE=${REVIEWED_HERMES_INDEX}\n`, @@ -124,11 +134,14 @@ printf '%s %s\n' "$digest" "$1" encoding: "utf8", env: { ...process.env, + CHECKOUT_SHA: HEAD_SHA, DCODE_BASE_CONTRACT: JSON.stringify({ platformReferences: { "linux/amd64": DCODE_BASE_REF }, }), DCODE_BASE_REF, GITHUB_OUTPUT: outputPath, + HERMES_BASE_REF: `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE: fixture, PATH: `${fakeBin}:${process.env.PATH ?? ""}`, PLATFORM: "linux/amd64", RUNNER_TEMP: runnerTemp, diff --git a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts index 473009af679..a93a2795cdb 100644 --- a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts +++ b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts @@ -301,18 +301,33 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "Resolve digest-pinned amd64 runtime base images", ); requireValues(errors, `${JOB_ID} runtime base env`, record(bases?.env), { + CHECKOUT_SHA: "${{ inputs.checkout_sha || github.sha }}", DCODE_BASE_REF: "${{ needs.base-image-publication.outputs.dcode_base_ref }}", + HERMES_BASE_REF: + "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }}", }); requireFragments(errors, bases, [ - 'docker buildx imagetools inspect "$alias" --raw', - '.platform.os == "linux" and .platform.architecture == "amd64"', - 'reference="${repository}@${digest}"', - '"sha256:$(sha256sum "$exact_raw" | awk \'{print $1}\')" == "$digest"', - "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", + 'prepared_inputs="$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/prepared-inputs"', + '[[ -f "$prepared_inputs" && ! -L "$prepared_inputs" ]]', + 'read -r cached_revision cached_platform cached_openclaw cached_hermes cached_dcode extra < "$prepared_inputs"', + '[[ -z "$extra" &&', + '"$cached_revision" == "$CHECKOUT_SHA"', + '"$cached_platform" == "linux/amd64"', + '"$cached_hermes" == "$HERMES_BASE_REF"', + '"$cached_dcode" == "$DCODE_BASE_REF"', + '"$(cat "$prepared_inputs")" == "$cached_revision $cached_platform $cached_openclaw $cached_hermes $cached_dcode"', + '[[ "$cached_openclaw" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]]', + 'openclaw_digest="${cached_openclaw##*@}"', + 'docker buildx imagetools inspect "$cached_openclaw" --raw > "$work_dir/openclaw-exact.raw"', + '"sha256:$(sha256sum "$work_dir/openclaw-exact.raw" | awk \'{print $1}\')" == "$openclaw_digest"', + 'printf \'openclaw=%s\\n\' "$cached_openclaw" >> "$GITHUB_OUTPUT"', 'docker buildx imagetools inspect "$DCODE_BASE_REF" --raw', 'dcode_digest="${DCODE_BASE_REF##*@}"', 'printf \'dcode=%s\\n\' "$DCODE_BASE_REF" >> "$GITHUB_OUTPUT"', ]); + if (text(bases?.run).includes("ghcr.io/nvidia/nemoclaw/sandbox-base:latest")) { + errors.push(`${JOB_ID} must reuse the OpenClaw base from the prepared build cache`); + } if (text(bases?.run).includes("langchain-deepagents-code-sandbox-base:latest")) { errors.push(`${JOB_ID} must not resolve the DCode base from a mutable alias`); } diff --git a/tools/e2e/standard-profile-workflow-boundary.mts b/tools/e2e/standard-profile-workflow-boundary.mts index 4ea1ba4ff3a..700f0ea2efc 100644 --- a/tools/e2e/standard-profile-workflow-boundary.mts +++ b/tools/e2e/standard-profile-workflow-boundary.mts @@ -338,12 +338,14 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi "Initialize runner comparison telemetry", "Install OpenShell CLI", "Install OpenShell CLI without workflow credentials", + "Prepare GPU launch-readiness runtime directory", "Run catalogue E2E target", "Finalize runner comparison telemetry", "Write E2E evidence manifest", "Upload skill-agent artifacts", "Upload E2E artifacts", "Restore Docker CLI after native Podman E2E", + "Restore GPU launch-readiness runtime directory", "Clean up Docker auth", ]; if ( @@ -606,6 +608,50 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi ); } + const gpuRuntime = requireStep( + errors, + workflowSteps, + "Prepare GPU launch-readiness runtime directory", + ); + const gpuRuntimeScript = [ + "set -euo pipefail", + 'uid="$(/usr/bin/id -u)"', + 'unit="user@${uid}.service"', + 'prior_state="$(/usr/bin/systemctl show "$unit" --property=ActiveState --value)"', + 'if [[ "$prior_state" != "active" ]]; then', + ' [[ "$prior_state" == "inactive" ]]', + " printf 'started=true\\n' >> \"$GITHUB_OUTPUT\"", + ' /usr/bin/sudo -n /usr/bin/systemctl start "$unit"', + "fi", + '/usr/bin/systemctl is-active --quiet "$unit"', + 'runtime_directory="/run/user/$uid"', + '[[ -d "$runtime_directory" && ! -L "$runtime_directory" ]]', + '[[ "$(/usr/bin/stat -c \'%u:%a\' "$runtime_directory")" == "${uid}:700" ]]', + ].join("\n"); + const restoreGpuRuntime = requireStep( + errors, + workflowSteps, + "Restore GPU launch-readiness runtime directory", + ); + const restoreGpuRuntimeScript = [ + "set -euo pipefail", + 'uid="$(/usr/bin/id -u)"', + '/usr/bin/sudo -n /usr/bin/systemctl stop "user@${uid}.service"', + ].join("\n"); + if ( + gpuRuntime?.id !== "gpu_runtime_directory" || + gpuRuntime.if !== + "${{ inputs.catalogue_id == 'gpu-e2e' && inputs.runtime_provider == 'docker' }}" || + gpuRuntime.shell !== "/bin/bash --noprofile --norc -e -o pipefail {0}" || + String(gpuRuntime.run).trim() !== gpuRuntimeScript || + restoreGpuRuntime?.if !== + "${{ always() && inputs.catalogue_id == 'gpu-e2e' && inputs.runtime_provider == 'docker' && steps.gpu_runtime_directory.outputs.started == 'true' }}" || + restoreGpuRuntime.shell !== "/bin/bash --noprofile --norc -e -o pipefail {0}" || + String(restoreGpuRuntime.run).trim() !== restoreGpuRuntimeScript + ) { + errors.push("GPU E2E must prepare and restore only its OS-managed user runtime directory"); + } + const execute = requireStep(errors, workflowSteps, "Run catalogue E2E target"); const executeEnv = record(execute?.env); if (